vtty 0.1.0

Zero-allocation, panic-free DEC VT500 terminal parser with UTF-8 decoding and no_std support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Copyright © Fangdun Tsai <fundon@pindash.io>
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Parser end-to-end tests (ported from the old `vt` crate's parser suite).

use vtty::{Event, Parser, Perform};

#[derive(Default)]
#[allow(
    clippy::type_complexity,
    reason = "event vectors mirror the parser's callback signatures"
)]
struct Collecting {
    printed: String,
    executed: Vec<u8>,
    csi: Vec<(Vec<u16>, Vec<u8>, char, Vec<bool>)>,
    osc: Vec<Vec<Vec<u8>>>,
    esc: Vec<(Vec<u8>, u8)>,
}

impl Perform for Collecting {
    fn print(&mut self, c: char) {
        self.printed.push(c);
    }
    fn print_bytes(&mut self, s: &[u8]) {
        for &b in s {
            self.printed.push(b as char);
        }
    }
    fn execute(&mut self, b: u8) {
        self.executed.push(b);
    }
    #[allow(
        clippy::cast_possible_truncation,
        reason = "the -1 sentinel surfaces as u16::MAX"
    )]
    fn csi_dispatch(&mut self, params: &[i32], sep: u16, inters: &[u8], final_byte: u8) {
        // The `-1` empty-param sentinel surfaces as `u16::MAX` after the
        // `i32 → u16` cast (asserted by `csi_trailing_empty_param_is_sentinel`).
        let values: Vec<u16> = params.iter().map(|&p| p as u16).collect();
        // Bit `i` of `sep` marks param `i` as followed by a colon.
        let seps: Vec<bool> = (0..values.len())
            .map(|i| i < 16 && sep & (1 << i) != 0)
            .collect();
        self.csi
            .push((values, inters.to_vec(), final_byte as char, seps));
    }
    fn esc_dispatch(&mut self, inters: &[u8], b: u8) {
        self.esc.push((inters.to_vec(), b));
    }
    fn osc_dispatch(&mut self, params: &[&[u8]], _bell: bool) {
        self.osc.push(params.iter().map(|p| p.to_vec()).collect());
    }
}

fn parse(bytes: &[u8]) -> Collecting {
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, bytes);
    c
}

#[test]
fn print_ascii_and_utf8() {
    let c = parse("aλ🚀\n".as_bytes());
    assert_eq!(c.printed, "aλ🚀");
    assert_eq!(c.executed, vec![b'\n']);
}

#[cfg(feature = "simd")]
#[test]
fn simd_and_scalar_paths_agree() {
    // `Parser::new()` (scalar) and `Parser::with_simd()` must produce the
    // same event stream.
    let bytes = b"\x1b[31mred \xce\xbb \xf0\x9f\x9a\x80 \x1b[0mplain\n";

    let mut scalar = Parser::new();
    let mut a = Collecting::default();
    scalar.advance(&mut a, bytes);

    let mut simd = Parser::with_simd();
    let mut b = Collecting::default();
    simd.advance(&mut b, bytes);

    assert_eq!(a.printed, b.printed);
    assert_eq!(a.executed, b.executed);
    assert_eq!(a.csi, b.csi);
    assert_eq!(a.osc, b.osc);
    assert_eq!(a.esc, b.esc);
}

/// Sink that records `print_codepoints` batches and lone `print` calls
/// separately, so the bulk non-ASCII path can be asserted.
#[cfg(feature = "simd")]
#[derive(Default)]
struct CodepointBatches {
    batches: Vec<Vec<u32>>,
    executed: Vec<u8>,
}

#[cfg(feature = "simd")]
impl Perform for CodepointBatches {
    fn print_codepoints(&mut self, codepoints: &[u32]) {
        self.batches.push(codepoints.to_vec());
    }
    fn print(&mut self, c: char) {
        self.batches.push(vec![c as u32]);
    }
    fn execute(&mut self, b: u8) {
        self.executed.push(b);
    }
}

#[cfg(feature = "simd")]
#[test]
fn print_codepoints_batches_utf8_runs() {
    // 11 × 3 bytes = 33 bytes of CJK, no ESC: long enough to reach the SIMD
    // batched decode (probe window is 32 bytes). The flattened code-point
    // stream must reproduce the text under both paths; the SIMD path should
    // emit it as one batch.
    let text = "中中中中中中中中中中中";

    let mut p = Parser::with_simd();
    let mut sink = CodepointBatches::default();
    p.advance(&mut sink, text.as_bytes());

    let flat: Vec<u32> = sink.batches.iter().flatten().copied().collect();
    assert_eq!(flat, text.chars().map(|c| c as u32).collect::<Vec<_>>());
    #[cfg(feature = "simd")]
    assert!(
        sink.batches.iter().any(|b| b.len() > 1),
        "SIMD path should batch code points, got {:?}",
        sink.batches
    );
}

#[test]
fn csi_no_params_is_empty() {
    // A param-less CSI (`CSI H`) dispatches with an empty param list (so
    // decoders can distinguish it from an explicit `CSI 0 …`).
    let c = parse(b"\x1b[H");
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0, vec![]);
    assert_eq!(c.csi[0].2, 'H');
}

#[test]
fn csi_semicolon_params() {
    let c = parse(b"\x1b[1;4H");
    assert_eq!(c.csi[0].0, vec![1, 4]);
    assert_eq!(c.csi[0].3, vec![false, false]);
}

#[test]
fn csi_trailing_empty_param_is_sentinel() {
    // ConPTY emits SGR with a trailing `;` (e.g. `ESC[48;2;R;G;B;m`). The
    // trailing empty param must be distinguishable from an explicit `0` (which
    // SGR would treat as "reset"), so it is dispatched as the `-1` sentinel
    // (surfaced here as `u16::MAX` after `Params::from_i32`).
    let c = parse(b"\x1b[48;2;255;128;0;m");
    assert_eq!(c.csi[0].0, vec![48, 2, 255, 128, 0, u16::MAX]);
}

#[test]
fn csi_paramless_split_across_writes_is_empty() {
    // `CSI s` (SCOSC) split across two `advance` calls must still dispatch
    // with an empty param list — not `[0]`, which the decoder reads as
    // DECSLRM. (Regression for the non-ground final-byte fast path.)
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, b"\x1b[");
    p.advance(&mut c, b"s");
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0, vec![]);
    assert_eq!(c.csi[0].2, 's');
}

#[test]
fn csi_colon_params() {
    let c = parse(b"\x1b[4:2m");
    assert_eq!(c.csi[0].0, vec![4, 2]);
    // param 0 (the 4) was followed by a colon.
    assert_eq!(c.csi[0].3, vec![true, false]);
}

#[test]
fn csi_colon_rgb() {
    let c = parse(b"\x1b[38:2:255:0:0m");
    assert_eq!(c.csi[0].0, vec![38, 2, 255, 0, 0]);
    assert_eq!(c.csi[0].3, vec![true, true, true, true, false]);
}

#[test]
fn csi_private_marker_intermediate() {
    let c = parse(b"\x1b[?25h");
    assert_eq!(c.csi[0].2, 'h');
    assert_eq!(c.csi[0].1, vec![b'?']);
    assert_eq!(c.csi[0].0, vec![25]);
}

#[test]
fn esc_dispatch_with_intermediate() {
    let c = parse(b"\x1b(0");
    assert_eq!(c.esc[0].0, vec![b'(']);
    assert_eq!(c.esc[0].1, b'0');
}

#[test]
fn osc_bel_terminated() {
    let c = parse(b"\x1b]0;title\x07");
    assert_eq!(c.osc.len(), 1);
    assert_eq!(c.osc[0], vec![b"0".to_vec(), b"title".to_vec()]);
}

#[test]
fn osc_st_terminated() {
    let c = parse(b"\x1b]2;x\x1b\\");
    assert_eq!(c.osc.len(), 1);
    assert_eq!(c.osc[0], vec![b"2".to_vec(), b"x".to_vec()]);
}

#[test]
fn osc_sixteen_params_across_multiple_parsers() {
    // A full 16-param OSC (`0;1;…;15`). Each parser must dispatch all 16
    // independently — the `EMPTY` seed array is copied per call, so one
    // parser's slices never leak into another, and no trailing empty slice
    // is dispatched.
    let mut bytes = vec![0x1b, b']'];
    for i in 0..16 {
        if i > 0 {
            bytes.push(b';');
        }
        bytes.extend_from_slice(i.to_string().as_bytes());
    }
    bytes.push(0x07);

    for _ in 0..3 {
        let mut p = Parser::new();
        let mut c = Collecting::default();
        p.advance(&mut c, &bytes);
        assert_eq!(c.osc.len(), 1);
        assert_eq!(c.osc[0].len(), 16, "all 16 params must dispatch");
        for (i, param) in c.osc[0].iter().enumerate() {
            assert_eq!(param, i.to_string().as_bytes());
        }
    }
}

#[test]
fn osc_payload_over_limit_is_discarded() {
    // A payload at/under the cap dispatches; one byte over is dropped whole.
    let mut under = Parser::new();
    let mut c = Collecting::default();
    under.advance(&mut c, b"\x1b]52;c;");
    under.advance(&mut c, &vec![b'a'; 1024]);
    under.advance(&mut c, b"\x07");
    assert_eq!(c.osc.len(), 1, "small OSC must dispatch");

    let mut over = Parser::new();
    let mut c = Collecting::default();
    over.advance(&mut c, b"\x1b]52;c;");
    over.advance(&mut c, &vec![b'a'; 1_048_577]); // MAX_OSC_PAYLOAD + 1
    over.advance(&mut c, b"\x07");
    assert!(c.osc.is_empty(), "oversized OSC must be discarded");

    // A parser that saw an oversized OSC still parses the next one cleanly.
    over.advance(&mut c, b"\x1b]0;ok\x07");
    assert_eq!(c.osc.len(), 1);
    assert_eq!(c.osc[0], vec![b"0".to_vec(), b"ok".to_vec()]);
}

#[test]
fn osc_single_call_payload_over_limit_is_discarded() {
    // A single `advance` call (deferred path) must still cap the payload.
    let mut p = Parser::new();
    let mut c = Collecting::default();
    let mut buf = b"\x1b]0;".to_vec();
    buf.extend_from_slice(&vec![b'a'; 1_048_577]); // MAX_OSC_PAYLOAD + 1
    buf.push(0x07);
    p.advance(&mut c, &buf);
    assert!(
        c.osc.is_empty(),
        "single-call oversized OSC must be discarded"
    );

    // The parser still works afterward.
    p.advance(&mut c, b"\x1b]0;ok\x07");
    assert_eq!(c.osc.len(), 1);
    assert_eq!(c.osc[0], vec![b"0".to_vec(), b"ok".to_vec()]);
}

#[test]
fn osc_via_c1_consuming_trailing_partial_does_not_panic() {
    // Regression: a raw-C1 OSC introducer + payload can consume past a
    // trailing UTF-8 partial, so a later ground re-entry must not underflow
    // `valid_end - i`. The trailing bytes are raw C1 controls (executed), not
    // a partial code point.
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0x04, 0x9d, 0xff, 0xf1, 0x8a, 0x87]);
    assert_eq!(c.executed, vec![0x04, 0x8a, 0x87]);
    assert!(c.printed.is_empty());
}

#[test]
fn utf8_split_across_chunks() {
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0xce]); // first byte of λ
    assert!(c.printed.is_empty());
    p.advance(&mut c, &[0xbb]); // second byte
    assert_eq!(c.printed, "λ");
}

#[test]
fn utf8_partial_abort_emits_single_replacement() {
    // A 3-byte lead (U+4xxx) followed by a NON-continuation byte must emit
    // exactly one U+FFFD for the aborted partial and then decode the byte —
    // NOT re-emit the stale truncated code point as a spurious control char.
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0xe4]); // partial lead, 2 continuations expected
    assert!(c.printed.is_empty());
    p.advance(&mut c, b"X");
    assert_eq!(c.printed, "\u{FFFD}X");
    assert!(
        c.executed.is_empty(),
        "aborted partial must not emit a control: {:?}",
        c.executed
    );
}

#[test]
fn utf8_partial_abort_after_continuation_emits_single_replacement() {
    // A partial that consumes a continuation byte and THEN hits a
    // non-continuation byte must still emit exactly one U+FFFD — not the
    // stale truncated code point plus a replacement char.
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0xe4]); // partial lead, 2 continuations expected
    assert!(c.printed.is_empty());
    p.advance(&mut c, &[0x80, b'X']); // one continuation, then non-continuation
    assert_eq!(c.printed, "\u{FFFD}X");
    assert!(c.executed.is_empty());
}

#[test]
fn utf8_flush_emits_pending_partial_as_replacement() {
    // A trailing partial at end-of-stream becomes one U+FFFD (W3C), and a
    // second flush is a no-op.
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0xe4]); // 3-byte lead, 2 continuations expected
    assert!(c.printed.is_empty());
    p.flush(&mut c);
    assert_eq!(c.printed, "\u{FFFD}");
    p.flush(&mut c);
    assert_eq!(c.printed, "\u{FFFD}");
}

#[test]
fn parser_reset_clears_state_and_partial() {
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, &[0xe4]); // pending partial
    p.reset();
    p.flush(&mut c);
    assert!(c.printed.is_empty(), "reset must clear the pending partial");
}

#[test]
fn paramless_csi_after_aborted_csi_dispatches_empty() {
    // `CSI 1` (digit, no final) followed by `ESC [ H` must reset the partial
    // parameter, so the param-less `CSI H` dispatches `[]` (not `[0]` from a
    // stale `param_empty == false`).
    let mut p = Parser::new();
    let mut c = Collecting::default();
    p.advance(&mut c, b"\x1b[1");
    p.advance(&mut c, b"\x1b[H");
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0, Vec::<u16>::new());
    assert_eq!(c.csi[0].2, 'H');
}

#[test]
fn standalone_c1_control_executes() {
    // 0x9b (CSI) standalone byte → enters CSI entry (8-bit form); no final
    // byte arrives, so nothing is dispatched or executed.
    let c = parse(&[0x9b]);
    assert!(c.executed.is_empty());
    assert!(c.csi.is_empty());
}

#[test]
fn event_collector_api() {
    let mut p = Parser::new();
    let events = p.parse_events(b"\x1b[31mX");
    assert_eq!(
        events,
        vec![
            Event::CsiDispatch {
                params: vec![31].into_iter().collect(),
                intermediates: Vec::new().into_iter().collect(),
                final_byte: b'm',
            },
            Event::Print('X'),
        ]
    );
}

#[test]
fn dcs_hook_put_unhook() {
    let mut p = Parser::new();
    let events = p.parse_events(b"\x1bP1;2$rpayload\x1b\\");
    assert_eq!(
        events[0],
        Event::DcsHook {
            params: vec![1, 2].into_iter().collect(),
            intermediates: vec![b'$'].into_iter().collect(),
            final_byte: b'r',
        }
    );
    let puts: Vec<u8> = events[1..8]
        .iter()
        .map(|e| match e {
            Event::DcsPut(b) => *b,
            other => panic!("expected DcsPut, got {other:?}"),
        })
        .collect();
    assert_eq!(puts, b"payload");
    assert_eq!(events[8], Event::DcsUnhook);
    // The `\` of the `ESC \` ST terminator dispatches as an escape final,
    // matching vte (the differential baseline).
    assert_eq!(
        events[9],
        Event::EscDispatch {
            intermediates: Vec::new().into_iter().collect(),
            byte: b'\\',
        }
    );
}

#[test]
fn ris_esc_dispatch_empty_intermediates() {
    let c = parse(b"\x1bc");
    assert_eq!(c.esc, vec![(Vec::new(), b'c')]);
}

#[test]
fn dcs_no_params_is_empty() {
    let mut p = Parser::new();
    let events = p.parse_events(b"\x1bPqpayload\x1b\\");
    assert_eq!(
        events[0],
        Event::DcsHook {
            params: Vec::new().into_iter().collect(),
            intermediates: Vec::new().into_iter().collect(),
            final_byte: b'q',
        }
    );
}

#[test]
fn multiple_csi_params() {
    let c = parse(b"\x1b[1;2;3m");
    assert_eq!(c.csi[0].0, vec![1, 2, 3]);
    assert_eq!(c.csi[0].2, 'm');
}

#[test]
fn csi_params_capped_at_32() {
    // A malicious stream with thousands of `;` must not grow the param
    // vector unboundedly — only the first 32 are kept (vte/rio-vt cap).
    let mut seq = vec![0x1b, b'['];
    for _ in 0..1000 {
        seq.push(b'7');
        seq.push(b';');
    }
    seq.push(b'm');
    let c = parse(&seq);
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0.len(), 32);
    assert_eq!(c.csi[0].2, 'm');
}

// ── 8-bit C1 handling (DEC "anywhere" transitions) ──────────────────────

#[test]
fn c1_csi_introducer_starts_sequence() {
    // 0x9b is the 8-bit form of CSI.
    let c = parse(b"\x9b1;2H");
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0, vec![1, 2]);
    assert_eq!(c.csi[0].2, 'H');
}

#[test]
fn c1_osc_introducer_and_st_terminator() {
    // 0x9d = OSC, 0x9c = ST (8-bit).
    let c = parse(b"\x9d0;title\x9c");
    assert_eq!(c.osc, vec![vec![b"0".to_vec(), b"title".to_vec()]]);
}

#[test]
fn c1_aborts_in_progress_csi() {
    // A raw CSI (0x9b) inside a 7-bit CSI aborts it and starts fresh.
    let c = parse(b"\x1b[1;\x9b2;3m");
    assert_eq!(c.csi.len(), 1);
    assert_eq!(c.csi[0].0, vec![2, 3]);
    assert_eq!(c.csi[0].2, 'm');
}

#[test]
fn c1_st_is_noop_terminator() {
    // 0x9c (ST) inside a CSI is a no-op and returns to ground; a following
    // printable char is printed.
    let c = parse(b"\x1b[1\x9cX");
    assert!(c.csi.is_empty());
    assert_eq!(c.printed, "X");
}

#[test]
fn c1_other_controls_execute_and_cancel() {
    // 0x84 (IND, a non-introducer C1) inside CSI executes and cancels it.
    let c = parse(b"\x1b[1\x84");
    assert!(c.csi.is_empty());
    assert_eq!(c.executed, vec![0x84]);
}