Skip to content

Commit

Permalink
fix: Span.trim_remainder gave incorrect result if after was incom…
Browse files Browse the repository at this point in the history
…plete subset of `self` (#147)
  • Loading branch information
scouten authored Oct 28, 2024
1 parent 895deed commit 1de7004
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/span/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,13 @@ impl<'src> Span<'src> {
///
/// Note that the trailing remainder condition is not enforced.
pub(crate) fn trim_remainder(self, after: Span<'src>) -> Span<'src> {
// Sanity check: If after is longer than source, we can't trim.
let rlen = after.len();
let slen = self.len();
let offset = (self.offset + self.len()).min(after.offset);

if rlen >= slen {
if offset <= self.offset {
// Invalid input: We'll respond with an empty slice.
self.slice(0..0)
} else {
let trim_len = slen - rlen;
let trim_len = offset - self.offset;
self.slice(0..trim_len)
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/tests/span/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,4 +567,21 @@ mod trim_remainder {
}
);
}

#[test]
fn rem_is_incomplete_subset_of_source() {
let source = Span::new("abc\ndef\n");
let line1 = source.take_normalized_line();
let line2 = line1.after.take_line();

assert_eq!(
source.trim_remainder(line2.item),
TSpan {
data: "abc\n",
line: 1,
col: 1,
offset: 0
}
);
}
}

0 comments on commit 1de7004

Please sign in to comment.