Skip to main content

rust_css_parser/parser/
linesmap.rs

1//! Port of `src/parser/linesmap.ts`.
2
3/// compute the line and column of an offset
4#[derive(Clone, Debug)]
5pub struct LineMap {
6    pub line_starts: Vec<u32>,
7}
8
9impl LineMap {
10    pub fn new(mut lines: Vec<u32>) -> Self {
11        if lines.is_empty() {
12            lines.push(0);
13        }
14        Self { line_starts: lines }
15    }
16
17    /// `[line, column]` of an offset (1-based line, 1-based column on the first line)
18    pub fn get_offsets(&self, offset: u32) -> (u32, u32) {
19        let line = self.search(offset);
20        if line < 0 {
21            // typescript: lineStarts[-1] is undefined -> NaN
22            return (0, 0);
23        }
24        let column = offset as i64 - self.line_starts[line as usize] as i64;
25        (line as u32 + 1, if line == 0 { (column + 1) as u32 } else { column as u32 })
26    }
27
28    /// greatest index of a line start less than or equal to the offset, -1 when none
29    pub fn search(&self, offset: u32) -> i64 {
30        // `partition_point` is the binary search of the typescript implementation
31        self.line_starts.partition_point(|&start| start <= offset) as i64 - 1
32    }
33}