From cf0c848f6e1900396ec5e0f429eb472d578ee4b7 Mon Sep 17 00:00:00 2001 From: Johannes Altmanninger Date: Tue, 15 Oct 2024 08:33:14 +0200 Subject: [PATCH] line-index method to allow clamping column to line length Part of #18240 --- lib/line-index/Cargo.toml | 2 +- lib/line-index/src/lib.rs | 10 +++++++++- lib/line-index/src/tests.rs | 23 +++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/line-index/Cargo.toml b/lib/line-index/Cargo.toml index 8ae4954dd0de..14196ba3d097 100644 --- a/lib/line-index/Cargo.toml +++ b/lib/line-index/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "line-index" -version = "0.1.1" +version = "0.1.2" description = "Maps flat `TextSize` offsets to/from `(line, column)` representation." license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/line-index" diff --git a/lib/line-index/src/lib.rs b/lib/line-index/src/lib.rs index 66875e25242b..ef97e0e8a0c0 100644 --- a/lib/line-index/src/lib.rs +++ b/lib/line-index/src/lib.rs @@ -177,10 +177,18 @@ impl LineIndex { Some(LineCol { line: line_col.line, col }) } + /// Returns the given line's range. + pub fn line(&self, line: u32) -> Option { + let start = self.start_offset(line as usize)?; + let next_newline = self.newlines.get(line as usize).copied().unwrap_or(self.len); + let line_length = next_newline - start; + Some(TextRange::new(start, start + line_length)) + } + /// Given a range [start, end), returns a sorted iterator of non-empty ranges [start, x1), [x1, /// x2), ..., [xn, end) where all the xi, which are positions of newlines, are inside the range /// [start, end). - pub fn lines(&self, range: TextRange) -> impl Iterator + '_ { + pub fn lines_in_range(&self, range: TextRange) -> impl Iterator + '_ { let lo = self.newlines.partition_point(|&it| it < range.start()); let hi = self.newlines.partition_point(|&it| it <= range.end()); let all = std::iter::once(range.start()) diff --git a/lib/line-index/src/tests.rs b/lib/line-index/src/tests.rs index 57fad1dfc057..f2bb04aec323 100644 --- a/lib/line-index/src/tests.rs +++ b/lib/line-index/src/tests.rs @@ -195,3 +195,26 @@ fn test_every_chars() { } } } + +#[test] +fn test_line() { + use text_size::TextRange; + + macro_rules! validate { + ($text:expr, $line:expr, $expected_start:literal .. $expected_end:literal) => { + let line_index = LineIndex::new($text); + assert_eq!( + line_index.line($line), + Some(TextRange::new( + TextSize::from($expected_start), + TextSize::from($expected_end) + )) + ); + }; + } + + validate!("", 0, 0..0); + validate!("\n", 1, 1..1); + validate!("\nabc", 1, 1..4); + validate!("\nabc\ndef", 1, 1..5); +}