Skip to main content

uncurses/ansi/
text.rs

1//! ANSI-aware byte-stream tokenizer for text utilities.
2//!
3//! ## Category
4//!
5//! The tokenizer classifies an input byte slice as visible grapheme clusters,
6//! complete ANSI escape/string sequences, or standalone control bytes. Width,
7//! stripping, truncation, and wrapping utilities all build on this stream.
8//!
9//! ## Control encodings
10//!
11//! Both 7-bit forms (`ESC [`, `ESC ]`, `ESC P`, `ESC X`, `ESC ^`, `ESC _`) and
12//! their 8-bit C1 bytes (`0x9B`, `0x9D`, `0x90`, `0x98`, `0x9E`, `0x9F`) open a
13//! sequence. The tokenizer also accepts UTF-8 C1 characters (`C2 80` through
14//! `C2 9F`) as controls.
15//!
16//! A control string ends at ST: `0x9C`, `C2 9C`, or `ESC \`.
17//! **`BEL` ends an OSC and nothing else**: `OSC Ps ; Pt BEL` is an xterm
18//! convention rather than a rule about control strings, and ECMA-48 gives them
19//! all one terminator. A `0x07` inside a DCS, SOS, PM or APC is payload, which
20//! matters because DCS carries arbitrary data. A lone `ESC` also ends a string
21//! and is re-parsed as the start of the next sequence.
22//!
23//! ## C1 bytes depend on decoder state
24//!
25//! A byte in `0x80..=0x9F` is a C1 control **between** characters and a UTF-8
26//! continuation byte **inside** one. Which it is depends on where the decoder
27//! is and on nothing else, so:
28//!
29//! - the byte `0x9C` is 8-bit ST, and the byte `0x9D` opens an OSC;
30//! - `C2 9C` is UTF-8 ST, and `C2 9D` opens an OSC;
31//! - the `0x9C` inside `E2 9C 85` ("✅") is neither, and is never examined.
32//!
33//! That last case is why every code point in U+2700..U+273F survives inside an
34//! OSC title. UTF-8 C1 support lets text utilities parse controls in a `&str`.
35//! This is an input-text convention. Terminal output should use 7-bit controls:
36//! xterm processes control bytes before UTF-8 decoding.
37//!
38//! ## Malformed input
39//!
40//! [`tokenize`] takes bytes, so its input need not be valid UTF-8. A byte that
41//! begins no well-formed character is emitted as [`TokenKind::Control`] to keep
42//! forward progress, and contributes no width. Tokens always concatenate back
43//! to the input exactly.
44//!
45//! ## Mode interaction
46//!
47//! This module does not interpret terminal modes or sequence semantics. Escape
48//! bytes are passed through as zero-width tokens so callers can preserve or drop
49//! them according to their own policy.
50
51pub use crate::text::WidthMode;
52use crate::unicode::graphemes;
53
54/// The category of a token produced by [`tokenize`].
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum TokenKind {
57    /// One whole, well-formed UTF-8 grapheme cluster.
58    Text,
59    /// An ANSI escape sequence or control string, with zero display width.
60    Escape,
61    /// A standalone C0 control, DEL, C1 control, or malformed byte, with zero display width.
62    Control,
63}
64
65/// A single token produced by [`tokenize`].
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Token<'a> {
68    /// The token category.
69    pub kind: TokenKind,
70    /// The original input bytes, borrowed without modification.
71    ///
72    /// Tokens returned by [`tokenize`] contain a nonempty slice.
73    /// Standalone UTF-8 C1 controls contain `0xC2` followed by the control code.
74    pub bytes: &'a [u8],
75    /// The display width in terminal cells.
76    ///
77    /// Escape and control tokens have width zero. Text width depends on the
78    /// selected width mode and can be zero for combining marks.
79    pub width: u16,
80    /// The decoded byte for a control token, or zero for text and escape tokens.
81    ///
82    /// Raw and UTF-8 C1 encodings produce the same control code.
83    /// A malformed byte retains its byte value here.
84    pub control: u8,
85}
86
87/// Return the display width of `bytes` ignoring ANSI escapes.
88///
89/// Non-UTF-8 bytes contribute no width.
90pub fn string_width(bytes: &[u8], mode: WidthMode, eaw_wide: bool) -> usize {
91    tokenize(bytes, mode, eaw_wide)
92        .map(|t| usize::from(t.width))
93        .sum()
94}
95
96/// Tokenize an input byte slice into ANSI-aware tokens.
97///
98/// The tokens concatenate back to `bytes` exactly; the tokenizer reclassifies
99/// bytes but never invents or drops one. `bytes` need not be valid UTF-8.
100///
101/// See the [module docs](self) for which byte ends a control string, and for
102/// why a byte in `0x80..=0x9F` is a C1 control in one position and part of a
103/// character in another.
104pub fn tokenize(bytes: &[u8], mode: WidthMode, eaw_wide: bool) -> Tokenizer<'_> {
105    Tokenizer {
106        bytes,
107        pos: 0,
108        mode,
109        eaw_wide,
110        scan_end: 0,
111        run: "",
112        #[cfg(test)]
113        scanned: 0,
114        #[cfg(test)]
115        validated: 0,
116    }
117}
118
119/// Iterator returned by [`tokenize`].
120pub struct Tokenizer<'a> {
121    bytes: &'a [u8],
122    pos: usize,
123    mode: WidthMode,
124    eaw_wide: bool,
125    /// Where the current run of plain text ends - the next byte that opens an
126    /// escape or a control token, or that cannot start a UTF-8 character.
127    ///
128    /// The run is what makes this iterator linear. Finding where the plain
129    /// text ends is work proportional to the run's length, and it is done
130    /// once for the run rather than once for each grapheme inside it. `pos`
131    /// then walks the run a grapheme at a time and only crossing `scan_end`
132    /// makes this look again.
133    scan_end: usize,
134    /// The validated remainder of the run, starting at `pos`.
135    ///
136    /// Held separately from `scan_end` on purpose. Malformed UTF-8 ends this
137    /// slice early but says nothing about where the *run* ends, and conflating
138    /// the two made every malformed byte rescan the rest of the input: text
139    /// that was one byte of UTF-8 short cost O(n^2) to tokenize. Keeping the
140    /// two boundaries apart means the scan still happens once per run, and
141    /// only the validation - which stops at the first bad byte, so it is cheap
142    /// exactly when it is repeated - runs again.
143    run: &'a str,
144    /// Bytes visited by the run scan, which is the thing that went quadratic.
145    ///
146    /// It is not visible in the tokens - that is why the bug survived a full
147    /// test suite - and timing it is a benchmark, not a test. So the tests
148    /// count it.
149    #[cfg(test)]
150    scanned: usize,
151    /// Bytes handed to UTF-8 validation, counted separately from `scanned`.
152    ///
153    /// The scan and the validation are two different pieces of work over the
154    /// same run, and only one of them is refreshed at `scan_end`. A version
155    /// that finds the run once but revalidates the remainder on every token
156    /// is quadratic in real time - 4x per doubling, 8 s for a 128 KB line of
157    /// CJK - while visiting each byte exactly once *in the scan*. `scanned`
158    /// alone cannot see that; this can.
159    #[cfg(test)]
160    validated: usize,
161}
162
163impl<'a> Tokenizer<'a> {
164    fn control_token(&mut self, control: u8, size: usize) -> Token<'a> {
165        let start = self.pos;
166        self.pos += size;
167        Token {
168            kind: TokenKind::Control,
169            bytes: &self.bytes[start..self.pos],
170            width: 0,
171            control,
172        }
173    }
174
175    /// Set `run` to the validated text from `pos` up to `to`.
176    ///
177    /// The byte count lives here rather than at the call site on purpose: the
178    /// cost that has to stay linear is "bytes handed to `from_utf8`", so
179    /// moving the validation moves its meter with it. A version that finds the
180    /// run once but revalidates the remainder per token keeps `scanned` at
181    /// exactly one visit per byte while running in quadratic time.
182    #[inline]
183    fn validate(&mut self, to: usize) {
184        let from = self.pos;
185        #[cfg(test)]
186        {
187            self.validated += to - from;
188        }
189        self.run = std::str::from_utf8(&self.bytes[from..to]).unwrap_or("");
190    }
191}
192
193impl<'a> Iterator for Tokenizer<'a> {
194    type Item = Token<'a>;
195
196    fn next(&mut self) -> Option<Token<'a>> {
197        let b = *self.bytes.get(self.pos)?;
198
199        // Printable ASCII followed by ASCII or end-of-input is a whole
200        // cluster. Consume it before scanning or validating a text run.
201        if (0x20..0x7f).contains(&b) && self.bytes.get(self.pos + 1).is_none_or(u8::is_ascii) {
202            let start = self.pos;
203            self.pos += 1;
204            if !self.run.is_empty() {
205                self.run = &self.run[1..];
206            }
207            return Some(Token {
208                kind: TokenKind::Text,
209                bytes: &self.bytes[start..self.pos],
210                width: 1,
211                control: 0,
212            });
213        }
214
215        // Keep escape introducers ahead of the run check for dense sequences.
216        let c1 = c1_at(self.bytes, self.pos);
217        if b == 0x1b || c1.is_some_and(|(control, _)| is_c1_introducer(control)) {
218            let start = self.pos;
219            let end = scan_sequence(self.bytes, start);
220            self.pos = end;
221            return Some(Token {
222                kind: TokenKind::Escape,
223                bytes: &self.bytes[start..end],
224                width: 0,
225                control: 0,
226            });
227        }
228        if let Some((control, size)) = c1 {
229            return Some(self.control_token(control, size));
230        }
231
232        // A cached run contains only validated plain text. Check remaining
233        // control bytes and find a new run only after that run ends.
234        if self.run.is_empty() {
235            // C0 controls and DEL occupy one byte.
236            if b < 0x20 || b == 0x7f {
237                return Some(self.control_token(b, 1));
238            }
239
240            // Plain text — walk forward one grapheme at a time, stopping at any
241            // byte that would start an escape or control token. Stepping per
242            // codepoint when scanning guarantees we never confuse a UTF-8
243            // continuation byte (which can be in 0x80..=0xBF) with a C1 control.
244            //
245            // The scan runs once per *run* of plain text, not once per grapheme
246            // in it. Doing it per grapheme is O(run) work O(run) times, which
247            // made tokenizing a single long line quadratic in its length - a
248            // 32 KB line took 852 ms, and nothing about the tokens it produced
249            // changed, so only a timing test could see it.
250            if self.pos >= self.scan_end {
251                let mut end = self.pos;
252                while end < self.bytes.len() {
253                    let bb = self.bytes[end];
254                    if bb < 0x20 || bb == 0x7f || c1_at(self.bytes, end).is_some() {
255                        break;
256                    }
257                    match utf8_char_at(self.bytes, end) {
258                        Some(n) => end += n,
259                        None => break,
260                    }
261                }
262                #[cfg(test)]
263                {
264                    self.scanned += end.max(self.pos + 1) - self.pos;
265                }
266                self.scan_end = end;
267                // Valid by construction: the scan stopped at the first byte that
268                // does not begin a well-formed character, so this cannot fail.
269                self.validate(end);
270            }
271            if self.run.is_empty() {
272                // Nothing plain starts here, or what does is not valid UTF-8.
273                // Either way the byte is emitted verbatim to keep forward
274                // progress, exactly as an invalid leading byte always was.
275                return Some(self.control_token(b, 1));
276            }
277        }
278        let g = graphemes(self.run).next()?;
279        let start = self.pos;
280        self.pos += g.len();
281        self.run = &self.run[g.len()..];
282        let width = self.mode.grapheme_width(g, self.eaw_wide) as u16;
283        Some(Token {
284            kind: TokenKind::Text,
285            bytes: &self.bytes[start..self.pos],
286            width,
287            control: 0,
288        })
289    }
290}
291
292/// The length of the well-formed UTF-8 character starting at `i`, if there is
293/// one.
294///
295/// A lead byte announces how many bytes follow it, and nothing else in this
296/// file may take that announcement on trust. Bytes that do not follow are the
297/// whole problem: a lead byte with the wrong continuations makes a naive walk
298/// step *over* whatever comes next, which is how a scan can pass a terminator
299/// it should have stopped at, and how the tokenizer's two boundaries came to
300/// disagree about where a character starts.
301fn utf8_char_at(bytes: &[u8], i: usize) -> Option<usize> {
302    let n = utf8_char_len(bytes[i]);
303    if n == 0 || i + n > bytes.len() {
304        return None;
305    }
306    // A one-byte character is ASCII, and `utf8_char_len` already established
307    // that; anything longer has to prove its continuations.
308    if n > 1 && std::str::from_utf8(&bytes[i..i + n]).is_err() {
309        return None;
310    }
311    Some(n)
312}
313
314#[inline]
315fn utf8_char_len(b: u8) -> usize {
316    match b {
317        0x00..=0x7f => 1,
318        0xc2..=0xdf => 2,
319        0xe0..=0xef => 3,
320        0xf0..=0xf4 => 4,
321        _ => 0,
322    }
323}
324
325#[inline]
326fn is_c1_introducer(b: u8) -> bool {
327    matches!(b, 0x90 | 0x98 | 0x9b | 0x9d | 0x9e | 0x9f)
328}
329
330#[inline]
331fn c1_at(bytes: &[u8], at: usize) -> Option<(u8, usize)> {
332    let b = bytes[at];
333    if (0x80..=0x9f).contains(&b) {
334        Some((b, 1))
335    } else if b == 0xc2
336        && let Some(&control @ 0x80..=0x9f) = bytes.get(at + 1)
337    {
338        Some((control, 2))
339    } else {
340        None
341    }
342}
343
344/// Return the byte index past the end of an escape sequence starting at
345/// `start`.
346///
347/// `bytes[start]` starts ESC or a raw or UTF-8 C1 sequence introducer
348/// (`0x9B`, `0x9D`, `0x90`, `0x98`, `0x9E`, `0x9F`). The returned index points
349/// to the first byte after the sequence. If the sequence is incomplete the
350/// index is the end of `bytes`.
351fn scan_sequence(bytes: &[u8], start: usize) -> usize {
352    let len = bytes.len();
353    let (head, size) = c1_at(bytes, start).unwrap_or((bytes[start], 1));
354
355    match head {
356        0x1b => {
357            let i = start + 1;
358            if i >= len {
359                return len;
360            }
361            match bytes[i] {
362                b'[' => scan_csi(bytes, i + 1),
363                // The `true` is "BEL ends this": OSC only.
364                b']' => scan_string(bytes, i + 1, true),
365                b'P' | b'X' | b'^' | b'_' => scan_string(bytes, i + 1, false),
366                _ => scan_esc_intermediate(bytes, i),
367            }
368        }
369        0x9b => scan_csi(bytes, start + size),
370        0x9d => scan_string(bytes, start + size, true),
371        0x90 | 0x98 | 0x9e | 0x9f => scan_string(bytes, start + size, false),
372        _ => start + 1,
373    }
374}
375
376fn scan_csi(bytes: &[u8], from: usize) -> usize {
377    let len = bytes.len();
378    let mut i = from;
379    while i < len {
380        if (0x40..=0x7e).contains(&bytes[i]) {
381            return i + 1;
382        }
383        i += 1;
384    }
385    len
386}
387
388/// Scan a control string to its terminator, which is ST - and also `BEL` if
389/// `bel_ends`, that being an xterm convention for OSC and no other string.
390///
391/// `from` is the byte after the introducer, which for DCS is not yet the
392/// payload: a DCS carries a CSI-shaped command section first, so the shape is
393/// `ESC P` prefix params intermediates final, and only then the string. This
394/// scan does not need to know where that boundary is, because every byte the
395/// command section may hold - prefix `0x3C..=0x3F`, parameters `0x30..=0x3B`,
396/// intermediates `0x20..=0x2F`, final `0x40..=0x7E` - lies inside
397/// `0x20..=0x7E` and so is none of ST, BEL or ESC. Anything that has to treat
398/// the payload differently from the command section, such as the doubled ESC
399/// bytes in a tmux passthrough, does need to find it.
400///
401/// Terminators are only ever tested at a character boundary. `0x9C` is 8-bit
402/// ST between characters and a continuation byte inside one, and every code
403/// point in U+2700..U+273F carries one, so a scan that does not know which it
404/// is looking at ends the sequence in the middle of "✅".
405fn scan_string(bytes: &[u8], from: usize, bel_ends: bool) -> usize {
406    let len = bytes.len();
407    let mut i = from;
408    while i < len {
409        let b = bytes[i];
410        if let Some((0x9c, size)) = c1_at(bytes, i) {
411            return i + size;
412        }
413        if b == 0x07 && bel_ends {
414            return i + 1;
415        }
416        if b == 0x1b && i + 1 < len && bytes[i + 1] == b'\\' {
417            return i + 2;
418        }
419        // Lone ESC (without trailing `\`) terminates the string but is left
420        // to be re-parsed as the next sequence.
421        if b == 0x1b {
422            return i;
423        }
424        // Collect a whole character, so the bytes inside it are never tested
425        // as terminators. Only a *well-formed* one: trusting a lead byte
426        // whose continuations do not match would step over whatever followed
427        // it, terminators included, and one malformed byte in a payload would
428        // swallow the BEL that ends it and all the text after.
429        i += utf8_char_at(bytes, i).unwrap_or(1);
430    }
431    len
432}
433
434fn scan_esc_intermediate(bytes: &[u8], at: usize) -> usize {
435    let len = bytes.len();
436    let mut i = at;
437    while i < len && (0x20..=0x2f).contains(&bytes[i]) {
438        i += 1;
439    }
440    if i < len {
441        // The final byte, or the whole character it leads - splitting one
442        // strands continuation bytes that the next token reads as C1
443        // controls.
444        i + utf8_char_at(bytes, i).unwrap_or(1)
445    } else {
446        len
447    }
448}
449
450/// Helpers shared by the test modules below.
451#[cfg(test)]
452mod util {
453    use super::*;
454
455    pub(super) fn text_token(bytes: &[u8], width: u16) -> Token<'_> {
456        Token {
457            kind: TokenKind::Text,
458            bytes,
459            width,
460            control: 0,
461        }
462    }
463
464    pub(super) fn escape_token(bytes: &[u8]) -> Token<'_> {
465        Token {
466            kind: TokenKind::Escape,
467            bytes,
468            width: 0,
469            control: 0,
470        }
471    }
472
473    pub(super) fn control_token(bytes: &[u8]) -> Token<'_> {
474        Token {
475            kind: TokenKind::Control,
476            bytes,
477            width: 0,
478            control: *bytes.last().unwrap(),
479        }
480    }
481
482    pub(super) fn tokens(input: &[u8]) -> Vec<Token<'_>> {
483        tokenize(input, WidthMode::Grapheme, false).collect()
484    }
485
486    /// The visible text of a token stream, which is what a caller loses when
487    /// a sequence runs past its terminator or a character is cut in half.
488    ///
489    /// Not lossy: a text token that is not whole UTF-8 is a bug, and
490    /// rendering it as U+FFFD hides the failure these tests exist to catch.
491    pub(super) fn visible(toks: &[Token<'_>]) -> String {
492        toks.iter()
493            .filter(|t| t.kind == TokenKind::Text)
494            .map(|t| std::str::from_utf8(t.bytes).expect("a text token is whole UTF-8"))
495            .collect()
496    }
497
498    /// Concatenate a token stream back into bytes. It must equal the input:
499    /// the tokenizer may reclassify a byte but must never invent or drop one.
500    pub(super) fn rebuild(toks: &[Token<'_>]) -> Vec<u8> {
501        let mut out = Vec::new();
502        for t in toks {
503            out.extend_from_slice(t.bytes);
504        }
505        out
506    }
507
508    /// A control function in 7-bit, raw C1, and UTF-8 C1 forms.
509    pub(super) fn forms(seven: &[u8], eight: u8) -> [(&'static str, Vec<u8>); 3] {
510        [
511            ("7-bit", seven.to_vec()),
512            ("8-bit", vec![eight]),
513            ("UTF-8", vec![0xc2, eight]),
514        ]
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use super::util::*;
521    use super::*;
522
523    #[test]
524    fn token_fields_preserve_bytes_widths_and_control_codes() {
525        let input = b"A\x1b[31m\t\x85\xc2\x85\xff\xe4\xb8\xad";
526        let expected = [
527            text_token(b"A", 1),
528            escape_token(b"\x1b[31m"),
529            control_token(b"\t"),
530            control_token(b"\x85"),
531            control_token(b"\xc2\x85"),
532            control_token(b"\xff"),
533            text_token(b"\xe4\xb8\xad", 2),
534        ];
535        for mode in [WidthMode::Wc, WidthMode::Grapheme] {
536            let toks: Vec<_> = tokenize(input, mode, false).collect();
537            assert_eq!(toks, expected);
538            let mut offset = 0;
539            for token in &toks {
540                assert_eq!(token.bytes.as_ptr(), input[offset..].as_ptr());
541                offset += token.bytes.len();
542            }
543        }
544    }
545
546    #[test]
547    fn tokenize_csi() {
548        let toks: Vec<_> = tokenize(b"\x1b[31mhi\x1b[m", WidthMode::Grapheme, false).collect();
549        assert_eq!(toks.len(), 4);
550        assert_eq!(toks[0], escape_token(b"\x1b[31m"));
551        assert_eq!(toks[3], escape_token(b"\x1b[m"));
552    }
553
554    #[test]
555    fn utf8_c1_sequences_are_zero_width() {
556        for input in [
557            &b"\x9b31mhello\x9bm"[..],
558            b"\xc2\x9b31mhello\xc2\x9bm",
559            b"\xc2\x9d8;;https://example.com\xc2\x9chello\xc2\x9d8;;\xc2\x9c",
560        ] {
561            for mode in [WidthMode::Wc, WidthMode::Grapheme] {
562                assert_eq!(string_width(input, mode, false), 5, "{input:x?}");
563            }
564        }
565    }
566
567    #[test]
568    fn tokenize_osc_bel() {
569        let toks: Vec<_> = tokenize(b"\x1b]0;title\x07rest", WidthMode::Grapheme, false).collect();
570        assert_eq!(toks[0], escape_token(b"\x1b]0;title\x07"));
571    }
572
573    #[test]
574    fn tokenize_osc_st() {
575        let toks: Vec<_> =
576            tokenize(b"\x1b]0;title\x1b\\rest", WidthMode::Grapheme, false).collect();
577        assert_eq!(toks[0], escape_token(b"\x1b]0;title\x1b\\"));
578    }
579
580    #[test]
581    fn tokenize_wide_char() {
582        let toks: Vec<_> = tokenize("中".as_bytes(), WidthMode::Grapheme, false).collect();
583        assert_eq!(toks.len(), 1);
584        assert_eq!(toks[0], text_token("中".as_bytes(), 2));
585    }
586
587    #[test]
588    fn tokenize_newline_control() {
589        let toks: Vec<_> = tokenize(b"a\nb", WidthMode::Grapheme, false).collect();
590        assert_eq!(toks.len(), 3);
591        assert_eq!(toks[1], control_token(b"\n"));
592    }
593
594    #[test]
595    fn string_width_ignores_escapes() {
596        assert_eq!(
597            string_width(b"\x1b[31mhello\x1b[m", WidthMode::Grapheme, false),
598            5
599        );
600        assert_eq!(
601            string_width("中文".as_bytes(), WidthMode::Grapheme, false),
602            4
603        );
604    }
605
606    #[test]
607    fn tokenize_8bit_csi() {
608        let toks: Vec<_> = tokenize(b"\x9b31mhi\x9bm", WidthMode::Grapheme, false).collect();
609        assert_eq!(toks[0], escape_token(b"\x9b31m"));
610        assert_eq!(toks[3], escape_token(b"\x9bm"));
611    }
612
613    #[test]
614    fn tokenize_8bit_osc_with_8bit_st() {
615        // 0x9d "0;title" 0x9c "rest"
616        let toks: Vec<_> = tokenize(b"\x9d0;title\x9crest", WidthMode::Grapheme, false).collect();
617        assert_eq!(toks[0], escape_token(b"\x9d0;title\x9c"));
618        // "rest" tokenizes to 4 single-grapheme Text tokens.
619        assert_eq!(toks.len(), 5);
620    }
621
622    #[test]
623    fn tokenize_8bit_dcs() {
624        let toks: Vec<_> = tokenize(b"\x90q!data\x9cafter", WidthMode::Grapheme, false).collect();
625        assert_eq!(toks[0], escape_token(b"\x90q!data\x9c"));
626    }
627
628    #[test]
629    fn tokenize_8bit_sos_pm_apc() {
630        for &intro in &[0x98u8, 0x9e, 0x9f] {
631            let mut input = vec![intro];
632            input.extend_from_slice(b"payload");
633            input.push(0x9c);
634            let toks: Vec<_> = tokenize(&input, WidthMode::Grapheme, false).collect();
635            assert_eq!(toks[0], escape_token(&input));
636        }
637    }
638
639    #[test]
640    fn tokenize_standalone_c1_is_control() {
641        // IND (0x84) standalone — not an introducer, emitted as Control.
642        let toks: Vec<_> = tokenize(b"a\x84b", WidthMode::Grapheme, false).collect();
643        assert_eq!(toks.len(), 3);
644        assert_eq!(toks[1], control_token(b"\x84"));
645    }
646
647    #[test]
648    fn tokenize_two_byte_esc() {
649        // ESC = (DECKPAM)
650        let toks: Vec<_> = tokenize(b"a\x1b=b", WidthMode::Grapheme, false).collect();
651        assert_eq!(toks.len(), 3);
652        assert_eq!(toks[1], escape_token(b"\x1b="));
653    }
654}
655
656/// The five string sequences - OSC, DCS, SOS, PM, APC - across both control
657/// forms, every terminator, and payloads that do and do not contain UTF-8.
658///
659/// These share one scanner, so they share one bug. The `0x9C` split that made
660/// this file's `from_utf8_unchecked` calls undefined behaviour was found in an
661/// OSC title, but it was never an OSC bug: DCS, SOS, PM and APC all reached
662/// the same code, and only OSC was tested. A payload is arbitrary text, so any
663/// of them can carry a character whose continuation bytes look like a
664/// terminator.
665#[cfg(test)]
666mod sequences {
667    use super::util::*;
668    use super::*;
669
670    /// `(name, 7-bit introducer, 8-bit introducer)`.
671    const STRINGS: &[(&str, &[u8], u8)] = &[
672        ("OSC", b"\x1b]", 0x9d),
673        ("DCS", b"\x1bP", 0x90),
674        ("SOS", b"\x1bX", 0x98),
675        ("PM", b"\x1b^", 0x9e),
676        ("APC", b"\x1b_", 0x9f),
677    ];
678
679    /// Every way a string sequence may end.
680    ///
681    /// `BEL` is in here for OSC only; the loop skips it elsewhere.
682    const TERMINATORS: &[(&str, &[u8])] = &[
683        ("BEL", b"\x07"),
684        ("ESC backslash", b"\x1b\\"),
685        ("8-bit ST", b"\x9c"),
686        ("UTF-8 ST", b"\xc2\x9c"),
687    ];
688
689    /// Payloads with and without UTF-8. The non-ASCII one is chosen for the
690    /// bytes it contains, not for how it reads: `é` is `C3 A9`, `✅` is
691    /// `E2 9C 85` and carries a `0x9C`, `一` is `E4 B8 80`, and `😀` is a
692    /// four-byte character.
693    const PAYLOADS: &[(&str, &str)] = &[
694        ("ascii", "0;plain title"),
695        ("utf8", "0;caf\u{e9} \u{2705} \u{4e00} \u{1f600}"),
696    ];
697
698    /// Whatever the type, the form, the payload or the terminator, the whole
699    /// sequence is exactly one zero-width token and the text after it
700    /// survives intact.
701    #[test]
702    fn every_string_sequence_is_one_whole_token() {
703        for (name, seven, eight) in STRINGS {
704            for (pname, payload) in PAYLOADS {
705                for (tname, term) in TERMINATORS {
706                    if *term == b"\x07" && *name != "OSC" {
707                        continue;
708                    }
709                    for (form, intro) in forms(seven, *eight) {
710                        let mut input = intro;
711                        input.extend_from_slice(payload.as_bytes());
712                        input.extend_from_slice(term);
713                        let seq_len = input.len();
714                        input.extend_from_slice("after \u{2705}".as_bytes());
715
716                        let what = format!("{name} {form} {pname} payload, {tname} terminator");
717                        let toks = tokens(&input);
718                        assert_eq!(
719                            toks.first(),
720                            Some(&escape_token(&input[..seq_len])),
721                            "{what}: the sequence is not one token"
722                        );
723                        assert_eq!(
724                            visible(&toks[1..]),
725                            "after \u{2705}",
726                            "{what}: text after was lost"
727                        );
728                        // The sequence itself is invisible.
729                        assert_eq!(
730                            string_width(&input, WidthMode::Grapheme, false),
731                            8,
732                            "{what}: the sequence was measured"
733                        );
734                    }
735                }
736            }
737        }
738    }
739
740    /// A payload that runs off the end is still one token, not a stream of
741    /// stray control bytes.
742    #[test]
743    fn an_unterminated_string_sequence_runs_to_the_end() {
744        for (name, seven, eight) in STRINGS {
745            for (form, intro) in forms(seven, *eight) {
746                for (pname, payload) in PAYLOADS {
747                    let mut input = intro.clone();
748                    input.extend_from_slice(payload.as_bytes());
749                    let toks = tokens(&input);
750                    assert_eq!(
751                        toks,
752                        vec![escape_token(&input[..])],
753                        "{name} {form} {pname}: an unterminated sequence should be one token"
754                    );
755                    assert_eq!(string_width(&input, WidthMode::Grapheme, false), 0);
756                }
757            }
758        }
759    }
760
761    /// A lone ESC ends the string and is left to open the next sequence, so a
762    /// sequence cannot swallow the one that follows it.
763    #[test]
764    fn a_lone_esc_ends_a_string_and_is_reparsed() {
765        for (name, seven, eight) in STRINGS {
766            for (form, intro) in forms(seven, *eight) {
767                let mut input = intro.clone();
768                input.extend_from_slice("pay\u{2705}".as_bytes());
769                let cut = input.len();
770                input.extend_from_slice(b"\x1b[31mZ");
771
772                let toks = tokens(&input);
773                assert_eq!(
774                    toks[0],
775                    escape_token(&input[..cut]),
776                    "{name} {form}: the string should stop at the ESC"
777                );
778                assert_eq!(
779                    toks[1],
780                    escape_token(b"\x1b[31m"),
781                    "{name} {form}: the CSI after it should survive whole"
782                );
783                assert_eq!(toks[2], text_token(b"Z", 1));
784            }
785        }
786    }
787
788    /// Two sequences back to back, in either control form, stay two.
789    #[test]
790    fn adjacent_sequences_do_not_merge() {
791        // (input, first sequence, second sequence); the input names the case.
792        let cases: &[(&[u8], &[u8], &[u8])] = &[
793            // 7-bit OSC then 7-bit DCS.
794            (
795                b"\x1b]0;a\x07\x1bPq\x1b\\Z",
796                b"\x1b]0;a\x07",
797                b"\x1bPq\x1b\\",
798            ),
799            // 8-bit APC then 8-bit PM.
800            (b"\x9fa\x9c\x9eb\x9cZ", b"\x9fa\x9c", b"\x9eb\x9c"),
801            // An 8-bit introducer closed by 7-bit ST, then a 7-bit introducer
802            // closed by 8-bit ST: both mixed forms, adjacent.
803            (b"\x9d0;a\x1b\\\x1b^b\x9cZ", b"\x9d0;a\x1b\\", b"\x1b^b\x9c"),
804        ];
805        for (input, first, second) in cases {
806            let toks = tokens(input);
807            assert_eq!(toks[0], escape_token(first), "{input:x?}");
808            assert_eq!(toks[1], escape_token(second), "{input:x?}");
809            assert_eq!(toks[2], text_token(b"Z", 1), "{input:x?}");
810        }
811    }
812
813    /// Sequences as they actually arrive from terminals and applications.
814    #[test]
815    fn real_payloads_survive() {
816        // (what, input, the opening sequence, the visible text)
817        let cases: &[(&str, &[u8], &[u8], &str)] = &[
818            (
819                "sixel",
820                b"\x1bPq#0;2;0;0;0#1;2;100;100;100\x1b\\ok",
821                b"\x1bPq#0;2;0;0;0#1;2;100;100;100\x1b\\",
822                "ok",
823            ),
824            (
825                "DECRQSS reply",
826                b"\x1bP1$r0;1m\x1b\\ok",
827                b"\x1bP1$r0;1m\x1b\\",
828                "ok",
829            ),
830            (
831                "OSC 8 hyperlink with a UTF-8 target",
832                b"\x1b]8;;https://example.com/\xe2\x9c\x85\x07link\x1b]8;;\x07",
833                b"\x1b]8;;https://example.com/\xe2\x9c\x85\x07",
834                "link",
835            ),
836            (
837                "OSC with an empty payload",
838                b"\x1b]\x07ok",
839                b"\x1b]\x07",
840                "ok",
841            ),
842            (
843                "8-bit APC with an empty payload",
844                b"\x9f\x9cok",
845                b"\x9f\x9c",
846                "ok",
847            ),
848        ];
849        for (what, input, opening, want) in cases {
850            let toks = tokens(input);
851            assert_eq!(toks.first(), Some(&escape_token(opening)), "{what}");
852            assert_eq!(visible(&toks), *want, "{what}");
853            // Nothing is invented or dropped anywhere in the stream.
854            assert_eq!(
855                rebuild(&toks),
856                *input,
857                "{what}: the stream did not reassemble"
858            );
859        }
860    }
861
862    #[test]
863    fn c1_encodings_preserve_sequence_boundaries() {
864        for input in [
865            &b"\x1b]0;title\x9cZ"[..],
866            b"\x1b]0;title\xc2\x9cZ",
867            b"\x9d0;title\x07Z",
868            b"\xc2\x9d0;title\x07Z",
869            b"\x1b]0;\xe2\x9c\x85\x07Z",
870        ] {
871            let toks = tokens(input);
872            assert_eq!(toks[0], escape_token(&input[..input.len() - 1]));
873            assert_eq!(visible(&toks), "Z");
874            assert_eq!(rebuild(&toks), input);
875        }
876    }
877
878    /// `BEL` ends an OSC and only an OSC.
879    ///
880    /// `OSC Ps ; Pt BEL` is an xterm convention, and the common way to write
881    /// one, but it is not a rule about control strings in general - ECMA-48
882    /// gives them all a single terminator, ST. A `0x07` inside a DCS, SOS, PM
883    /// or APC is payload, and ending the sequence there would spill the rest
884    /// of that payload onto the screen as visible text.
885    #[test]
886    fn bel_ends_an_osc_and_nothing_else() {
887        for (name, seven, eight) in STRINGS {
888            for (form, intro) in forms(seven, *eight) {
889                let mut input = intro;
890                input.extend_from_slice(b"pay\x07load");
891                let bel_at = input.len() - b"load".len();
892                input.extend_from_slice(b"\x9cZ");
893
894                let toks = tokens(&input);
895                let what = format!("{name} {form}");
896                if *name == "OSC" {
897                    assert_eq!(
898                        toks[0],
899                        escape_token(&input[..bel_at]),
900                        "{what}: BEL should have ended it"
901                    );
902                    // What followed the BEL is now visible text.
903                    assert!(
904                        toks.iter()
905                            .any(|t| t.kind == TokenKind::Text && t.bytes == b"l"),
906                        "{what}: text after the BEL went missing"
907                    );
908                } else {
909                    assert_eq!(
910                        toks[0],
911                        escape_token(&input[..input.len() - 1]),
912                        "{what}: BEL is payload, so it should have run to the ST"
913                    );
914                    assert_eq!(toks[1], text_token(b"Z", 1), "{what}");
915                    assert_eq!(string_width(&input, WidthMode::Grapheme, false), 1);
916                }
917            }
918        }
919    }
920
921    #[test]
922    fn every_c1_control_preserves_its_encoding() {
923        for c in 0x80u8..=0x9f {
924            for input in [vec![c], vec![0xc2, c]] {
925                for mode in [WidthMode::Wc, WidthMode::Grapheme] {
926                    let toks: Vec<_> = tokenize(&input, mode, false).collect();
927                    let expected = if is_c1_introducer(c) {
928                        escape_token(&input)
929                    } else {
930                        control_token(&input)
931                    };
932                    assert_eq!(toks, [expected]);
933                    assert_eq!(string_width(&input, mode, false), 0);
934
935                    let payload = [b"\x1b]0;", input.as_slice(), b"Z\x07"].concat();
936                    let expected_len = if c == 0x9c {
937                        4 + input.len()
938                    } else {
939                        payload.len()
940                    };
941                    assert_eq!(
942                        tokenize(&payload, mode, false).next(),
943                        Some(escape_token(&payload[..expected_len])),
944                    );
945                }
946            }
947        }
948    }
949}
950
951#[cfg(test)]
952mod utf8_c1 {
953    use super::{util::*, *};
954    use crate::ansi::{strip::strip, truncate, wrap};
955
956    #[test]
957    fn text_utilities_preserve_standalone_control_encoding() {
958        let input = std::str::from_utf8(b"ab\xc2\x80cdef").unwrap();
959        assert_eq!(strip(input), input);
960        assert_eq!(
961            wrap::hardwrap(input, 3, true).as_bytes(),
962            b"ab\xc2\x80c\ndef"
963        );
964        for result in [
965            wrap::wordwrap(
966                std::str::from_utf8(b"ab\xc2\x80 cd").unwrap(),
967                2,
968                wrap::DEFAULT_BREAKPOINTS,
969            ),
970            wrap::wrap(
971                std::str::from_utf8(b"ab\xc2\x80 cd").unwrap(),
972                2,
973                wrap::DEFAULT_BREAKPOINTS,
974            ),
975        ] {
976            assert_eq!(result.as_bytes(), b"ab\xc2\x80\ncd");
977        }
978        assert_eq!(truncate::truncate(input, 4, "").as_bytes(), b"ab\xc2\x80cd");
979        assert_eq!(
980            truncate::truncate_left(input, 4, "").as_bytes(),
981            b"\xc2\x80cdef"
982        );
983        assert_eq!(truncate::cut(input, 1, 1).as_bytes(), b"b\xc2\x80cde");
984    }
985
986    #[test]
987    fn text_utilities_preserve_encoded_sequences() {
988        let input = std::str::from_utf8(b"\xc2\x9b31mabcdef\xc2\x9bm").unwrap();
989        assert_eq!(strip(input), "abcdef");
990        assert_eq!(
991            wrap::hardwrap(input, 3, true).as_bytes(),
992            b"\xc2\x9b31mabc\ndef\xc2\x9bm"
993        );
994        assert_eq!(
995            truncate::truncate(input, 4, "").as_bytes(),
996            b"\xc2\x9b31mabcd\xc2\x9bm"
997        );
998        assert_eq!(
999            truncate::truncate_left(input, 4, "").as_bytes(),
1000            b"\xc2\x9b31mcdef\xc2\x9bm"
1001        );
1002        assert_eq!(
1003            truncate::cut(input, 1, 1).as_bytes(),
1004            b"\xc2\x9b31mbcde\xc2\x9bm"
1005        );
1006    }
1007
1008    #[test]
1009    fn other_two_byte_characters_remain_text() {
1010        for lead in 0xc2..=0xdf {
1011            for tail in 0x80..=0xbf {
1012                if lead == 0xc2 && tail <= 0x9f {
1013                    continue;
1014                }
1015                let input = [lead, tail];
1016                let toks = tokens(&input);
1017                assert_eq!(toks.len(), 1);
1018                assert_eq!(toks[0].kind, TokenKind::Text);
1019                assert_eq!(toks[0].bytes, input);
1020            }
1021        }
1022    }
1023
1024    #[test]
1025    fn malformed_leads_preserve_encoded_controls_and_progress() {
1026        for input in [
1027            &b"\xc2\xc2\x9b31mZ"[..],
1028            b"\xe0\xc2\x9d0;title\xc2\x9cZ",
1029            b"\xc2\x1b]0;title\xc2\x9cZ",
1030        ] {
1031            let toks = tokens(input);
1032            assert_eq!(visible(&toks), "Z");
1033            assert_eq!(rebuild(&toks), input);
1034        }
1035    }
1036}
1037
1038#[cfg(test)]
1039mod fast_path {
1040    use super::util::*;
1041    use super::*;
1042
1043    #[test]
1044    fn cached_runs_stop_before_controls_escapes_and_invalid_bytes() {
1045        let before = "ab中e\u{301}".as_bytes();
1046        let after = "xy界".as_bytes();
1047        for boundary in [
1048            &b"\n"[..],
1049            b"\x7f",
1050            b"\x9c",
1051            b"\xc2\x9c",
1052            b"\xff",
1053            b"\x1b[31m",
1054            b"\x9b31m",
1055            b"\xc2\x9b31m",
1056            b"\xc2\x9d0;title\xc2\x9c",
1057            b"\x1b]0;title\x07",
1058            b"\x1bPpayload\x1b\\",
1059        ] {
1060            let input = [before, boundary, after].concat();
1061            for mode in [WidthMode::Wc, WidthMode::Grapheme] {
1062                for eaw_wide in [false, true] {
1063                    let expected: Vec<_> = [before, boundary, after]
1064                        .into_iter()
1065                        .flat_map(|part| tokenize(part, mode, eaw_wide))
1066                        .collect();
1067                    let mut iter = tokenize(&input, mode, eaw_wide);
1068                    assert_eq!(iter.by_ref().collect::<Vec<_>>(), expected);
1069                    assert_eq!(iter.next(), None);
1070                }
1071            }
1072        }
1073    }
1074
1075    fn text_tokens_eaw(s: &str, mode: WidthMode, eaw_wide: bool) -> Vec<(String, u16)> {
1076        tokenize(s.as_bytes(), mode, eaw_wide)
1077            .filter(|t| t.kind == TokenKind::Text)
1078            .map(|t| {
1079                // Not lossy: a token that is not valid UTF-8 is a bug, and
1080                // rendering it as U+FFFD hides exactly the failure these
1081                // tests exist to catch.
1082                (
1083                    std::str::from_utf8(t.bytes)
1084                        .expect("a text token is whole UTF-8")
1085                        .to_owned(),
1086                    t.width,
1087                )
1088            })
1089            .collect()
1090    }
1091
1092    /// The ASCII shortcut must agree with grapheme segmentation, cluster for
1093    /// cluster, in both width modes.
1094    ///
1095    /// The shortcut answers "one ASCII byte, one column" without consulting
1096    /// Unicode at all, which is only sound while nothing can join to an ASCII
1097    /// base from the byte after it. Everything that can - a combining mark, a
1098    /// zero-width joiner, a variation selector, a regional indicator - begins
1099    /// at 0x80 or above in UTF-8, so the shortcut declines whenever the next
1100    /// byte is not ASCII. These are the cases on either side of that line.
1101    #[test]
1102    fn the_ascii_shortcut_agrees_with_grapheme_segmentation() {
1103        for mode in [WidthMode::Wc, WidthMode::Grapheme] {
1104            for eaw_wide in [false, true] {
1105                let toks = |s: &str| text_tokens_eaw(s, mode, eaw_wide);
1106                assert_eq!(
1107                    toks("abc"),
1108                    vec![("a".into(), 1), ("b".into(), 1), ("c".into(), 1)],
1109                    "plain ASCII is one column per byte"
1110                );
1111                // A combining acute joins the `e` before it: one cluster, and
1112                // the shortcut must not have claimed that `e` on its own.
1113                assert_eq!(
1114                    toks("e\u{301}f"),
1115                    vec![("e\u{301}".into(), 1), ("f".into(), 1)],
1116                    "a combining mark still joins the ASCII base before it"
1117                );
1118                assert_eq!(
1119                    toks("a"),
1120                    vec![("a".into(), 1)],
1121                    "the last byte of the input takes the shortcut too"
1122                );
1123                // A variation selector and a keycap sequence both extend an
1124                // ASCII base from bytes at 0x80 and above.
1125                assert_eq!(
1126                    toks("1\u{fe0f}\u{20e3}z"),
1127                    vec![("1\u{fe0f}\u{20e3}".into(), 1), ("z".into(), 1)],
1128                    "a keycap keeps its ASCII digit"
1129                );
1130                // A zero-width joiner cannot follow ASCII in any real text,
1131                // but it must not be able to strand one either.
1132                assert_eq!(
1133                    toks("a\u{200d}b"),
1134                    vec![("a\u{200d}".into(), 1), ("b".into(), 1)],
1135                    "a ZWJ joins the ASCII base before it"
1136                );
1137                // The shortcut never applies across a non-ASCII byte, so a
1138                // wide character keeps its two columns and its neighbours
1139                // keep one each.
1140                assert_eq!(
1141                    toks("a\u{4e00}b"),
1142                    vec![("a".into(), 1), ("\u{4e00}".into(), 2), ("b".into(), 1)],
1143                    "a wide character between two ASCII ones is still wide"
1144                );
1145            }
1146        }
1147        // The ambiguous-width block is the only thing `eaw_wide` moves, and
1148        // it must not move the ASCII on either side of it.
1149        assert_eq!(
1150            text_tokens_eaw("a\u{2018}b", WidthMode::Wc, false),
1151            vec![("a".into(), 1), ("\u{2018}".into(), 1), ("b".into(), 1)]
1152        );
1153        assert_eq!(
1154            text_tokens_eaw("a\u{2018}b", WidthMode::Wc, true),
1155            vec![("a".into(), 1), ("\u{2018}".into(), 2), ("b".into(), 1)]
1156        );
1157    }
1158
1159    /// The fast path emits text only for printable ASCII.
1160    ///
1161    /// Its `0x20..0x7f` range excludes C0 controls and DEL, even though the
1162    /// shortcut runs before control handling. This test checks every
1163    /// seven-bit byte: printable ASCII has width one, controls stay controls,
1164    /// and ESC opens an escape sequence.
1165    #[test]
1166    fn controls_never_reach_the_ascii_shortcut() {
1167        for b in 0u8..=0x7f {
1168            let input = [b];
1169            let toks: Vec<_> = tokenize(&input, WidthMode::Wc, false).collect();
1170            match toks.as_slice() {
1171                [
1172                    Token {
1173                        kind: TokenKind::Text,
1174                        bytes,
1175                        width,
1176                        control,
1177                    },
1178                ] => {
1179                    assert!(
1180                        (0x20..=0x7e).contains(&b),
1181                        "0x{b:02x} was emitted as text, but only printable ASCII may be"
1182                    );
1183                    assert_eq!(*bytes, &input[..]);
1184                    assert_eq!(*width, 1);
1185                    assert_eq!(*control, 0);
1186                }
1187                [token] if token.kind == TokenKind::Control => {
1188                    assert_eq!(*token, control_token(&input));
1189                    assert!(
1190                        b < 0x20 || b == 0x7f,
1191                        "0x{b:02x} is printable but was emitted as a control"
1192                    );
1193                }
1194                // A bare ESC opens a sequence with nothing in it.
1195                [token] if token.kind == TokenKind::Escape => {
1196                    assert_eq!(*token, escape_token(b"\x1b"));
1197                }
1198                other => panic!("0x{b:02x} produced {other:?}"),
1199            }
1200        }
1201    }
1202
1203    /// An OSC payload may contain any UTF-8, and `0x9C` appears inside a great
1204    /// many characters as a continuation byte. Terminating the string there
1205    /// cut those characters in half, which left the trailing bytes of one
1206    /// outside the escape token - where the rest of the crate, reasonably,
1207    /// treated a token it had been told was text as UTF-8.
1208    #[test]
1209    fn a_continuation_byte_does_not_terminate_a_string_sequence() {
1210        // Every scanner that steps through a payload, not just the OSC one.
1211        // `scan_esc_intermediate` has the same bug and the same fix, and a
1212        // test that only builds OSC titles leaves half of it uncovered.
1213        const PREFIXES: &[&[u8]] = &[
1214            b"\x1b]0;", b"\x1bP", b"\x1b_", b"\x1b^", b"\x1bX", b"\x1b", b"\x1b ", b"\x1b#",
1215        ];
1216        for c in [
1217            '\u{2705}',
1218            '\u{2714}',
1219            '\u{2728}',
1220            '\u{171c}',
1221            '\u{4e00}',
1222            '\u{1f600}',
1223        ] {
1224            for prefix in PREFIXES {
1225                // Controls as bytes, the character as a character.
1226                let mut input = prefix.to_vec();
1227                input.extend_from_slice(c.to_string().as_bytes());
1228                input.extend_from_slice(b"\x07after");
1229                for t in tokenize(&input, WidthMode::Wc, false) {
1230                    if t.kind == TokenKind::Control {
1231                        continue;
1232                    }
1233                    let bytes = t.bytes;
1234                    assert!(
1235                        std::str::from_utf8(bytes).is_ok(),
1236                        "{input:x?} produced a token split mid-character: {bytes:x?}"
1237                    );
1238                }
1239            }
1240        }
1241        // The OSC case in full: the sequence stays whole and the text after it
1242        // survives.
1243        for c in ['\u{2705}', '\u{2714}', '\u{2728}', '\u{171c}'] {
1244            let mut input = b"\x1b]0;Build ".to_vec();
1245            input.extend_from_slice(c.to_string().as_bytes());
1246            input.extend_from_slice(b"\x07after");
1247            let toks: Vec<_> = tokenize(&input, WidthMode::Wc, false).collect();
1248            let (escape, rest) = toks.split_first().expect("a token");
1249            let mut want = b"\x1b]0;Build ".to_vec();
1250            want.extend_from_slice(c.to_string().as_bytes());
1251            want.push(0x07);
1252            assert_eq!(*escape, escape_token(&want), "the sequence is whole");
1253            assert_eq!(visible(rest), "after");
1254        }
1255        // A bare ESC takes the whole character after it, not its lead byte.
1256        let toks: Vec<_> = tokenize(b"\x1b\xe2\x9c\x85x", WidthMode::Wc, false).collect();
1257        assert_eq!(toks[0], escape_token(b"\x1b\xe2\x9c\x85"));
1258        // A `0x9C` on a character boundary is still an 8-bit ST.
1259        let toks: Vec<_> = tokenize(b"\x1b]0;t\x9cx", WidthMode::Wc, false).collect();
1260        assert_eq!(toks[0], escape_token(b"\x1b]0;t\x9c"));
1261    }
1262
1263    /// A malformed byte in a payload must not eat the terminator.
1264    ///
1265    /// Stepping a whole character on the strength of a lead byte alone steps
1266    /// over whatever actually follows it. A stray high byte then swallowed
1267    /// the BEL or `ESC \` that ends the sequence, and with it every visible
1268    /// character after - and could consume a following legitimate CSI whole.
1269    #[test]
1270    fn a_malformed_byte_does_not_swallow_a_terminator() {
1271        let cases: &[(&[u8], &[u8])] = &[
1272            (b"\x1b]0;\xe0\x07Zz", b"\x1b]0;\xe0\x07"),
1273            (b"\x1b]0;\xf0\x1b\\Zz", b"\x1b]0;\xf0\x1b\\"),
1274            (b"\x1b]0;\xe0\x9cZz", b"\x1b]0;\xe0\x9c"),
1275            (b"\x1b_G\xf0\x9f\x1b\\Zz", b"\x1b_G\xf0\x9f\x1b\\"),
1276            (b"\x1b]0;\xc2\x07visible", b"\x1b]0;\xc2\x07"),
1277        ];
1278        for (input, escape) in cases {
1279            let toks: Vec<_> = tokenize(input, WidthMode::Wc, false).collect();
1280            assert_eq!(
1281                toks.first(),
1282                Some(&escape_token(escape)),
1283                "input {input:x?} did not stop at its terminator"
1284            );
1285            assert!(
1286                !visible(&toks).is_empty(),
1287                "input {input:x?} lost all its text"
1288            );
1289        }
1290        // A bare ESC must not consume the CSI that follows a malformed byte.
1291        let toks: Vec<_> = tokenize(b"\x1b\xe0\x1b[31mZ", WidthMode::Wc, false).collect();
1292        assert_eq!(toks[0], escape_token(b"\x1b\xe0"));
1293        assert_eq!(toks[1], escape_token(b"\x1b[31m"));
1294    }
1295
1296    /// Arbitrary bytes must not panic, and must not produce a token that
1297    /// splits a character.
1298    ///
1299    /// `tokenize` and `string_width` take `&[u8]`, so this is reachable from
1300    /// the public API by anyone reading a PTY. The run cache holds a byte
1301    /// offset and a validated `&str` and they have to agree about where a
1302    /// character starts; when the scan trusted a lead byte its continuations
1303    /// did not match, they disagreed, and slicing the run panicked.
1304    #[test]
1305    fn arbitrary_bytes_never_panic_or_split_a_character() {
1306        // The token stream is pinned, not just checked for well-formedness.
1307        // The desync had a quieter failure mode than the panic: a run cache
1308        // that disagrees with itself demotes perfectly good characters to
1309        // `Control` bytes, which round-trips and splits nothing while losing
1310        // every character after the first bad byte. These are the merge-base
1311        // streams, byte for byte.
1312        let pinned: &[(&[u8], &str)] = &[
1313            (
1314                b"\xe0\x20\x0d\xef\xb8\x8f",
1315                "C[e0] T[20]w1 C[0d] T[ef, b8, 8f]w0",
1316            ),
1317            (
1318                b"\xf0\x30\x0d\x5b\xe2\x9c\x85\x30",
1319                "C[f0] T[30]w1 C[0d] T[5b]w1 T[e2, 9c, 85]w2 T[30]w1",
1320            ),
1321            (
1322                b"\xe0\x41\x1b\x41\xc3\xa9",
1323                "C[e0] T[41]w1 E[1b, 41] T[c3, a9]w1",
1324            ),
1325            (b"\xcf\xc8\x9c", "C[cf] T[c8, 9c]w1"),
1326            (
1327                b"\xe3\x61\x0a\xc4\x81\xc4\x81\x78",
1328                "C[e3] T[61]w1 C[0a] T[c4, 81]w1 T[c4, 81]w1 T[78]w1",
1329            ),
1330        ];
1331        for (seed, expected) in pinned {
1332            let rendered: Vec<String> = tokenize(seed, WidthMode::Grapheme, false)
1333                .map(|t| match t.kind {
1334                    TokenKind::Text => format!("T{:x?}w{}", t.bytes, t.width),
1335                    TokenKind::Escape => format!("E{:x?}", t.bytes),
1336                    TokenKind::Control => format!("C{:02x?}", t.bytes),
1337                })
1338                .collect();
1339            assert_eq!(rendered.join(" "), *expected, "input {seed:x?}");
1340            string_width(seed, WidthMode::Grapheme, false);
1341            string_width(seed, WidthMode::Wc, false);
1342        }
1343
1344        // A cheap xorshift beats no fuzzing at all; the seeds above are the
1345        // cases it found, kept so a failure names itself.
1346        let mut state = 0x2545_f491_4f6c_dd1du64;
1347        let mut buf = [0u8; 24];
1348        for _ in 0..200_000 {
1349            let len = {
1350                state ^= state << 13;
1351                state ^= state >> 7;
1352                state ^= state << 17;
1353                (state % 24) as usize
1354            };
1355            for b in buf.iter_mut().take(len) {
1356                state ^= state << 13;
1357                state ^= state >> 7;
1358                state ^= state << 17;
1359                // Weighted towards the bytes that break things: lead bytes,
1360                // continuations, introducers, controls.
1361                *b =
1362                    match state % 4 {
1363                        0 => (state >> 8) as u8,
1364                        1 => [0x1b, 0x9b, 0x9d, 0x90, 0x98, 0x9e, 0x9f, 0x07]
1365                            [(state >> 8) as usize % 8],
1366                        2 => [0xc2, 0xe0, 0xe2, 0xf0, 0xf4, 0xff, 0x9c, 0x80]
1367                            [(state >> 8) as usize % 8],
1368                        _ => b"abc \n\r\\;0"[(state >> 8) as usize % 9],
1369                    };
1370            }
1371            let input = &buf[..len];
1372            for t in tokenize(input, WidthMode::Grapheme, false) {
1373                assert!(!t.bytes.is_empty());
1374                match t.kind {
1375                    TokenKind::Text => assert_eq!(t.control, 0),
1376                    TokenKind::Escape => {
1377                        assert_eq!(t.width, 0);
1378                        assert_eq!(t.control, 0);
1379                    }
1380                    TokenKind::Control => {
1381                        assert_eq!(t.width, 0);
1382                        assert_eq!(t.control, *t.bytes.last().unwrap());
1383                        if t.bytes.len() == 2 {
1384                            assert_eq!(t.bytes[0], 0xc2);
1385                            assert!((0x80..=0x9f).contains(&t.control));
1386                        } else {
1387                            assert_eq!(t.bytes.len(), 1);
1388                        }
1389                    }
1390                }
1391                if t.kind == TokenKind::Text {
1392                    assert!(
1393                        std::str::from_utf8(t.bytes).is_ok(),
1394                        "{input:x?} produced a split character {:x?}",
1395                        t.bytes
1396                    );
1397                }
1398            }
1399            string_width(input, WidthMode::Grapheme, false);
1400        }
1401    }
1402}
1403
1404#[cfg(test)]
1405mod scaling {
1406    use super::util::*;
1407    use super::*;
1408
1409    /// Tokenize `bytes` fully and return the work it cost: bytes visited by
1410    /// the run scan, and bytes handed to UTF-8 validation.
1411    ///
1412    /// Both are needed. They are two passes over the same run refreshed by two
1413    /// different conditions, so either can go quadratic while the other stays
1414    /// linear - a tokenizer that scans once per run but revalidates the
1415    /// remainder once per token takes 4x as long for each doubling of the
1416    /// input and still reports exactly one scan visit per byte.
1417    ///
1418    /// The tokens are checked rather than discarded: these inputs are the
1419    /// shapes most likely to desynchronise the run cache, so measuring what
1420    /// they cost while ignoring what they produced would miss an answer that
1421    /// is wrong but cheap.
1422    fn scan_cost(bytes: &[u8]) -> (usize, usize) {
1423        let mut t = tokenize(bytes, WidthMode::Wc, false);
1424        let toks: Vec<_> = (&mut t).collect();
1425        // Measuring what a wrong answer costs is no use, so check it. The
1426        // discarded `visible` is the check: it panics on a text token that is
1427        // not whole UTF-8.
1428        let _ = visible(&toks);
1429        assert_eq!(rebuild(&toks), bytes, "tokens did not reassemble the input");
1430        (t.scanned, t.validated)
1431    }
1432
1433    #[test]
1434    fn utf8_c1_boundaries_keep_scans_linear() {
1435        for unit in [
1436            &b"\xe7\x95\x8c\xc2\x9b31m\xe7\x95\x8c\xc2\x9bm"[..],
1437            b"\xe7\x95\x8c\xc2\x80\xe7\x95\x8c",
1438            b"\xe7\x95\x8c\xc2\x9d0;title\xc2\x9c",
1439        ] {
1440            for count in [1_000, 4_000, 16_000] {
1441                let input = unit.repeat(count);
1442                let (scanned, validated) = scan_cost(&input);
1443                assert!(scanned <= input.len());
1444                assert!(validated <= input.len());
1445            }
1446        }
1447    }
1448
1449    /// Tokenizing one long line must cost work proportional to its length.
1450    ///
1451    /// This is not a micro-optimisation guard, it is a complexity one. The
1452    /// tokenizer used to find the end of the current run of text - and
1453    /// validate it as UTF-8 - once **per grapheme**, so a line of `n`
1454    /// characters did O(n) work `n` times. Nothing in the output changed, so
1455    /// no correctness test could see it; what it produced was a renderer
1456    /// whose frame time depended on the longest line in view. A 32 KB line
1457    /// (one JSON blob, one base64 payload, one minified file in a tool
1458    /// result) took 852 ms to wrap, which is a hundred dropped frames for
1459    /// one entry scrolling past.
1460    ///
1461    /// The work is counted rather than timed. A timing test here is a
1462    /// benchmark wearing a test's clothes: on a machine running anything else
1463    /// the linear code reads slower than the quadratic threshold it is meant
1464    /// to catch, so it fails for reasons that have nothing to do with the
1465    /// code. Byte visits are exact, identical on every machine, and are the
1466    /// thing that actually went quadratic.
1467    #[test]
1468    fn tokenizing_one_long_line_is_linear_in_its_length() {
1469        for n in [1_000usize, 4_000, 16_000, 64_000] {
1470            let line: String = std::iter::repeat_n('x', n).collect();
1471            assert_eq!(
1472                scan_cost(line.as_bytes()),
1473                (0, 0),
1474                "printable ASCII needs neither a run scan nor UTF-8 validation"
1475            );
1476        }
1477    }
1478
1479    /// The same bound for text that is not ASCII.
1480    ///
1481    /// The line above is all `x`, so every token leaves through the ASCII
1482    /// shortcut and the grapheme path is never entered. A run of non-ASCII
1483    /// characters is the one that walks `run` a cluster at a time, and it is
1484    /// the one the run cache exists for: `latin1`, wide, astral, and a base
1485    /// plus a combining mark, which is the case where a cluster spans more
1486    /// than one character.
1487    #[test]
1488    fn tokenizing_a_long_non_ascii_line_is_linear_too() {
1489        for unit in ["\u{e9}", "\u{4e00}", "\u{1f600}", "e\u{301}"] {
1490            for n in [1_000usize, 4_000, 16_000, 64_000] {
1491                let line = unit.repeat(n);
1492                let len = line.len();
1493                assert_eq!(
1494                    scan_cost(line.as_bytes()),
1495                    (len, len),
1496                    "{unit:?} x{n}: the run is found once and validated once"
1497                );
1498            }
1499        }
1500    }
1501
1502    /// The same bound with the UTF-8 broken.
1503    ///
1504    /// This is the case the first version of the run cache missed. It cached
1505    /// one boundary for two questions - where the run ends, and how much of
1506    /// it is valid UTF-8 - so a single malformed byte invalidated the run and
1507    /// sent the *scan* back over the rest of the input, once per byte. The
1508    /// tokens were right and the timing test above passed, because its input
1509    /// is valid; only text that was one byte short of valid stayed quadratic.
1510    #[test]
1511    fn malformed_utf8_is_linear_too() {
1512        for n in [1_000usize, 4_000, 16_000, 64_000] {
1513            // `C2` opens a two-byte character that `41` cannot continue: a
1514            // malformed byte every two bytes, all the way through.
1515            let bytes: Vec<u8> = std::iter::repeat_n([0xc2u8, 0x41], n / 2)
1516                .flatten()
1517                .collect();
1518            let (scanned, validated) = scan_cost(&bytes);
1519            assert!(
1520                scanned <= 2 * n,
1521                "scanning {n} malformed bytes visited {scanned} of them"
1522            );
1523            assert!(
1524                validated <= 2 * n,
1525                "validating {n} malformed bytes submitted {validated} of them"
1526            );
1527        }
1528    }
1529}