Skip to content

Commit d42a4e6

Browse files
committed
line-index method to allow clamping column to line length
Part of rust-lang#18240
1 parent 0319586 commit d42a4e6

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

lib/line-index/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "line-index"
3-
version = "0.1.1"
3+
version = "0.1.2"
44
description = "Maps flat `TextSize` offsets to/from `(line, column)` representation."
55
license = "MIT OR Apache-2.0"
66
repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/line-index"

lib/line-index/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,14 @@ impl LineIndex {
177177
Some(LineCol { line: line_col.line, col })
178178
}
179179

180+
/// Returns the given line's range.
181+
pub fn line(&self, line: u32) -> Option<TextRange> {
182+
let start = self.start_offset(line as usize)?;
183+
let next_newline = self.newlines.get(line as usize).copied().unwrap_or(self.len);
184+
let line_length = next_newline - start;
185+
Some(TextRange::new(start, start + line_length))
186+
}
187+
180188
/// Given a range [start, end), returns a sorted iterator of non-empty ranges [start, x1), [x1,
181189
/// x2), ..., [xn, end) where all the xi, which are positions of newlines, are inside the range
182190
/// [start, end).

lib/line-index/src/tests.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,26 @@ fn test_every_chars() {
195195
}
196196
}
197197
}
198+
199+
#[test]
200+
fn test_line() {
201+
use text_size::TextRange;
202+
203+
macro_rules! validate {
204+
($text:expr, $line:expr, $expected_start:literal .. $expected_end:literal) => {
205+
let line_index = LineIndex::new($text);
206+
assert_eq!(
207+
line_index.line($line),
208+
Some(TextRange::new(
209+
TextSize::from($expected_start),
210+
TextSize::from($expected_end)
211+
))
212+
);
213+
};
214+
}
215+
216+
validate!("", 0, 0..0);
217+
validate!("\n", 1, 1..1);
218+
validate!("\nabc", 1, 1..4);
219+
validate!("\nabc\ndef", 1, 1..5);
220+
}

0 commit comments

Comments
 (0)