1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
const BOM_CHAR: char = '\u{FEFF}';

#[cfg_attr(
  feature = "serialization",
  derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineAndColumnIndex {
  /// The zero-indexed line index.
  pub line_index: usize,
  /// The character index relative to the start of the line.
  pub column_index: usize,
}

#[cfg_attr(
  feature = "serialization",
  derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineAndColumnDisplay {
  /// The 1-indexed line number for display purposes.
  pub line_number: usize,
  /// The 1-indexed column number based on the indent width.
  pub column_number: usize,
}

#[derive(Debug)]
struct MultiByteCharInfo {
  /// The byte index in the entire file.
  byte_index: usize,
  /// The character index on the current line.
  line_char_index: usize,
  length: usize,
}

#[derive(Debug)]
struct TextLine {
  start_index: usize,
  end_index: usize,
  multi_line_chars: Vec<MultiByteCharInfo>,
  tab_chars: Vec<usize>,
}

#[derive(Debug)]
pub struct TextLines {
  lines: Vec<TextLine>,
  indent_width: usize,
}

impl TextLines {
  /// Creates a new `TextLines` with the specified text and default
  /// indent width of 4.
  pub fn new(text: &str) -> Self {
    TextLines::with_indent_width(text, 4)
  }

  /// Creates a new `TextLines` with the specified text and indent width.
  /// The indent width sets the width of a tab character when getting
  /// the display column.
  pub fn with_indent_width(text: &str, indent_width: usize) -> Self {
    let mut last_line_start = if text.starts_with(BOM_CHAR) {
      BOM_CHAR.len_utf8()
    } else {
      0
    };
    let mut multi_line_chars = Vec::new();
    let mut tab_chars = Vec::new();
    let mut lines = Vec::new();
    let mut was_last_slash_r = false;
    let mut line_char_index = 0;
    for (char_index, (byte_index, c)) in text.char_indices().enumerate() {
      if byte_index == 0 && c == BOM_CHAR {
        continue;
      }

      if c == '\n' {
        lines.push(TextLine {
          start_index: last_line_start,
          end_index: if was_last_slash_r { byte_index - 1 } else { byte_index },
          multi_line_chars: std::mem::take(&mut multi_line_chars),
          tab_chars: std::mem::take(&mut tab_chars),
        });
        last_line_start = byte_index + 1;
        line_char_index = char_index + 1;
      } else if c == '\t' {
        tab_chars.push(byte_index);
      } else if c.len_utf8() > 1 {
        multi_line_chars.push(MultiByteCharInfo {
          line_char_index: char_index - line_char_index,
          byte_index,
          length: c.len_utf8(),
        });
      }
      was_last_slash_r = c == '\r';
    }

    lines.push(TextLine {
      start_index: last_line_start,
      end_index: text.len(),
      multi_line_chars,
      tab_chars,
    });

    Self {
      lines,
      indent_width,
    }
  }

  /// Gets the number of lines in the text.
  pub fn lines_count(&self) -> usize {
    self.lines.len()
  }

  /// Gets the text length in bytes.
  pub fn text_length(&self) -> usize {
    self.lines.last().unwrap().end_index
  }

  /// Gets the line index from a byte index.
  /// Note that if you provide the middle byte index of a \r\n newline
  /// then it will return the index of the line the preceding line.
  pub fn line_index(&self, byte_index: usize) -> usize {
    self.assert_valid_byte_index(byte_index);

    match self
      .lines
      .binary_search_by_key(&byte_index, |line| line.start_index)
    {
      Ok(index) => index,
      Err(insert_index) => {
        if insert_index == 0 {
          0 // may happen when there's a BOM
        } else {
          insert_index - 1
        }
      }
    }
  }

  /// Gets the line start byte index.
  pub fn line_start(&self, line_index: usize) -> usize {
    self.assert_valid_line_index(line_index);
    self.lines[line_index].start_index
  }

  /// Gets the line end byte index (before/at the newline character).
  pub fn line_end(&self, line_index: usize) -> usize {
    self.assert_valid_line_index(line_index);
    self.lines[line_index].end_index
  }

  /// Gets the line range.
  pub fn line_range(&self, line_index: usize) -> (usize, usize) {
    self.assert_valid_line_index(line_index);
    let line = &self.lines[line_index];
    (line.start_index, line.end_index)
  }

  /// Gets the byte position from the provided line and column index.
  pub fn byte_index(&self, line_and_column: LineAndColumnIndex) -> usize {
    let line = &self.lines[line_and_column.line_index];
    let mut byte_index = line.start_index + line_and_column.column_index;

    for char_info in line.multi_line_chars.iter() {
      if char_info.line_char_index < line_and_column.column_index {
        // - 1 because the 1 was already added above when adding the column index
        byte_index += char_info.length - 1;
      } else {
        break;
      }
    }

    // fallback gracefully to the end index of the line when the column goes off
    if byte_index > line.end_index {
      line.end_index
    } else {
      byte_index
    }
  }

  /// Gets the line and column index of the provided byte index.
  pub fn line_and_column_index(&self, byte_index: usize) -> LineAndColumnIndex {
    // ensure no panics will happen here in case someone is specifying a byte position in the middle of a char
    let line_index = self.line_index(byte_index);
    let line = &self.lines[line_index];

    let relative_byte_index = if byte_index < line.start_index {
      0 // could happen when at the BOM position
    } else {
      byte_index - line.start_index
    };
    let multi_line_char_offset = line
      .multi_line_chars
      .iter()
      .take_while(|char_info| char_info.byte_index < byte_index)
      .map(|char_info| {
        if char_info.byte_index + char_info.length > byte_index {
          byte_index - char_info.byte_index
        } else {
          char_info.length - 1
        }
      })
      .sum::<usize>();

    LineAndColumnIndex {
      line_index,
      column_index: relative_byte_index - multi_line_char_offset,
    }
  }

  /// Gets the line and column display based on the indentation width and the provided byte index.
  pub fn line_and_column_display(&self, byte_index: usize) -> LineAndColumnDisplay {
    self.line_and_column_display_with_indent_width(byte_index, self.indent_width)
  }

  /// Gets the line and column display based on the provided byte index and indentation width.
  pub fn line_and_column_display_with_indent_width(&self, byte_index: usize, indent_width: usize) -> LineAndColumnDisplay {
    let line_and_column_index = self.line_and_column_index(byte_index);
    let line = &self.lines[line_and_column_index.line_index];
    let tab_char_count = line
      .tab_chars
      .iter()
      .take_while(|tab_index| **tab_index < byte_index)
      .count();

    LineAndColumnDisplay {
      line_number: line_and_column_index.line_index + 1,
      column_number: line_and_column_index.column_index - tab_char_count
        + tab_char_count * indent_width
        + 1,
    }
  }

  fn assert_valid_byte_index(&self, byte_index: usize) {
    if byte_index > self.text_length() {
      panic!(
        "The specified byte index {} was greater than the text length of {}.",
        byte_index,
        self.text_length()
      )
    }
  }

  fn assert_valid_line_index(&self, line_index: usize) {
    if line_index >= self.lines.len() {
      panic!(
        "The specified line index {} was greater or equal to the number of lines of {}.",
        line_index,
        self.lines.len()
      );
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn line_and_column_index() {
    let text = "12\n3\r\n4\n5";
    let info = TextLines::new(text);
    assert_line_and_col_index(&info, 0, 0, 0); // 1
    assert_line_and_col_index(&info, 1, 0, 1); // 2
    assert_line_and_col_index(&info, 2, 0, 2); // \n
    assert_line_and_col_index(&info, 3, 1, 0); // 3
    assert_line_and_col_index(&info, 4, 1, 1); // \r
    assert_line_and_col_index(&info, 5, 1, 2); // \n
    assert_line_and_col_index(&info, 6, 2, 0); // 4
    assert_line_and_col_index(&info, 7, 2, 1); // \n
    assert_line_and_col_index(&info, 8, 3, 0); // 5
    assert_line_and_col_index(&info, 9, 3, 1); // <EOF>
  }

  #[test]
  fn line_and_column_index_bom() {
    let text = "\u{FEFF}12\n3";
    let info = TextLines::new(text);
    assert_line_and_col_index(&info, 0, 0, 0); // first BOM index
    assert_line_and_col_index(&info, 1, 0, 0); // second BOM index
    assert_line_and_col_index(&info, 2, 0, 0); // third BOM index
    assert_line_and_col_index(&info, 3, 0, 0); // 1
    assert_line_and_col_index(&info, 4, 0, 1); // 2
    assert_line_and_col_index(&info, 5, 0, 2); // \n
    assert_line_and_col_index(&info, 6, 1, 0); // 3
    assert_line_and_col_index(&info, 7, 1, 1); // <EOF>
  }

  #[test]
  fn line_and_column_index_multi_byte_chars() {
    let text = "β1β\nΔβ1";
    let info = TextLines::new(text);
    assert_line_and_col_index(&info, 0, 0, 0); // first β index
    assert_line_and_col_index(&info, 1, 0, 0); // second β index
    assert_line_and_col_index(&info, 2, 0, 1); // 1
    assert_line_and_col_index(&info, 3, 0, 2); // first β index
    assert_line_and_col_index(&info, 4, 0, 2); // second β index
    assert_line_and_col_index(&info, 5, 0, 3); // \n
    assert_line_and_col_index(&info, 6, 1, 0); // first Δ index
    assert_line_and_col_index(&info, 7, 1, 0); // second Δ index
    assert_line_and_col_index(&info, 8, 1, 1); // first β index
    assert_line_and_col_index(&info, 9, 1, 1); // second β index
    assert_line_and_col_index(&info, 10, 1, 2); // 1
    assert_line_and_col_index(&info, 11, 1, 3); // <EOF>
  }

  fn assert_line_and_col_index(
    info: &TextLines,
    byte_index: usize,
    line_index: usize,
    column_index: usize,
  ) {
    assert_eq!(
      info.line_and_column_index(byte_index),
      LineAndColumnIndex {
        line_index,
        column_index,
      }
    );
  }

  #[test]
  fn line_and_column_display() {
    let text = "\t1\n\t 3\t4";
    let info = TextLines::new(text);
    assert_line_and_col_display(&info, 0, 1, 1); // \t
    assert_line_and_col_display(&info, 1, 1, 5); // 1
    assert_line_and_col_display(&info, 2, 1, 6); // \n
    assert_line_and_col_display(&info, 3, 2, 1); // \t
    assert_line_and_col_display(&info, 4, 2, 5); // <space>
    assert_line_and_col_display(&info, 5, 2, 6); // 3
    assert_line_and_col_display(&info, 6, 2, 7); // \t
    assert_line_and_col_display(&info, 7, 2, 11); // \t
    assert_line_and_col_display(&info, 8, 2, 12); // <EOF>
  }

  #[test]
  fn line_and_column_display_bom() {
    let text = "\u{FEFF}\t1";
    let info = TextLines::new(text);
    assert_line_and_col_display(&info, 0, 1, 1); // first BOM index
    assert_line_and_col_display(&info, 1, 1, 1); // second BOM index
    assert_line_and_col_display(&info, 2, 1, 1); // third BOM index
    assert_line_and_col_display(&info, 3, 1, 1); // \t
    assert_line_and_col_display(&info, 4, 1, 5); // 1
    assert_line_and_col_display(&info, 5, 1, 6); // <EOF>
  }

  #[test]
  fn line_and_column_display_indent_width() {
    let text = "\t1";
    let info = TextLines::with_indent_width(text, 2);
    assert_line_and_col_display(&info, 0, 1, 1); // \t
    assert_line_and_col_display(&info, 1, 1, 3); // 1
    assert_line_and_col_display(&info, 2, 1, 4); // <EOF>
  }

  fn assert_line_and_col_display(
    info: &TextLines,
    byte_index: usize,
    line_number: usize,
    column_number: usize,
  ) {
    assert_eq!(
      info.line_and_column_display(byte_index),
      LineAndColumnDisplay {
        line_number,
        column_number,
      }
    );
  }

  #[test]
  fn line_and_column_display_with_indent_width() {
    let text = "\t1\n\t 3\t4";
    let info = TextLines::new(text);
    assert_eq!(
      info.line_and_column_display_with_indent_width(1, 2),
      LineAndColumnDisplay {
        line_number: 1,
        column_number: 3,
      }
    );
    assert_eq!(
      info.line_and_column_display_with_indent_width(1, 4),
      LineAndColumnDisplay {
        line_number: 1,
        column_number: 5,
      }
    );
  }

  #[test]
  #[should_panic(expected = "The specified byte index 5 was greater than the text length of 4.")]
  fn line_and_column_index_panic_greater_than() {
    let info = TextLines::new("test");
    info.line_and_column_index(5);
  }

  #[test]
  fn line_start() {
    let text = "12\n3\r\n4\n5";
    let info = TextLines::new(text);
    assert_line_start(&info, 0, 0);
    assert_line_start(&info, 1, 3);
    assert_line_start(&info, 2, 6);
    assert_line_start(&info, 3, 8);
  }

  fn assert_line_start(info: &TextLines, line_index: usize, line_start: usize) {
    assert_eq!(info.line_start(line_index), line_start);
  }

  #[test]
  #[should_panic(
    expected = "The specified line index 1 was greater or equal to the number of lines of 1."
  )]
  fn line_start_equal_number_lines() {
    let info = TextLines::new("test");
    info.line_start(1);
  }

  #[test]
  fn line_end() {
    let text = "12\n3\r\n4\n5";
    let info = TextLines::new(text);
    assert_line_end(&info, 0, 2);
    assert_line_end(&info, 1, 4);
    assert_line_end(&info, 2, 7);
    assert_line_end(&info, 3, 9);
  }

  fn assert_line_end(info: &TextLines, line_index: usize, line_end: usize) {
    assert_eq!(info.line_end(line_index), line_end);
  }

  #[test]
  #[should_panic(
    expected = "The specified line index 1 was greater or equal to the number of lines of 1."
  )]
  fn line_end_equal_number_lines() {
    let info = TextLines::new("test");
    info.line_end(1);
  }

  #[test]
  fn byte_index() {
    let text = "12\n3\r\n4\n5";
    let info = TextLines::new(text);
    assert_byte_index(&info, 0, 0, 0); // 1
    assert_byte_index(&info, 0, 1, 1); // 2
    assert_byte_index(&info, 0, 2, 2); // \n
    assert_byte_index(&info, 0, 3, 2); // passed the \n
    assert_byte_index(&info, 0, 4, 2); // passed the \n
    assert_byte_index(&info, 1, 0, 3); // 3
    assert_byte_index(&info, 1, 1, 4); // \r
    assert_byte_index(&info, 1, 2, 4); // \n
    assert_byte_index(&info, 1, 3, 4); // passed the \r\n
    assert_byte_index(&info, 2, 0, 6); // 4
    assert_byte_index(&info, 2, 1, 7); // \n
    assert_byte_index(&info, 3, 0, 8); // 5
    assert_byte_index(&info, 3, 1, 9); // <EOF>
    assert_byte_index(&info, 3, 2, 9); // passed the<EOF>
  }

  #[test]
  fn byte_index_bom() {
    let text = "\u{FEFF}12\n3";
    let info = TextLines::new(text);
    assert_byte_index(&info, 0, 0, 3); // 1
    assert_byte_index(&info, 0, 1, 4); // 2
    assert_byte_index(&info, 0, 2, 5); // \n
    assert_byte_index(&info, 1, 0, 6); // 3
    assert_byte_index(&info, 1, 1, 7); // <EOF>
  }

  #[test]
  fn byte_index_multi_byte_chars() {
    let text = "β1β\nΔβ1";
    let info = TextLines::new(text);
    assert_byte_index(&info, 0, 0, 0); // first β index
    assert_byte_index(&info, 0, 1, 2); // 1
    assert_byte_index(&info, 0, 2, 3); // first β index
    assert_byte_index(&info, 0, 3, 5); // \n
    assert_byte_index(&info, 1, 0, 6); // first Δ index
    assert_byte_index(&info, 1, 1, 8); // first β index
    assert_byte_index(&info, 1, 2, 10); // 1
    assert_byte_index(&info, 1, 3, 11); // <EOF>
  }

  fn assert_byte_index(
    info: &TextLines,
    line_index: usize,
    column_index: usize,
    byte_index: usize,
  ) {
    assert_eq!(
      info.byte_index(LineAndColumnIndex {
        line_index,
        column_index,
      }),
      byte_index,
    );
  }

  #[test]
  fn readme_example() {
    let text = "Line 1\n\tLine 2";
    let info = TextLines::new(&text);

    assert_eq!(info.line_index(9), 1);
    assert_eq!(
      info.line_and_column_index(9),
      LineAndColumnIndex {
        line_index: 1,
        column_index: 2,
      }
    );
    assert_eq!(
      info.line_and_column_display(9),
      LineAndColumnDisplay {
        line_number: 2,
        column_number: 6,
      }
    );

    let info = TextLines::with_indent_width(&text, 2);
    assert_eq!(
      info.line_and_column_display(9),
      LineAndColumnDisplay {
        line_number: 2,
        column_number: 4,
      }
    );
  }
}