@@ -83,7 +83,7 @@ impl WideChar {
83
83
/// Maps flat [`TextSize`] offsets to/from `(line, column)` representation.
84
84
#[ derive( Debug , Clone , PartialEq , Eq ) ]
85
85
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) .
87
87
newlines : Box < [ TextSize ] > ,
88
88
/// List of non-ASCII characters on each line.
89
89
line_wide_chars : IntMap < u32 , Box < [ WideChar ] > > ,
@@ -100,8 +100,6 @@ impl LineIndex {
100
100
let mut cur_col = TextSize :: from ( 0 ) ;
101
101
let mut line = 0 ;
102
102
103
- newlines. push ( TextSize :: from ( 0 ) ) ;
104
-
105
103
for c in text. chars ( ) {
106
104
let c_len = TextSize :: of ( c) ;
107
105
cur_row += c_len;
@@ -147,8 +145,8 @@ impl LineIndex {
147
145
/// Transforms the `TextSize` into a `LineCol`, or returns `None` if the `offset` was invalid,
148
146
/// e.g. if it points to the middle of a multi-byte character.
149
147
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) ?;
152
150
let col = offset - start;
153
151
let ret = LineCol { line : line as u32 , col : col. into ( ) } ;
154
152
self . line_wide_chars
@@ -162,9 +160,14 @@ impl LineIndex {
162
160
163
161
/// Transforms the `LineCol` into a `TextSize`.
164
162
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
+ }
168
171
}
169
172
170
173
/// Transforms the `LineCol` with the given `WideEncoding` into a `WideLineCol`.
0 commit comments