use crate::{HashId, Span, SrcRef, src_ref::LineCol};
#[derive(Clone, Debug)]
pub struct LineIndex {
line_offsets: Vec<u32>,
}
impl LineIndex {
pub fn new(s: &str) -> Self {
Self {
line_offsets: std::iter::once(0)
.chain(s.match_indices('\n').map(|(i, _)| (i + 1) as u32))
.collect(),
}
}
pub fn line_col(&self, input: &str, pos: usize) -> LineCol {
let line = self.line_offsets.partition_point(|&it| it <= pos as u32) - 1;
let first_offset = self.line_offsets[line] as usize;
let line_str = &input[first_offset..pos];
let col = line_str.chars().count();
LineCol {
line: line as u32,
col: (col + 1) as u32,
}
}
pub fn src_ref(&self, text: &str, span: &Span, hash: HashId) -> SrcRef {
SrcRef::new(span.clone(), self.line_col(text, span.start), hash)
}
}