Skip to main content

indigo_text/
grapheme.rs

1//! Unicode grapheme cluster boundaries.
2//!
3//! <https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>
4
5use ropey::{RopeSlice, iter::Chunks};
6use std::iter::FusedIterator;
7use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
8
9#[must_use]
10pub fn is_grapheme_boundary(rope: &RopeSlice, byte_offset: usize) -> bool {
11    assert!(
12        byte_offset <= rope.len(),
13        "byte offset {byte_offset} is out of bounds (rope length is {})",
14        rope.len()
15    );
16    let (chunk, chunk_byte_offset) = rope.chunk(byte_offset);
17    if !chunk.is_char_boundary(byte_offset - chunk_byte_offset) {
18        return false;
19    }
20    is_grapheme_boundary_in_chunk(rope, chunk, chunk_byte_offset, byte_offset)
21}
22
23// Like `is_grapheme_boundary` but reuses `chunk`.
24fn is_grapheme_boundary_in_chunk(
25    rope: &RopeSlice,
26    chunk: &str,
27    chunk_byte_offset: usize,
28    // Must be a `char` boundary.
29    byte_offset: usize,
30) -> bool {
31    // Note [ASCII fast path]
32    let bytes = chunk.as_bytes();
33    let i = byte_offset - chunk_byte_offset;
34    if 0 < i && i < bytes.len() {
35        let (before, after) = (bytes[i - 1], bytes[i]);
36        if before.is_ascii() && after.is_ascii() {
37            return !(before == b'\r' && after == b'\n');
38        }
39    }
40    let mut cursor = GraphemeCursor::new(byte_offset, rope.len(), true);
41    loop {
42        match cursor.is_boundary(chunk, chunk_byte_offset) {
43            Ok(is_boundary) => return is_boundary,
44            Err(GraphemeIncomplete::PreContext(byte_offset)) => {
45                let (prev_chunk, prev_chunk_byte_offset) = rope.chunk(byte_offset - 1);
46                cursor.provide_context(prev_chunk, prev_chunk_byte_offset);
47            }
48            _ => unreachable!(),
49        }
50    }
51}
52
53#[must_use]
54pub fn is_grapheme_start(rope: &RopeSlice, byte_index: usize) -> bool {
55    assert!(
56        byte_index <= rope.len(),
57        "byte index {byte_index} is out of bounds (rope length is {})",
58        rope.len()
59    );
60    if byte_index == rope.len() {
61        return false;
62    }
63    is_grapheme_boundary(rope, byte_index)
64}
65
66#[must_use]
67pub fn prev_grapheme_boundary(rope: &RopeSlice, byte_offset: usize) -> Option<usize> {
68    assert!(
69        byte_offset <= rope.len(),
70        "byte offset {byte_offset} is out of bounds (rope length is {})",
71        rope.len()
72    );
73    if byte_offset == 0 {
74        return None;
75    }
76    // `GraphemeCursor` requires a `char` boundary to start from
77    let start = rope.floor_char_boundary(byte_offset);
78    if start < byte_offset && is_grapheme_boundary(rope, start) {
79        return Some(start);
80    }
81    let (mut chunk, mut chunk_byte_offset) = rope.chunk(start);
82    let mut cursor = GraphemeCursor::new(start, rope.len(), true);
83    loop {
84        match cursor.prev_boundary(chunk, chunk_byte_offset) {
85            Ok(boundary) => return boundary,
86            Err(GraphemeIncomplete::PrevChunk) => {
87                (chunk, chunk_byte_offset) = rope.chunk(chunk_byte_offset - 1);
88            }
89            Err(GraphemeIncomplete::PreContext(byte_offset)) => {
90                let (prev_chunk, prev_chunk_byte_offset) = rope.chunk(byte_offset - 1);
91                cursor.provide_context(prev_chunk, prev_chunk_byte_offset);
92            }
93            _ => unreachable!(),
94        }
95    }
96}
97
98#[must_use]
99pub fn next_grapheme_boundary(rope: &RopeSlice, byte_offset: usize) -> Option<usize> {
100    assert!(
101        byte_offset <= rope.len(),
102        "byte offset {byte_offset} is out of bounds (rope length is {})",
103        rope.len()
104    );
105    if byte_offset == rope.len() {
106        return None;
107    }
108    // `GraphemeCursor` requires a `char` boundary to start from
109    let start = rope.ceil_char_boundary(byte_offset);
110    if start > byte_offset && is_grapheme_boundary(rope, start) {
111        return Some(start);
112    }
113    let (mut chunk, mut chunk_byte_offset) = rope.chunk(start);
114    let mut cursor = GraphemeCursor::new(start, rope.len(), true);
115    loop {
116        match cursor.next_boundary(chunk, chunk_byte_offset) {
117            Ok(boundary) => return boundary,
118            Err(GraphemeIncomplete::NextChunk) => {
119                (chunk, chunk_byte_offset) = rope.chunk(chunk_byte_offset + chunk.len());
120            }
121            Err(GraphemeIncomplete::PreContext(byte_offset)) => {
122                let (prev_chunk, prev_chunk_byte_offset) = rope.chunk(byte_offset - 1);
123                cursor.provide_context(prev_chunk, prev_chunk_byte_offset);
124            }
125            _ => unreachable!(),
126        }
127    }
128}
129
130#[must_use]
131pub fn floor_grapheme_boundary(rope: &RopeSlice, byte_offset: usize) -> usize {
132    assert!(
133        byte_offset <= rope.len(),
134        "byte offset {byte_offset} is out of bounds (rope length is {})",
135        rope.len()
136    );
137    // Chunks are `str`s, so their edges are `char` boundaries, and flooring within the chunk
138    // agrees with flooring within the rope.
139    let (chunk, chunk_byte_offset) = rope.chunk(byte_offset);
140    let byte_offset =
141        chunk_byte_offset + chunk.floor_char_boundary(byte_offset - chunk_byte_offset);
142    if is_grapheme_boundary_in_chunk(rope, chunk, chunk_byte_offset, byte_offset) {
143        return byte_offset;
144    }
145    prev_grapheme_boundary(rope, byte_offset)
146        .expect("only fails at start of text, which is a grapheme boundary")
147}
148
149#[must_use]
150pub fn ceil_grapheme_boundary(rope: &RopeSlice, byte_offset: usize) -> usize {
151    assert!(
152        byte_offset <= rope.len(),
153        "byte offset {byte_offset} is out of bounds (rope length is {})",
154        rope.len()
155    );
156    let byte_offset = rope.ceil_char_boundary(byte_offset);
157    if is_grapheme_boundary(rope, byte_offset) {
158        return byte_offset;
159    }
160    next_grapheme_boundary(rope, byte_offset)
161        .expect("only fails at end of text, which is a grapheme boundary")
162}
163
164#[derive(Clone, Debug)]
165pub struct Graphemes<'a> {
166    rope: RopeSlice<'a>,
167    chunks: Chunks<'a>,
168    chunk: &'a str,
169    chunk_byte_offset: usize,
170    cursor: GraphemeCursor,
171}
172
173impl<'a> Graphemes<'a> {
174    #[must_use]
175    pub fn new(rope: &RopeSlice<'a>) -> Self {
176        let mut chunks = rope.chunks();
177        let chunk = chunks.next().unwrap_or("");
178        Graphemes {
179            rope: *rope,
180            chunks,
181            chunk,
182            chunk_byte_offset: 0,
183            cursor: GraphemeCursor::new(0, rope.len(), true),
184        }
185    }
186}
187
188impl<'a> Iterator for Graphemes<'a> {
189    type Item = RopeSlice<'a>;
190
191    fn next(&mut self) -> Option<RopeSlice<'a>> {
192        let start = self.cursor.cur_cursor();
193        let end;
194        loop {
195            match self
196                .cursor
197                .next_boundary(self.chunk, self.chunk_byte_offset)
198            {
199                Ok(None) => return None,
200                Ok(Some(boundary)) => {
201                    end = boundary;
202                    break;
203                }
204                Err(GraphemeIncomplete::NextChunk) => {
205                    self.chunk_byte_offset += self.chunk.len();
206                    self.chunk = self
207                        .chunks
208                        .next()
209                        .expect("only requested when the cursor is not at the end of the rope");
210
211                    // Note [Grapheme cursor bug workaround]
212                    // BEGIN WORKAROUND
213                    let crossing = self.cursor.cur_cursor();
214                    self.cursor = GraphemeCursor::new(crossing, self.rope.len(), true);
215                    if crossing > start && is_grapheme_boundary(&self.rope, crossing) {
216                        end = crossing;
217                        break;
218                    }
219                    // END WORKAROUND
220                }
221                Err(GraphemeIncomplete::PreContext(byte_offset)) => {
222                    let (prev_chunk, prev_chunk_byte_offset) = self.rope.chunk(byte_offset - 1);
223                    self.cursor
224                        .provide_context(prev_chunk, prev_chunk_byte_offset);
225                }
226                _ => unreachable!(),
227            }
228        }
229        if start < self.chunk_byte_offset {
230            // Grapheme spans multiple chunks, so requires going through the rope
231            Some(self.rope.slice(start..end))
232        } else {
233            // Grapheme fits within the current chunk, so requires no copying
234            let start_in_chunk = start - self.chunk_byte_offset;
235            let end_in_chunk = end - self.chunk_byte_offset;
236            Some((&self.chunk[start_in_chunk..end_in_chunk]).into())
237        }
238    }
239
240    fn size_hint(&self) -> (usize, Option<usize>) {
241        // Graphemes are at least one byte long
242        let remaining_bytes = self.rope.len() - self.cursor.cur_cursor();
243        (usize::from(remaining_bytes > 0), Some(remaining_bytes))
244    }
245}
246
247impl FusedIterator for Graphemes<'_> {}
248
249/*
250Note [Grapheme cursor bug workaround]
251--------------------------------------
252
253Claude: `unicode-segmentation` 1.13.3's `GraphemeCursor` produces false grapheme boundaries in
254flag-emoji (regional indicator) runs when a long-lived cursor crosses a chunk boundary: at the
255hand-off, `handle_regional`'s backward pre-context scan is seeded with the forward-accumulated
256`ris_count`, counting the same indicators twice and flipping the pairing parity.
257
258The workaround decides each chunk crossing with a fresh cursor (via `is_grapheme_boundary`) and
259rebuilds the iterator's cursor there, so no stale state survives the hand-off.
260*/
261
262/*
263Note [ASCII fast path]
264----------------------
265
266Claude: Between two ASCII characters there is always a grapheme boundary, except between CR and LF
267(GB3). Every rule that joins characters otherwise (Extend, ZWJ, SpacingMark, Prepend, regional
268indicators, emoji sequences, Indic conjuncts) involves a non-ASCII character on one side, and none
269look further back than the pair when the character after the boundary is ASCII. ASCII bytes only
270ever encode ASCII characters in UTF-8, so checking the two bytes around the offset is enough.
271
272The fast path skips `GraphemeCursor` entirely, which matters when snapping many cursors at once.
273It only applies when both bytes are in the same chunk; otherwise we fall back to the cursor.
274*/
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use hegel::{TestCase, generators as gs};
280    use ropey::Rope;
281    use unicode_segmentation::UnicodeSegmentation as _;
282
283    // Note [Grapheme cursor bug workaround]
284    #[test]
285    fn test_flag_run_across_chunks() {
286        let text = "\u{1f1e6}\u{1f1e7}".repeat(1024 / 8 + 1); // should be more than 1 chunk
287        let rope = Rope::from_str(&text);
288        for start in [0, 4] {
289            let expected: Vec<&str> = text[start..].graphemes(true).collect();
290            let actual: Vec<String> = Graphemes::new(&rope.slice(start..))
291                .map(|grapheme| grapheme.to_string())
292                .collect();
293            assert_eq!(actual, expected, "slice starting at {start}");
294        }
295    }
296
297    #[hegel::test(test_cases = 10_000)]
298    fn test_is_grapheme_boundary(tc: TestCase) {
299        let string = tc.draw(gs::text());
300        let input = tc.draw(gs::integers().max_value(string.len()));
301        let ropey = {
302            let rope = ropey::Rope::from(string.as_str());
303            is_grapheme_boundary(&rope.slice(..), input)
304        };
305        let crop = {
306            let rope = crop::Rope::from(string.as_str());
307            rope.is_grapheme_boundary(input)
308        };
309        assert_eq!(ropey, crop);
310    }
311
312    // Note [ASCII fast path]
313    #[hegel::test(test_cases = 10_000)]
314    fn test_is_grapheme_boundary_ascii_neighbors(tc: TestCase) {
315        // Mostly ASCII (including CR/LF), plus characters that join with ASCII neighbors:
316        // combining acute, ZWJ, regional indicator, Devanagari virama.
317        let string = tc
318            .draw(
319                gs::text()
320                    .alphabet("ab \r\n\t\u{301}\u{200d}\u{1f1e6}\u{94d}")
321                    .max_size(64),
322            )
323            // Repeat to sometimes span multiple chunks.
324            .repeat(tc.draw(gs::integers().min_value(1).max_value(100)));
325        let input = tc.draw(gs::integers().max_value(string.len()));
326        let rope = Rope::from(string.as_str());
327        let actual = is_grapheme_boundary(&rope.slice(..), input);
328        let expected =
329            input == string.len() || string.grapheme_indices(true).any(|(i, _)| i == input);
330        assert_eq!(actual, expected);
331    }
332
333    #[hegel::test(test_cases = 10_000)]
334    fn test_floor_grapheme_boundary(tc: TestCase) {
335        // Repeat to sometimes span multiple chunks.
336        let string = tc
337            .draw(gs::text())
338            .repeat(tc.draw(gs::integers().min_value(1).max_value(200)));
339        let input = tc.draw(gs::integers().max_value(string.len()));
340        let rope = Rope::from(string.as_str());
341        let actual = floor_grapheme_boundary(&rope.slice(..), input);
342        let expected = string
343            .grapheme_indices(true)
344            .map(|(i, _)| i)
345            .chain([string.len()])
346            .take_while(|&i| i <= input)
347            .last()
348            .unwrap();
349        assert_eq!(actual, expected);
350    }
351
352    #[hegel::test(test_cases = 10_000)]
353    fn test_graphemes(tc: TestCase) {
354        let string = tc.draw(gs::text());
355        let ropey = {
356            let rope = ropey::Rope::from(string.as_str());
357            Graphemes::new(&rope.slice(..))
358                .map(|slice| slice.to_string())
359                .collect::<Vec<_>>()
360        };
361        let str = string
362            .graphemes(true)
363            .map(str::to_string)
364            .collect::<Vec<_>>();
365        assert_eq!(ropey, str);
366    }
367}