Skip to main content

jlens_core/
offsets.rs

1//! Conversion between byte offsets and UTF-16 offsets.
2//!
3//! The Rust crates count offsets and spans in bytes of the UTF-8 text. JavaScript strings, browser
4//! editors and the `position` of an [`Error`](crate::Error) count UTF-16 code units. [`Offsets`]
5//! converts between the two for one text.
6
7/// Converts offsets into one text between UTF-8 bytes, the unit of the Rust crates, and UTF-16
8/// code units, the unit of JavaScript strings and browser editors.
9///
10/// Build it once per text, then convert as many offsets as needed, in either direction:
11///
12/// ```
13/// use jlens_core::Offsets;
14///
15/// // `Ć©` takes 2 bytes and 1 UTF-16 unit; `š„ž` takes 4 bytes and 2 units (a surrogate pair).
16/// let offsets = Offsets::new("Ć©š„žx");
17/// assert_eq!(offsets.to_utf16(6), 3); // the byte offset of `x`
18/// assert_eq!(offsets.to_byte(3), 6);
19/// ```
20///
21/// Each direction maps an offset that falls inside a character to the start of that character
22/// (a byte inside a multi-byte character, or a unit between the halves of a surrogate pair), and
23/// an offset past the end of the text to the end. For ASCII text, both units are the same and no
24/// table is built.
25#[derive(Clone, Debug)]
26pub struct Offsets {
27    table: Table,
28    len: usize,
29}
30
31#[derive(Clone, Debug)]
32enum Table {
33    /// ASCII text: a byte offset is a UTF-16 offset.
34    Ascii,
35    /// The UTF-16 offset of every byte offset (`len + 1` entries). Bytes inside a character map to
36    /// the offset of the character.
37    Units(Vec<u32>),
38    /// Text too long for `u32` offsets: each conversion walks the text.
39    Long(Box<str>),
40}
41
42impl Offsets {
43    /// Prepares the conversion of offsets into `text`. Outside ASCII, this builds a table of
44    /// four bytes per byte of text, so each conversion takes constant or logarithmic time.
45    pub fn new(text: &str) -> Self {
46        let table = if text.is_ascii() {
47            Table::Ascii
48        } else if u32::try_from(text.len()).is_ok() {
49            // A text has no more UTF-16 units than bytes, so every offset fits in `u32`.
50            let mut table = Vec::with_capacity(text.len() + 1);
51            let mut units = 0u32;
52            for c in text.chars() {
53                table.extend(std::iter::repeat_n(units, c.len_utf8()));
54                units += c.len_utf16() as u32;
55            }
56            table.push(units);
57            Table::Units(table)
58        } else {
59            Table::Long(text.into())
60        };
61        Offsets {
62            table,
63            len: text.len(),
64        }
65    }
66
67    /// Whether the text is ASCII, where a byte offset and a UTF-16 offset are the same number.
68    pub fn is_ascii(&self) -> bool {
69        matches!(self.table, Table::Ascii)
70    }
71
72    /// The UTF-16 offset of a byte offset.
73    pub fn to_utf16(&self, byte: usize) -> usize {
74        let byte = byte.min(self.len);
75        match &self.table {
76            Table::Ascii => byte,
77            Table::Units(table) => table[byte] as usize,
78            Table::Long(text) => {
79                let mut end = byte;
80                while !text.is_char_boundary(end) {
81                    end -= 1;
82                }
83                text[..end].chars().map(char::len_utf16).sum()
84            }
85        }
86    }
87
88    /// The byte offset of a UTF-16 offset.
89    pub fn to_byte(&self, unit: usize) -> usize {
90        match &self.table {
91            Table::Ascii => unit.min(self.len),
92            Table::Units(table) => {
93                // The first byte whose UTF-16 offset reaches `unit`.
94                let mut byte = table
95                    .partition_point(|&u| (u as usize) < unit)
96                    .min(self.len);
97                if table[byte] as usize > unit {
98                    // `unit` falls inside a surrogate pair: go back to the character's start.
99                    byte -= 1;
100                    while byte > 0 && table[byte - 1] == table[byte] {
101                        byte -= 1;
102                    }
103                }
104                byte
105            }
106            Table::Long(text) => {
107                let mut units = 0;
108                for (byte, c) in text.char_indices() {
109                    units += c.len_utf16();
110                    if units > unit {
111                        return byte;
112                    }
113                }
114                self.len
115            }
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::{Offsets, Table};
123
124    /// Bytes: a=0, Ć©=1..3, š„ž=3..7, b=7, end=8. UTF-16: a=0, Ć©=1, š„ž=2..4, b=4, end=5.
125    const TEXT: &str = "aĆ©š„žb";
126
127    #[test]
128    fn ascii_offsets_are_the_same() {
129        let o = Offsets::new("abc");
130        assert!(o.is_ascii());
131        assert_eq!([0, 1, 3].map(|b| o.to_utf16(b)), [0, 1, 3]);
132        assert_eq!([0, 1, 3].map(|u| o.to_byte(u)), [0, 1, 3]);
133        let empty = Offsets::new("");
134        assert_eq!((empty.to_utf16(0), empty.to_byte(0)), (0, 0));
135    }
136
137    #[test]
138    fn offsets_outside_ascii_convert_both_ways() {
139        let o = Offsets::new(TEXT);
140        assert!(!o.is_ascii());
141        assert_eq!([0, 1, 3, 7, 8].map(|b| o.to_utf16(b)), [0, 1, 2, 4, 5]);
142        assert_eq!([0, 1, 2, 4, 5].map(|u| o.to_byte(u)), [0, 1, 3, 7, 8]);
143        // A byte inside a character: the start of the character.
144        assert_eq!([2, 4, 5, 6].map(|b| o.to_utf16(b)), [1, 2, 2, 2]);
145    }
146
147    #[test]
148    fn a_unit_inside_a_surrogate_pair_maps_to_the_character() {
149        let o = Offsets::new(TEXT);
150        assert_eq!(o.to_byte(3), 3);
151        let o = Offsets::new("š„ž");
152        assert_eq!([0, 1, 2].map(|u| o.to_byte(u)), [0, 0, 4]);
153    }
154
155    #[test]
156    fn offsets_past_the_end_map_to_the_end() {
157        let o = Offsets::new(TEXT);
158        assert_eq!((o.to_utf16(99), o.to_byte(99)), (5, 8));
159        let ascii = Offsets::new("abc");
160        assert_eq!((ascii.to_utf16(9), ascii.to_byte(9)), (3, 3));
161    }
162
163    #[test]
164    fn the_walk_for_long_texts_agrees_with_the_table() {
165        let table = Offsets::new(TEXT);
166        let long = Offsets {
167            table: Table::Long(TEXT.into()),
168            len: TEXT.len(),
169        };
170        for n in 0..=10 {
171            assert_eq!(long.to_utf16(n), table.to_utf16(n), "byte {n}");
172            assert_eq!(long.to_byte(n), table.to_byte(n), "unit {n}");
173        }
174    }
175}