glsl_lang_pp/util/
line_map.rs

1use std::collections::BTreeMap;
2
3#[derive(Debug, Clone)]
4pub struct LineMap {
5    map: BTreeMap<u32, u32>,
6}
7
8impl LineMap {
9    /// Construct a new, empty LineMap
10    pub fn new() -> Self {
11        Self::default()
12    }
13
14    /// Add a new line boundary
15    ///
16    /// # Parameters
17    ///
18    /// * `offset`: starting offset of the next line in the input string
19    pub fn add_line(&mut self, offset: u32) {
20        self.map.insert(offset, self.map.len() as _);
21    }
22
23    /// Split an offset into line and column information
24    ///
25    /// # Parameters
26    ///
27    /// * `offset`: offset to split
28    pub fn get_line_and_col(&self, offset: u32) -> (u32, u32) {
29        // unwrap: offset >= 0 so there will always be a matching entry
30        let (prev_start_offset, line) = self.map.range(..=offset).next_back().unwrap();
31        (*line, offset - prev_start_offset)
32    }
33}
34
35impl Default for LineMap {
36    fn default() -> Self {
37        Self {
38            map: {
39                let mut map = BTreeMap::new();
40                map.insert(0, 0);
41                map
42            },
43        }
44    }
45}
46
47impl lang_util::located::Resolver for LineMap {
48    fn resolve(&self, offset: lang_util::TextSize) -> (u32, u32) {
49        self.get_line_and_col(offset.into())
50    }
51}