Skip to content

Commit 902b343

Browse files
committed
Use try_line_col
1 parent d683e22 commit 902b343

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

lib/line-index/src/lib.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,15 @@ impl LineIndex {
141141
///
142142
/// If the offset is invalid.
143143
pub fn line_col(&self, offset: TextSize) -> LineCol {
144-
let line = self.newlines.partition_point(|&it| it <= offset) - 1;
145-
let line_start_offset = self.newlines[line];
144+
self.try_line_col(offset).expect("invalid offset")
145+
}
146+
147+
/// Transforms the `TextSize` into a `LineCol`, or returns `None` if the `offset` was invalid.
148+
pub fn try_line_col(&self, offset: TextSize) -> Option<LineCol> {
149+
let line = self.newlines.partition_point(|&it| it <= offset).checked_sub(1)?;
150+
let line_start_offset = self.newlines.get(line)?;
146151
let col = offset - line_start_offset;
147-
LineCol { line: line as u32, col: col.into() }
152+
Some(LineCol { line: line as u32, col: col.into() })
148153
}
149154

150155
/// Transforms the `LineCol` into a `TextSize`.

0 commit comments

Comments
 (0)