enhanced_magic_string/utils/
get_locator.rs

1use super::char_string::CharString;
2
3pub fn get_locator(code: &CharString) -> impl Fn(usize) -> Loc {
4  let lines = code.split('\n');
5  let mut line_offsets = vec![];
6  let mut pos = 0;
7
8  for line in lines {
9    line_offsets.push(pos);
10    pos += line.len() + 1;
11  }
12
13  move |pos| {
14    // binary search
15    let mut left = 0;
16    let mut right = line_offsets.len();
17
18    while left < right {
19      let mid = (left + right) >> 1;
20
21      if pos < line_offsets[mid] {
22        right = mid;
23      } else {
24        left = mid + 1;
25      }
26    }
27
28    let line = left - 1;
29    let column = pos - line_offsets[line];
30
31    Loc { line, column }
32  }
33}
34
35#[derive(Debug, Clone)]
36pub struct Loc {
37  pub line: usize,
38  pub column: usize,
39}