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
//! Lazy parser for CSI and DCS parameter bodies.
//!
//! ## Category
//!
//! [`Params`] and [`Group`] expose the bytes between a control-sequence
//! introducer and its final byte. They handle 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':'
}
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)]");
}
}