Skip to content

Commit e8a9330

Browse files
committed
Remove 0 TextSize at front
1 parent 6500487 commit e8a9330

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

lib/line-index/src/lib.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ impl WideChar {
8383
/// Maps flat [`TextSize`] offsets to/from `(line, column)` representation.
8484
#[derive(Debug, Clone, PartialEq, Eq)]
8585
pub struct LineIndex {
86-
/// Offset the beginning of each line, zero-based.
86+
/// Offset the beginning of each line (except the first, which always has offset 0).
8787
newlines: Box<[TextSize]>,
8888
/// List of non-ASCII characters on each line.
8989
line_wide_chars: IntMap<u32, Box<[WideChar]>>,
@@ -100,8 +100,6 @@ impl LineIndex {
100100
let mut cur_col = TextSize::from(0);
101101
let mut line = 0;
102102

103-
newlines.push(TextSize::from(0));
104-
105103
for c in text.chars() {
106104
let c_len = TextSize::of(c);
107105
cur_row += c_len;
@@ -147,8 +145,8 @@ impl LineIndex {
147145
/// Transforms the `TextSize` into a `LineCol`, or returns `None` if the `offset` was invalid,
148146
/// e.g. if it points to the middle of a multi-byte character.
149147
pub fn try_line_col(&self, offset: TextSize) -> Option<LineCol> {
150-
let line = self.newlines.partition_point(|&it| it <= offset).checked_sub(1)?;
151-
let start = self.newlines.get(line)?;
148+
let line = self.newlines.partition_point(|&it| it <= offset);
149+
let start = self.start_offset(line)?;
152150
let col = offset - start;
153151
let ret = LineCol { line: line as u32, col: col.into() };
154152
self.line_wide_chars
@@ -162,9 +160,14 @@ impl LineIndex {
162160

163161
/// Transforms the `LineCol` into a `TextSize`.
164162
pub fn offset(&self, line_col: LineCol) -> Option<TextSize> {
165-
self.newlines
166-
.get(line_col.line as usize)
167-
.map(|offset| offset + TextSize::from(line_col.col))
163+
self.start_offset(line_col.line as usize).map(|start| start + TextSize::from(line_col.col))
164+
}
165+
166+
fn start_offset(&self, line: usize) -> Option<TextSize> {
167+
match line.checked_sub(1) {
168+
None => Some(TextSize::from(0)),
169+
Some(it) => self.newlines.get(it).copied(),
170+
}
168171
}
169172

170173
/// Transforms the `LineCol` with the given `WideEncoding` into a `WideLineCol`.

0 commit comments

Comments
 (0)