Skip to main content

griz_core/
position.rs

1//! Converts an LSP position (0-based line and character) into a byte
2//! offset, honoring the encoding `character` counts in.
3
4use schemars::JsonSchema;
5use serde::Deserialize;
6
7/// A 0-based line and character inside a file.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
9pub struct Position {
10    /// 0-based line.
11    pub line: u32,
12    /// 0-based offset into the line, in units of the chosen encoding.
13    pub character: u32,
14}
15
16/// How a position's `character` counts into a line.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum PositionEncoding {
19    /// `character` counts UTF-8 bytes.
20    Utf8,
21    /// `character` counts UTF-16 code units. The LSP default.
22    #[default]
23    Utf16,
24    /// `character` counts Unicode scalar values.
25    Utf32,
26}
27
28impl PositionEncoding {
29    /// Parses `utf-8`, `utf-16`, or `utf-32`.
30    ///
31    /// # Errors
32    /// Returns a message naming the accepted values.
33    pub fn parse(text: &str) -> Result<Self, String> {
34        match text {
35            "utf-8" => Ok(Self::Utf8),
36            "utf-16" => Ok(Self::Utf16),
37            "utf-32" => Ok(Self::Utf32),
38            other => Err(format!(
39                "unknown position_encoding `{other}`; use utf-8, utf-16, or utf-32"
40            )),
41        }
42    }
43}
44
45/// Converts a batch in coordinate order, then returns offsets in caller order.
46pub fn to_bytes(
47    text: &str,
48    positions: &[Position],
49    encoding: PositionEncoding,
50) -> Vec<Option<usize>> {
51    let mut order: Vec<_> = (0..positions.len()).collect();
52    order.sort_unstable_by_key(|&index| (positions[index].line, positions[index].character));
53    let mut offsets = vec![None; positions.len()];
54    let mut cursor = Cursor::new(text);
55    for index in order {
56        offsets[index] = cursor.at(positions[index], encoding);
57    }
58    offsets
59}
60
61struct Cursor<'a> {
62    remaining: std::str::Split<'a, char>,
63    text: &'a str,
64    line: usize,
65    start: usize,
66    byte: usize,
67    units: usize,
68}
69
70impl<'a> Cursor<'a> {
71    fn new(text: &'a str) -> Self {
72        let mut remaining = text.split('\n');
73        let text = remaining.next().unwrap_or_default();
74        Self {
75            remaining,
76            text,
77            line: 0,
78            start: 0,
79            byte: 0,
80            units: 0,
81        }
82    }
83
84    fn advance_line(&mut self, line: u32) -> Option<()> {
85        while self.line < line as usize {
86            let next = self.remaining.next()?;
87            self.start += self.text.len() + 1;
88            self.text = next;
89            self.line += 1;
90            self.byte = 0;
91            self.units = 0;
92        }
93        Some(())
94    }
95
96    fn at(&mut self, position: Position, encoding: PositionEncoding) -> Option<usize> {
97        self.advance_line(position.line)?;
98        let target = position.character as usize;
99        if encoding == PositionEncoding::Utf8 {
100            return self
101                .start
102                .checked_add(target)
103                .filter(|_| target <= self.text.len());
104        }
105        while self.units < target {
106            let ch = self.text[self.byte..].chars().next()?;
107            self.units += character_units(ch, encoding);
108            self.byte += ch.len_utf8();
109        }
110        (self.units == target).then_some(self.start + self.byte)
111    }
112}
113
114fn character_units(ch: char, encoding: PositionEncoding) -> usize {
115    match encoding {
116        PositionEncoding::Utf16 => ch.len_utf16(),
117        PositionEncoding::Utf8 | PositionEncoding::Utf32 => 1,
118    }
119}