Skip to main content

uncurses/ansi/
params.rs

1//! Lazy parser for CSI, DCS, and APC parameter bodies.
2//!
3//! ## Category
4//!
5//! [`ControlSequence`] splits a sequence into the regions ECMA-48 names:
6//! parameter bytes, intermediate bytes, and the final byte that identifies
7//! the control function. [`Params`] and [`Group`] then walk the parameter
8//! region, handling semicolon-separated parameters and colon-separated
9//! subparameters without allocating.
10//!
11//! ## Parameter grammar
12//!
13//! A body such as `38:2::255:100:50;1` is viewed as two top-level groups. Empty
14//! slots decode to `None`; numeric slots decode to `Some(value)`.
15//!
16//! ```text
17//! 38:2::255:100:50  ;  1
18//! ─────────┬────────   ┬
19//!      group 0       group 1
20//! ```
21//!
22//! ## Mode interaction
23//!
24//! Parameter defaults are sequence-specific. Callers apply defaults with
25//! [`Params::get_or`] after they know which final byte and mode context
26//! they are handling.
27
28use std::fmt;
29
30/// Borrowed view of a CSI, DCS, or APC parameter body.
31#[derive(Copy, Clone)]
32pub struct Params<'a> {
33    raw: &'a [u8],
34}
35
36impl<'a> Params<'a> {
37    /// Empty parameter list.
38    pub const EMPTY: Self = Self { raw: &[] };
39
40    /// Wrap the raw parameter bytes (between the introducer's last
41    /// byte and the final byte, exclusive on both ends).
42    #[inline]
43    pub fn from_raw(raw: &'a [u8]) -> Self {
44        Self { raw }
45    }
46
47    /// The raw parameter bytes, exactly as they appeared on the wire.
48    #[inline]
49    pub fn raw(&self) -> &'a [u8] {
50        self.raw
51    }
52
53    /// `true` when the parameter body is empty (no groups at all).
54    #[inline]
55    pub fn is_empty(&self) -> bool {
56        self.raw.is_empty()
57    }
58
59    /// Number of `;`-separated groups. An empty body has zero groups;
60    /// a trailing `;` produces an extra empty group.
61    pub fn len(&self) -> usize {
62        if self.raw.is_empty() {
63            0
64        } else {
65            self.raw.iter().filter(|&&b| b == b';').count() + 1
66        }
67    }
68
69    /// Sequential iterator over the `;`-separated groups.
70    pub fn iter(&self) -> ParamIter<'a> {
71        ParamIter {
72            inner: if self.raw.is_empty() {
73                None
74            } else {
75                Some(self.raw.split(is_semicolon))
76            },
77        }
78    }
79
80    /// The n-th group, or `None` when `idx >= len()`.
81    pub fn group(&self, idx: usize) -> Option<Group<'a>> {
82        self.iter().nth(idx)
83    }
84
85    /// First sub-parameter of the n-th group. `None` for absent groups
86    /// and explicitly empty slots.
87    pub fn get(&self, idx: usize) -> Option<u32> {
88        self.group(idx).and_then(|g| g.first())
89    }
90
91    /// First sub-parameter of the n-th group, or `default` when the
92    /// group is absent or the slot is explicitly empty.
93    pub fn get_or(&self, idx: usize, default: u32) -> u32 {
94        self.get(idx).unwrap_or(default)
95    }
96
97    /// A [`Params`] view starting at the group at index `start`. Used
98    /// when a caller needs to expose "the rest of the parameter list"
99    /// (e.g. `Event::WindowOp`'s args).
100    pub fn slice_from(&self, start: usize) -> Params<'a> {
101        let mut cur = self.raw;
102        let mut skipped = 0;
103        while skipped < start {
104            match cur.iter().position(|&b| b == b';') {
105                Some(p) => {
106                    cur = &cur[p + 1..];
107                    skipped += 1;
108                }
109                None => return Params::EMPTY,
110            }
111        }
112        Params { raw: cur }
113    }
114}
115
116impl<'a> fmt::Debug for Params<'a> {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_list()
119            .entries(self.iter().map(|g| g.first()))
120            .finish()
121    }
122}
123
124impl<'a> IntoIterator for Params<'a> {
125    type Item = Group<'a>;
126    type IntoIter = ParamIter<'a>;
127    fn into_iter(self) -> Self::IntoIter {
128        self.iter()
129    }
130}
131
132/// One `;`-separated group within a [`Params`] body. Wraps the raw
133/// bytes for that group (no separator); decodes its colon-separated
134/// sub-parameters on demand.
135#[derive(Copy, Clone)]
136pub struct Group<'a> {
137    raw: &'a [u8],
138}
139
140impl<'a> Group<'a> {
141    /// Group with no sub-parameters.
142    pub const EMPTY: Self = Self { raw: &[] };
143
144    /// Wrap raw bytes as a single group.
145    #[inline]
146    pub fn from_raw(raw: &'a [u8]) -> Self {
147        Self { raw }
148    }
149
150    /// Raw bytes between the surrounding `;` separators.
151    #[inline]
152    pub fn raw(&self) -> &'a [u8] {
153        self.raw
154    }
155
156    /// `true` when the group's raw body is empty (i.e. between two
157    /// `;` separators with nothing between them).
158    #[inline]
159    pub fn is_empty(&self) -> bool {
160        self.raw.is_empty()
161    }
162
163    /// Number of `:`-separated sub-parameters. An empty group has
164    /// exactly one slot (which decodes as `None`).
165    pub fn len(&self) -> usize {
166        if self.raw.is_empty() {
167            1
168        } else {
169            self.raw.iter().filter(|&&b| b == b':').count() + 1
170        }
171    }
172
173    /// Sequential iterator over sub-parameters.
174    pub fn iter(&self) -> SubIter<'a> {
175        SubIter {
176            inner: self.raw.split(is_colon),
177        }
178    }
179
180    /// First sub-parameter of the group.
181    pub fn first(&self) -> Option<u32> {
182        self.iter().next().flatten()
183    }
184
185    /// The n-th sub-parameter, `None` when out of range or explicitly
186    /// empty.
187    pub fn nth(&self, i: usize) -> Option<u32> {
188        self.iter().nth(i).flatten()
189    }
190}
191
192impl<'a> fmt::Debug for Group<'a> {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.debug_list().entries(self.iter()).finish()
195    }
196}
197
198impl<'a> IntoIterator for Group<'a> {
199    type Item = Option<u32>;
200    type IntoIter = SubIter<'a>;
201    fn into_iter(self) -> Self::IntoIter {
202        self.iter()
203    }
204}
205
206/// Iterator over the `;`-separated groups of a [`Params`].
207pub struct ParamIter<'a> {
208    // `None` when the body was empty (yielding zero items, matching
209    // the historical "empty body = zero params" convention).
210    #[allow(clippy::type_complexity)]
211    inner: Option<std::slice::Split<'a, u8, fn(&u8) -> bool>>,
212}
213
214impl<'a> Iterator for ParamIter<'a> {
215    type Item = Group<'a>;
216    fn next(&mut self) -> Option<Group<'a>> {
217        self.inner.as_mut()?.next().map(|raw| Group { raw })
218    }
219}
220
221/// Iterator over the `:`-separated sub-parameters of a [`Group`].
222#[derive(Clone)]
223pub struct SubIter<'a> {
224    inner: std::slice::Split<'a, u8, fn(&u8) -> bool>,
225}
226
227impl<'a> Iterator for SubIter<'a> {
228    type Item = Option<u32>;
229    fn next(&mut self) -> Option<Option<u32>> {
230        self.inner.next().map(parse_u32)
231    }
232}
233
234fn is_semicolon(b: &u8) -> bool {
235    *b == b';'
236}
237
238fn is_colon(b: &u8) -> bool {
239    *b == b':'
240}
241
242/// A control sequence body that follows ECMA-48 §5.4.1.
243///
244/// The introducer is not part of this view. Section 5.4 counts it as part of
245/// the sequence, but leaving it out is what lets one type serve every place
246/// the shape appears: a CSI body, a DCS or APC header before its payload, and
247/// the setting a DECRPSS reply spells out with no introducer at all.
248///
249/// ```text
250/// ? 2 0 4 8  h          $ r          2  SP q
251/// ┬ ───┬──── ┬          ┬ ┬          ┬  ─┬ ┬
252/// │  params  final      │ final      │   │ final
253/// private               intermediate │   intermediate
254///                                  params
255/// ```
256#[derive(Copy, Clone, Debug)]
257pub struct ControlSequence<'a> {
258    private: Option<u8>,
259    params: Params<'a>,
260    intermediate: Option<u8>,
261    final_byte: u8,
262}
263
264impl<'a> ControlSequence<'a> {
265    /// Parse a leading control sequence and return it with the bytes that
266    /// follow its final byte.
267    ///
268    /// The tail is empty for a CSI body, which ends at the final byte, and
269    /// carries the payload for a DCS or APC. A caller that expects nothing to
270    /// follow checks that for itself.
271    ///
272    /// # Returns
273    ///
274    /// `None` when `body` holds no final byte, when a byte falls outside the
275    /// region it appears in, or when more than one intermediate is present.
276    /// Every control function in use carries at most one, so a second means
277    /// this is not a sequence worth recognizing.
278    pub fn parse(body: &'a [u8]) -> Option<(Self, &'a [u8])> {
279        let (private, rest) = match body.first() {
280            Some(&b) if (0x3c..=0x3f).contains(&b) => (Some(b), &body[1..]),
281            _ => (None, body),
282        };
283
284        // One scan to the end of the parameter bytes. A single `position`
285        // over a byte range compiles to a tighter search than stepping an
286        // index by hand, which shows up on the long parameter lists SGR
287        // produces.
288        let mid = rest
289            .iter()
290            .position(|&b| !(0x30..=0x3b).contains(&b))
291            .unwrap_or(rest.len());
292        let params = Params::from_raw(&rest[..mid]);
293
294        // What follows is at most one intermediate, then the final byte. A
295        // second intermediate leaves a byte that is not final, so the check
296        // below rejects it.
297        let (intermediate, final_pos) = match rest.get(mid) {
298            Some(&b) if (0x20..=0x2f).contains(&b) => (Some(b), mid + 1),
299            _ => (None, mid),
300        };
301
302        let final_byte = *rest.get(final_pos)?;
303        if !(0x40..=0x7e).contains(&final_byte) {
304            return None;
305        }
306
307        Some((
308            Self {
309                private,
310                params,
311                intermediate,
312                final_byte,
313            },
314            &rest[final_pos + 1..],
315        ))
316    }
317
318    /// The first parameter byte when it falls in the private-use range 03/12
319    /// to 03/15 (`<`, `=`, `>`, `?`), which may only appear there.
320    pub fn private(&self) -> Option<u8> {
321        self.private
322    }
323
324    /// The parameter bytes, as a lazy walker over the `;`-separated list.
325    pub fn params(&self) -> Params<'a> {
326        self.params
327    }
328
329    /// The intermediate byte, from the range 02/00 to 02/15.
330    pub fn intermediate(&self) -> Option<u8> {
331        self.intermediate
332    }
333
334    /// The final byte, from the range 04/00 to 07/14. It identifies the
335    /// control function.
336    pub fn final_byte(&self) -> u8 {
337        self.final_byte
338    }
339}
340
341fn parse_u32(bytes: &[u8]) -> Option<u32> {
342    if bytes.is_empty() {
343        return None;
344    }
345    let mut acc: u32 = 0;
346    for &b in bytes {
347        if !b.is_ascii_digit() {
348            return None;
349        }
350        acc = acc.checked_mul(10)?.checked_add((b - b'0') as u32)?;
351    }
352    Some(acc)
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358
359    fn flat(p: Params<'_>) -> Vec<Option<u32>> {
360        p.iter().map(|g| g.first()).collect()
361    }
362
363    fn nested(p: Params<'_>) -> Vec<Vec<Option<u32>>> {
364        p.iter().map(|g| g.iter().collect()).collect()
365    }
366
367    #[test]
368    fn flat_distinguishes_absent_from_explicit_zero() {
369        assert_eq!(flat(Params::from_raw(b"")), Vec::<Option<u32>>::new());
370        assert_eq!(flat(Params::from_raw(b";")), vec![None, None]);
371        assert_eq!(
372            flat(Params::from_raw(b"0;;3")),
373            vec![Some(0), None, Some(3)]
374        );
375        assert_eq!(flat(Params::from_raw(b";5")), vec![None, Some(5)]);
376        assert_eq!(
377            flat(Params::from_raw(b"27;5;128512")),
378            vec![Some(27), Some(5), Some(128512)]
379        );
380    }
381
382    #[test]
383    fn flat_takes_first_colon_subparam() {
384        assert_eq!(flat(Params::from_raw(b"4:3;1")), vec![Some(4), Some(1)]);
385    }
386
387    #[test]
388    fn nested_preserves_colon_groups() {
389        assert_eq!(
390            nested(Params::from_raw(b"")),
391            Vec::<Vec<Option<u32>>>::new()
392        );
393        assert_eq!(
394            nested(Params::from_raw(b"38:2::255:100:50")),
395            vec![vec![
396                Some(38),
397                Some(2),
398                None,
399                Some(255),
400                Some(100),
401                Some(50),
402            ]]
403        );
404        assert_eq!(
405            nested(Params::from_raw(b"1;31;48:5:200")),
406            vec![
407                vec![Some(1)],
408                vec![Some(31)],
409                vec![Some(48), Some(5), Some(200)],
410            ]
411        );
412    }
413
414    #[test]
415    fn nested_empty_slots() {
416        assert_eq!(
417            nested(Params::from_raw(b";1;")),
418            vec![vec![None], vec![Some(1)], vec![None]]
419        );
420        assert_eq!(nested(Params::from_raw(b"4:")), vec![vec![Some(4), None]]);
421    }
422
423    #[test]
424    fn get_or_returns_default_only_for_absent() {
425        // Mirrors `;`-separated layout: [Some(5), None, Some(0), Some(7)]
426        let p = Params::from_raw(b"5;;0;7");
427        assert_eq!(p.get_or(0, 1), 5);
428        assert_eq!(p.get_or(1, 1), 1);
429        assert_eq!(p.get_or(2, 1), 0);
430        assert_eq!(p.get_or(3, 1), 7);
431        assert_eq!(p.get_or(4, 1), 1);
432        assert_eq!(Params::EMPTY.get_or(0, 42), 42);
433    }
434
435    #[test]
436    fn len_counts_groups() {
437        assert_eq!(Params::from_raw(b"").len(), 0);
438        assert_eq!(Params::from_raw(b"1").len(), 1);
439        assert_eq!(Params::from_raw(b";").len(), 2);
440        assert_eq!(Params::from_raw(b"1;2;3").len(), 3);
441        assert_eq!(Params::from_raw(b"1;").len(), 2);
442    }
443
444    #[test]
445    fn slice_from_skips_groups() {
446        let p = Params::from_raw(b"1;2;3;4");
447        assert_eq!(
448            flat(p.slice_from(0)),
449            vec![Some(1), Some(2), Some(3), Some(4)]
450        );
451        assert_eq!(flat(p.slice_from(2)), vec![Some(3), Some(4)]);
452        assert_eq!(flat(p.slice_from(4)), Vec::<Option<u32>>::new());
453        assert_eq!(flat(p.slice_from(99)), Vec::<Option<u32>>::new());
454    }
455
456    #[test]
457    fn debug_format_matches_flat_list() {
458        let p = Params::from_raw(b"1;2");
459        assert_eq!(format!("{:?}", p), "[Some(1), Some(2)]");
460    }
461
462    #[test]
463    fn control_sequence_splits_each_region() {
464        // Private prefix, parameters, final byte: DECSET of mode 2048.
465        let (s, rest) = ControlSequence::parse(b"?2048h").unwrap();
466        assert_eq!(s.private(), Some(b'?'));
467        assert_eq!(s.params().get_or(0, 0), 2048);
468        assert_eq!(s.intermediate(), None);
469        assert_eq!(s.final_byte(), b'h');
470        assert!(rest.is_empty());
471
472        // An intermediate, and a parameter that may be omitted: DECSCUSR.
473        let (s, _) = ControlSequence::parse(b"2 q").unwrap();
474        assert_eq!(s.params().get_or(0, 0), 2);
475        assert_eq!(s.intermediate(), Some(b' '));
476        assert_eq!(s.final_byte(), b'q');
477
478        let (s, _) = ControlSequence::parse(b" q").unwrap();
479        assert_eq!(s.params().get_or(0, 0), 0, "an omitted parameter is 0");
480        assert_eq!(s.intermediate(), Some(b' '));
481
482        // Subparameters stay available through `Params`.
483        let (s, _) = ControlSequence::parse(b"38:2::255:100:50m").unwrap();
484        assert_eq!(s.final_byte(), b'm');
485        assert_eq!(s.params().group(0).unwrap().nth(3), Some(255));
486    }
487
488    #[test]
489    fn control_sequence_returns_what_follows_the_final_byte() {
490        // A DCS carries its payload after the command section, which is why
491        // the tail is handed back rather than rejected.
492        let (s, rest) = ControlSequence::parse(b"1$r2 q").unwrap();
493        assert_eq!(s.params().get_or(0, 0), 1);
494        assert_eq!(s.intermediate(), Some(b'$'));
495        assert_eq!(s.final_byte(), b'r');
496        assert_eq!(rest, b"2 q");
497    }
498
499    #[test]
500    fn control_sequence_rejects_what_it_cannot_name() {
501        // No final byte at all.
502        assert!(ControlSequence::parse(b"").is_none());
503        assert!(ControlSequence::parse(b"12").is_none());
504        assert!(ControlSequence::parse(b"2 ").is_none());
505
506        // Two intermediates. Every control function in use carries at most
507        // one, so this is not a sequence worth recognizing. Taking the last
508        // would answer a question that was never asked.
509        assert!(ControlSequence::parse(b"1!!p").is_none());
510    }
511}