#[derive(Clone, Debug)]
pub struct LineIndex {
starts: Vec<usize>,
}
impl LineIndex {
pub fn new(text: &str) -> LineIndex {
let b = text.as_bytes();
let mut starts = vec![0];
let mut i = 0;
while i < b.len() {
match b[i] {
b'\r' if b.get(i + 1) == Some(&b'\n') => {
i += 1;
starts.push(i + 1);
}
b'\n' | b'\r' | b'\x0c' => starts.push(i + 1),
_ => {}
}
i += 1;
}
LineIndex { starts }
}
pub fn line_column(&self, text: &str, offset: usize) -> (usize, usize) {
let line = self.starts.partition_point(|&s| s <= offset) - 1;
let column = text[self.starts[line]..offset].chars().count() + 1;
(line + 1, column)
}
}