Skip to content

Commit d316eba

Browse files
committed
Add opt_span_before() to SpanUtils trait
With some refactorings to avoid duplicated code.
1 parent 64d8384 commit d316eba

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/codemap.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub trait SpanUtils {
2222
fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
2323
fn span_before(&self, original: Span, needle: &str) -> BytePos;
2424
fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos>;
25+
fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos>;
2526
}
2627

2728
pub trait LineRangeUtils {
@@ -35,10 +36,7 @@ pub trait LineRangeUtils {
3536

3637
impl<'a> SpanUtils for SnippetProvider<'a> {
3738
fn span_after(&self, original: Span, needle: &str) -> BytePos {
38-
let snippet = self.span_to_snippet(original).expect("Bad snippet");
39-
let offset = snippet.find_uncommented(needle).expect("Bad offset") + needle.len();
40-
41-
original.lo() + BytePos(offset as u32)
39+
self.opt_span_after(original, needle).expect("bad span")
4240
}
4341

4442
fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
@@ -53,15 +51,17 @@ impl<'a> SpanUtils for SnippetProvider<'a> {
5351
}
5452

5553
fn span_before(&self, original: Span, needle: &str) -> BytePos {
56-
let snippet = self.span_to_snippet(original).unwrap();
57-
let offset = snippet.find_uncommented(needle).unwrap();
58-
59-
original.lo() + BytePos(offset as u32)
54+
self.opt_span_before(original, needle).expect("bad span")
6055
}
6156

6257
fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
58+
self.opt_span_before(original, needle)
59+
.map(|bytepos| bytepos + BytePos(needle.len() as u32))
60+
}
61+
62+
fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos> {
6363
let snippet = self.span_to_snippet(original)?;
64-
let offset = snippet.find_uncommented(needle)? + needle.len();
64+
let offset = snippet.find_uncommented(needle)?;
6565

6666
Some(original.lo() + BytePos(offset as u32))
6767
}

0 commit comments

Comments
 (0)