about summary refs log tree commit diff
diff options
context:
space:
mode:
authorAriel Davis <ariel.z.davis@icloud.com>2023-05-06 01:04:41 -0700
committerAriel Davis <ariel.z.davis@icloud.com>2023-05-06 01:04:41 -0700
commit902b3438c97067c4fddf4eb7e429b8fd82cfe5b7 (patch)
tree5fbc7a02847b147b08153deb41e5f4466d7e5bb5
parentd683e220214f182ec788f86d3e005827a8a2648c (diff)
downloadrust-902b3438c97067c4fddf4eb7e429b8fd82cfe5b7.tar.gz
rust-902b3438c97067c4fddf4eb7e429b8fd82cfe5b7.zip
Use try_line_col
-rw-r--r--lib/line-index/src/lib.rs11
1 files changed, 8 insertions, 3 deletions
diff --git a/lib/line-index/src/lib.rs b/lib/line-index/src/lib.rs
index 527ba08717a..c0e526a8e0f 100644
--- a/lib/line-index/src/lib.rs
+++ b/lib/line-index/src/lib.rs
@@ -141,10 +141,15 @@ impl LineIndex {
     ///
     /// If the offset is invalid.
     pub fn line_col(&self, offset: TextSize) -> LineCol {
-        let line = self.newlines.partition_point(|&it| it <= offset) - 1;
-        let line_start_offset = self.newlines[line];
+        self.try_line_col(offset).expect("invalid offset")
+    }
+
+    /// Transforms the `TextSize` into a `LineCol`, or returns `None` if the `offset` was invalid.
+    pub fn try_line_col(&self, offset: TextSize) -> Option<LineCol> {
+        let line = self.newlines.partition_point(|&it| it <= offset).checked_sub(1)?;
+        let line_start_offset = self.newlines.get(line)?;
         let col = offset - line_start_offset;
-        LineCol { line: line as u32, col: col.into() }
+        Some(LineCol { line: line as u32, col: col.into() })
     }
 
     /// Transforms the `LineCol` into a `TextSize`.