Add Span::trim_end

This is the counterpart of `Span::trim_start`.
This commit is contained in:
Zalathar 2024-06-03 17:00:10 +10:00
parent e609c9b254
commit df96cba432
2 changed files with 26 additions and 0 deletions

View File

@ -682,6 +682,13 @@ pub fn trim_start(self, other: Span) -> Option<Span> {
if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
}
/// Returns `Some(span)`, where the end is trimmed by the start of `other`.
pub fn trim_end(self, other: Span) -> Option<Span> {
let span = self.data();
let other = other.data();
if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
}
/// Returns the source span -- this is either the supplied span, or the span for
/// the macro callsite that expanded to it.
pub fn source_callsite(self) -> Span {

View File

@ -61,6 +61,25 @@ fn test_trim() {
// The resulting span's context should be that of `self`, not `other`.
let other = span(start, end).with_ctxt(SyntaxContext::from_u32(999));
// Test cases for `trim_end`.
assert_eq!(span(well_before, before).trim_end(other), Some(span(well_before, before)));
assert_eq!(span(well_before, start).trim_end(other), Some(span(well_before, start)));
assert_eq!(span(well_before, mid).trim_end(other), Some(span(well_before, start)));
assert_eq!(span(well_before, end).trim_end(other), Some(span(well_before, start)));
assert_eq!(span(well_before, after).trim_end(other), Some(span(well_before, start)));
assert_eq!(span(start, mid).trim_end(other), None);
assert_eq!(span(start, end).trim_end(other), None);
assert_eq!(span(start, after).trim_end(other), None);
assert_eq!(span(mid, end).trim_end(other), None);
assert_eq!(span(mid, after).trim_end(other), None);
assert_eq!(span(end, after).trim_end(other), None);
assert_eq!(span(after, well_after).trim_end(other), None);
// Test cases for `trim_start`.
assert_eq!(span(after, well_after).trim_start(other), Some(span(after, well_after)));