uncurses 0.0.9

A Rust terminal rendering library
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
//! Lazy parser for CSI and DCS parameter bodies.
//!
//! ## Category
//!
//! [`ControlSequence`] splits a sequence into the regions ECMA-48 names:
//! parameter bytes, intermediate bytes, and the final byte that identifies
//! the control function. [`Params`] and [`Group`] then walk the parameter
//! region, handling semicolon-separated parameters and colon-separated
//! subparameters without allocating.
//!
//! ## Parameter grammar
//!
//! A body such as `38:2::255:100:50;1` is viewed as two top-level groups. Empty
//! slots decode to `None`; numeric slots decode to `Some(value)`.
//!
//! ```text
//! 38:2::255:100:50  ;  1
//! ─────────┬────────   ┬
//!      group 0       group 1
//! ```
//!
//! ## Mode interaction
//!
//! Parameter defaults are sequence-specific. Callers apply defaults with
//! [`Params::get_or`] after they know which CSI/DCS final byte and mode context
//! they are handling.

use std::fmt;

/// Borrowed view of a CSI / DCS parameter body.
#[derive(Copy, Clone)]
pub struct Params<'a> {
    raw: &'a [u8],
}

impl<'a> Params<'a> {
    /// Empty parameter list.
    pub const EMPTY: Self = Self { raw: &[] };

    /// Wrap the raw parameter bytes (between the introducer's last
    /// byte and the final byte, exclusive on both ends).
    #[inline]
    pub fn from_raw(raw: &'a [u8]) -> Self {
        Self { raw }
    }

    /// The raw parameter bytes, exactly as they appeared on the wire.
    #[inline]
    pub fn raw(&self) -> &'a [u8] {
        self.raw
    }

    /// `true` when the parameter body is empty (no groups at all).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// Number of `;`-separated groups. An empty body has zero groups;
    /// a trailing `;` produces an extra empty group.
    pub fn len(&self) -> usize {
        if self.raw.is_empty() {
            0
        } else {
            self.raw.iter().filter(|&&b| b == b';').count() + 1
        }
    }

    /// Sequential iterator over the `;`-separated groups.
    pub fn iter(&self) -> ParamIter<'a> {
        ParamIter {
            inner: if self.raw.is_empty() {
                None
            } else {
                Some(self.raw.split(is_semicolon))
            },
        }
    }

    /// The n-th group, or `None` when `idx >= len()`.
    pub fn group(&self, idx: usize) -> Option<Group<'a>> {
        self.iter().nth(idx)
    }

    /// First sub-parameter of the n-th group. `None` for absent groups
    /// and explicitly empty slots.
    pub fn get(&self, idx: usize) -> Option<u32> {
        self.group(idx).and_then(|g| g.first())
    }

    /// First sub-parameter of the n-th group, or `default` when the
    /// group is absent or the slot is explicitly empty.
    pub fn get_or(&self, idx: usize, default: u32) -> u32 {
        self.get(idx).unwrap_or(default)
    }

    /// A [`Params`] view starting at the group at index `start`. Used
    /// when a caller needs to expose "the rest of the parameter list"
    /// (e.g. `Event::WindowOp`'s args).
    pub fn slice_from(&self, start: usize) -> Params<'a> {
        let mut cur = self.raw;
        let mut skipped = 0;
        while skipped < start {
            match cur.iter().position(|&b| b == b';') {
                Some(p) => {
                    cur = &cur[p + 1..];
                    skipped += 1;
                }
                None => return Params::EMPTY,
            }
        }
        Params { raw: cur }
    }
}

impl<'a> fmt::Debug for Params<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.iter().map(|g| g.first()))
            .finish()
    }
}

impl<'a> IntoIterator for Params<'a> {
    type Item = Group<'a>;
    type IntoIter = ParamIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// One `;`-separated group within a [`Params`] body. Wraps the raw
/// bytes for that group (no separator); decodes its colon-separated
/// sub-parameters on demand.
#[derive(Copy, Clone)]
pub struct Group<'a> {
    raw: &'a [u8],
}

impl<'a> Group<'a> {
    /// Group with no sub-parameters.
    pub const EMPTY: Self = Self { raw: &[] };

    /// Wrap raw bytes as a single group.
    #[inline]
    pub fn from_raw(raw: &'a [u8]) -> Self {
        Self { raw }
    }

    /// Raw bytes between the surrounding `;` separators.
    #[inline]
    pub fn raw(&self) -> &'a [u8] {
        self.raw
    }

    /// `true` when the group's raw body is empty (i.e. between two
    /// `;` separators with nothing between them).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// Number of `:`-separated sub-parameters. An empty group has
    /// exactly one slot (which decodes as `None`).
    pub fn len(&self) -> usize {
        if self.raw.is_empty() {
            1
        } else {
            self.raw.iter().filter(|&&b| b == b':').count() + 1
        }
    }

    /// Sequential iterator over sub-parameters.
    pub fn iter(&self) -> SubIter<'a> {
        SubIter {
            inner: self.raw.split(is_colon),
        }
    }

    /// First sub-parameter of the group.
    pub fn first(&self) -> Option<u32> {
        self.iter().next().flatten()
    }

    /// The n-th sub-parameter, `None` when out of range or explicitly
    /// empty.
    pub fn nth(&self, i: usize) -> Option<u32> {
        self.iter().nth(i).flatten()
    }
}

impl<'a> fmt::Debug for Group<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<'a> IntoIterator for Group<'a> {
    type Item = Option<u32>;
    type IntoIter = SubIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over the `;`-separated groups of a [`Params`].
pub struct ParamIter<'a> {
    // `None` when the body was empty (yielding zero items, matching
    // the historical "empty body = zero params" convention).
    #[allow(clippy::type_complexity)]
    inner: Option<std::slice::Split<'a, u8, fn(&u8) -> bool>>,
}

impl<'a> Iterator for ParamIter<'a> {
    type Item = Group<'a>;
    fn next(&mut self) -> Option<Group<'a>> {
        self.inner.as_mut()?.next().map(|raw| Group { raw })
    }
}

/// Iterator over the `:`-separated sub-parameters of a [`Group`].
pub struct SubIter<'a> {
    inner: std::slice::Split<'a, u8, fn(&u8) -> bool>,
}

impl<'a> Iterator for SubIter<'a> {
    type Item = Option<u32>;
    fn next(&mut self) -> Option<Option<u32>> {
        self.inner.next().map(parse_u32)
    }
}

fn is_semicolon(b: &u8) -> bool {
    *b == b';'
}

fn is_colon(b: &u8) -> bool {
    *b == b':'
}

/// A control sequence as ECMA-48 5th edition section 5.4 defines it:
/// parameter bytes, intermediate bytes, and a final byte identifying the
/// control function.
///
/// The introducer is not part of this view. Section 5.4 counts it as part of
/// the sequence, but leaving it out is what lets one type serve every place
/// the shape appears: a CSI body, the command section a DCS carries before
/// its payload, and the setting a DECRPSS reply spells out with no
/// introducer at all.
///
/// ```text
/// ? 2 0 4 8  h          $ r          2  SP q
/// ┬ ───┬──── ┬          ┬ ┬          ┬  ─┬ ┬
/// │  params  final      │ final      │   │ final
/// private               intermediate │   intermediate
///                                  params
/// ```
#[derive(Copy, Clone, Debug)]
pub struct ControlSequence<'a> {
    private: Option<u8>,
    params: Params<'a>,
    intermediate: Option<u8>,
    final_byte: u8,
}

impl<'a> ControlSequence<'a> {
    /// Parse a leading control sequence and return it with the bytes that
    /// follow its final byte.
    ///
    /// The tail is empty for a CSI body, which ends at the final byte, and
    /// carries the payload for a DCS. A caller that expects nothing to follow
    /// checks that for itself.
    ///
    /// # Returns
    ///
    /// `None` when `body` holds no final byte, when a byte falls outside the
    /// region it appears in, or when more than one intermediate is present.
    /// Every control function in use carries at most one, so a second means
    /// this is not a sequence worth recognizing.
    pub fn parse(body: &'a [u8]) -> Option<(Self, &'a [u8])> {
        let (private, rest) = match body.first() {
            Some(&b) if (0x3c..=0x3f).contains(&b) => (Some(b), &body[1..]),
            _ => (None, body),
        };

        // One scan to the end of the parameter bytes. A single `position`
        // over a byte range compiles to a tighter search than stepping an
        // index by hand, which shows up on the long parameter lists SGR
        // produces.
        let mid = rest
            .iter()
            .position(|&b| !(0x30..=0x3b).contains(&b))
            .unwrap_or(rest.len());
        let params = Params::from_raw(&rest[..mid]);

        // What follows is at most one intermediate, then the final byte. A
        // second intermediate leaves a byte that is not final, so the check
        // below rejects it.
        let (intermediate, final_pos) = match rest.get(mid) {
            Some(&b) if (0x20..=0x2f).contains(&b) => (Some(b), mid + 1),
            _ => (None, mid),
        };

        let final_byte = *rest.get(final_pos)?;
        if !(0x40..=0x7e).contains(&final_byte) {
            return None;
        }

        Some((
            Self {
                private,
                params,
                intermediate,
                final_byte,
            },
            &rest[final_pos + 1..],
        ))
    }

    /// The first parameter byte when it falls in the private-use range 03/12
    /// to 03/15 (`<`, `=`, `>`, `?`), which may only appear there.
    pub fn private(&self) -> Option<u8> {
        self.private
    }

    /// The parameter bytes, as a lazy walker over the `;`-separated list.
    pub fn params(&self) -> Params<'a> {
        self.params
    }

    /// The intermediate byte, from the range 02/00 to 02/15.
    pub fn intermediate(&self) -> Option<u8> {
        self.intermediate
    }

    /// The final byte, from the range 04/00 to 07/14. It identifies the
    /// control function.
    pub fn final_byte(&self) -> u8 {
        self.final_byte
    }
}

fn parse_u32(bytes: &[u8]) -> Option<u32> {
    if bytes.is_empty() {
        return None;
    }
    let mut acc: u32 = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add((b - b'0') as u32)?;
    }
    Some(acc)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn flat(p: Params<'_>) -> Vec<Option<u32>> {
        p.iter().map(|g| g.first()).collect()
    }

    fn nested(p: Params<'_>) -> Vec<Vec<Option<u32>>> {
        p.iter().map(|g| g.iter().collect()).collect()
    }

    #[test]
    fn flat_distinguishes_absent_from_explicit_zero() {
        assert_eq!(flat(Params::from_raw(b"")), Vec::<Option<u32>>::new());
        assert_eq!(flat(Params::from_raw(b";")), vec![None, None]);
        assert_eq!(
            flat(Params::from_raw(b"0;;3")),
            vec![Some(0), None, Some(3)]
        );
        assert_eq!(flat(Params::from_raw(b";5")), vec![None, Some(5)]);
        assert_eq!(
            flat(Params::from_raw(b"27;5;128512")),
            vec![Some(27), Some(5), Some(128512)]
        );
    }

    #[test]
    fn flat_takes_first_colon_subparam() {
        assert_eq!(flat(Params::from_raw(b"4:3;1")), vec![Some(4), Some(1)]);
    }

    #[test]
    fn nested_preserves_colon_groups() {
        assert_eq!(
            nested(Params::from_raw(b"")),
            Vec::<Vec<Option<u32>>>::new()
        );
        assert_eq!(
            nested(Params::from_raw(b"38:2::255:100:50")),
            vec![vec![
                Some(38),
                Some(2),
                None,
                Some(255),
                Some(100),
                Some(50),
            ]]
        );
        assert_eq!(
            nested(Params::from_raw(b"1;31;48:5:200")),
            vec![
                vec![Some(1)],
                vec![Some(31)],
                vec![Some(48), Some(5), Some(200)],
            ]
        );
    }

    #[test]
    fn nested_empty_slots() {
        assert_eq!(
            nested(Params::from_raw(b";1;")),
            vec![vec![None], vec![Some(1)], vec![None]]
        );
        assert_eq!(nested(Params::from_raw(b"4:")), vec![vec![Some(4), None]]);
    }

    #[test]
    fn get_or_returns_default_only_for_absent() {
        // Mirrors `;`-separated layout: [Some(5), None, Some(0), Some(7)]
        let p = Params::from_raw(b"5;;0;7");
        assert_eq!(p.get_or(0, 1), 5);
        assert_eq!(p.get_or(1, 1), 1);
        assert_eq!(p.get_or(2, 1), 0);
        assert_eq!(p.get_or(3, 1), 7);
        assert_eq!(p.get_or(4, 1), 1);
        assert_eq!(Params::EMPTY.get_or(0, 42), 42);
    }

    #[test]
    fn len_counts_groups() {
        assert_eq!(Params::from_raw(b"").len(), 0);
        assert_eq!(Params::from_raw(b"1").len(), 1);
        assert_eq!(Params::from_raw(b";").len(), 2);
        assert_eq!(Params::from_raw(b"1;2;3").len(), 3);
        assert_eq!(Params::from_raw(b"1;").len(), 2);
    }

    #[test]
    fn slice_from_skips_groups() {
        let p = Params::from_raw(b"1;2;3;4");
        assert_eq!(
            flat(p.slice_from(0)),
            vec![Some(1), Some(2), Some(3), Some(4)]
        );
        assert_eq!(flat(p.slice_from(2)), vec![Some(3), Some(4)]);
        assert_eq!(flat(p.slice_from(4)), Vec::<Option<u32>>::new());
        assert_eq!(flat(p.slice_from(99)), Vec::<Option<u32>>::new());
    }

    #[test]
    fn debug_format_matches_flat_list() {
        let p = Params::from_raw(b"1;2");
        assert_eq!(format!("{:?}", p), "[Some(1), Some(2)]");
    }

    #[test]
    fn control_sequence_splits_each_region() {
        // Private prefix, parameters, final byte: DECSET of mode 2048.
        let (s, rest) = ControlSequence::parse(b"?2048h").unwrap();
        assert_eq!(s.private(), Some(b'?'));
        assert_eq!(s.params().get_or(0, 0), 2048);
        assert_eq!(s.intermediate(), None);
        assert_eq!(s.final_byte(), b'h');
        assert!(rest.is_empty());

        // An intermediate, and a parameter that may be omitted: DECSCUSR.
        let (s, _) = ControlSequence::parse(b"2 q").unwrap();
        assert_eq!(s.params().get_or(0, 0), 2);
        assert_eq!(s.intermediate(), Some(b' '));
        assert_eq!(s.final_byte(), b'q');

        let (s, _) = ControlSequence::parse(b" q").unwrap();
        assert_eq!(s.params().get_or(0, 0), 0, "an omitted parameter is 0");
        assert_eq!(s.intermediate(), Some(b' '));

        // Subparameters stay available through `Params`.
        let (s, _) = ControlSequence::parse(b"38:2::255:100:50m").unwrap();
        assert_eq!(s.final_byte(), b'm');
        assert_eq!(s.params().group(0).unwrap().nth(3), Some(255));
    }

    #[test]
    fn control_sequence_returns_what_follows_the_final_byte() {
        // A DCS carries its payload after the command section, which is why
        // the tail is handed back rather than rejected.
        let (s, rest) = ControlSequence::parse(b"1$r2 q").unwrap();
        assert_eq!(s.params().get_or(0, 0), 1);
        assert_eq!(s.intermediate(), Some(b'$'));
        assert_eq!(s.final_byte(), b'r');
        assert_eq!(rest, b"2 q");
    }

    #[test]
    fn control_sequence_rejects_what_it_cannot_name() {
        // No final byte at all.
        assert!(ControlSequence::parse(b"").is_none());
        assert!(ControlSequence::parse(b"12").is_none());
        assert!(ControlSequence::parse(b"2 ").is_none());

        // Two intermediates. Every control function in use carries at most
        // one, so this is not a sequence worth recognizing. Taking the last
        // would answer a question that was never asked.
        assert!(ControlSequence::parse(b"1!!p").is_none());
    }
}