Skip to content

Commit

Permalink
feat(offsets): utility function for converting from line/col to offset
Browse files Browse the repository at this point in the history
  • Loading branch information
zkat committed Aug 18, 2021
1 parent 9520036 commit 75c2312
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,31 @@ impl SourceOffset {
pub fn offset(&self) -> ByteOffset {
self.0
}

/// Little utility to help convert line/column locations into
/// miette-compatible Spans
///
/// This function is infallible: Giving an out-of-range line/column pair
/// will return the offset of the last byte in the source.
pub fn from_location(source: impl AsRef<str>, loc_line: usize, loc_col: usize) -> Self {
let mut line = 0usize;
let mut col = 0usize;
let mut offset = 0usize;
for char in source.as_ref().chars() {
if char == '\n' {
col = 0;
line += 1;
} else {
col += 1;
}
if line + 1 >= loc_line && col + 1 >= loc_col {
break;
}
offset += char.len_utf8();
}

SourceOffset(offset)
}
}

impl From<ByteOffset> for SourceOffset {
Expand Down

0 comments on commit 75c2312

Please sign in to comment.