hid-decode 0.3.1

HID report descriptor decoding utilities
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
//! Decode a single item inside an HID report descriptor.

use hid_types::encoding::{Size, TagTypeSize, TypeBits};
use hid_types::id::{
    CollectionType, GlobalItem, InputFlags, IoFlags, LocalItem, MainItem, OutputFeatureFlags, Unit,
    UnitExponent, UsagePage,
};
use hid_types::item::usage::{ExtendedUsage, Usage};
use hid_types::item::{Global, Item, Local, LongItem, Main};
use tinyvec::{ArrayVec, TinyVec};

/// Context that can affect the way the decoder interprets subsequent descriptor items.
#[derive(Default, Debug, Clone)]
pub struct DecoderContext {
    /// The current usage page.
    usage_page: Option<UsagePage>,
    /// Whether or not zero-length payloads are permitted for items with values.
    ///
    /// The HID specification is vague about where this is permitted, or what it
    /// means (unchanged/default/zero).
    pub(crate) reject_zero_length_values: bool,
}

/// A successfully decoded descriptor item.
pub struct DecodedItem {
    /// The decoded descriptor item.
    pub item: Item,
    /// The bytes this item was decoded from.
    pub bytes: TinyVec<[u8; 4]>,
}

impl DecodedItem {
    /// Capture an item along with the bytes that were used to decode it.
    fn new<T>(item: Item, recorder: Recorder<T>) -> Self {
        Self {
            item,
            bytes: recorder.take_bytes(),
        }
    }
}

/// Decode one item from its encoded bytes.
///
/// This will consume one or more bytes from the input iterator.
pub fn decode_one<Iter>(
    iter: Iter,
    context: &mut DecoderContext,
) -> Option<Result<DecodedItem, LengthError>>
where
    Iter: Iterator<Item = u8>,
{
    let mut iter = Recorder::new(iter);

    let Some(tag) = iter.next() else {
        // End of input iterator
        return None;
    };
    Some(decode_one_inner(iter, context, tag))
}

/// Decode one item from its tag and any data bytes that follow.
///
/// This will consume zero or more bytes from the input iterator.
fn decode_one_inner<I>(
    mut iter: Recorder<I>,
    context: &mut DecoderContext,
    tag: u8,
) -> Result<DecodedItem, LengthError>
where
    I: Iterator<Item = u8>,
{
    let tag = TagTypeSize::from_bits(tag);

    let item_data = match tag.size() {
        Size::Short(size_bytes) => {
            ItemData::new(size_bytes, &mut iter, context.reject_zero_length_values)?
        }
        Size::Long => {
            let (Some(size), Some(tag)) = (iter.next(), iter.next()) else {
                return Err(LengthError::Truncated);
            };
            let iter_payload = (&mut iter).take(usize::from(size));
            let data = iter_payload.collect::<Vec<_>>();
            if data.len() != size as usize {
                return Err(LengthError::Truncated);
            }
            let item = Item::Long(LongItem { tag, data });
            return Ok(DecodedItem::new(item, iter));
        }
    };

    match tag.ty() {
        TypeBits::Main => {
            let item = MainItem::from(tag.tag());
            let decoded = match item {
                MainItem::Input => {
                    let data = item_data.to_u32()?;
                    let flags = InputFlags(IoFlags::from(data));
                    Main::Input(flags)
                }
                MainItem::Output => {
                    let data = item_data.to_u32()?;
                    let flags = OutputFeatureFlags(IoFlags::from(data));
                    Main::Output(flags)
                }
                MainItem::Feature => {
                    let data = item_data.to_u32()?;
                    let flags = OutputFeatureFlags(IoFlags::from(data));
                    Main::Feature(flags)
                }
                MainItem::Collection => {
                    let data = item_data.to_u8()?;
                    let coll_type = CollectionType::from_integer(data);
                    Main::Collection(coll_type)
                }
                MainItem::EndCollection => {
                    if !item_data.is_empty() {
                        return Err(LengthError::DataTooBig);
                    }
                    Main::EndCollection
                }
                MainItem::Reserved => {
                    let data = item_data.to_option_i32()?;
                    Main::Reserved(tag.tag(), data)
                }
            };
            Ok(DecodedItem::new(Item::Main(decoded), iter))
        }
        TypeBits::Global => {
            let item = GlobalItem::from(tag.tag());
            let decoded = match item {
                GlobalItem::UsagePage => {
                    let page_number = item_data.to_u16()?;
                    let usage_page = UsagePage::from_integer(page_number);
                    context.usage_page = Some(usage_page);
                    Global::UsagePage(usage_page)
                }
                GlobalItem::LogicalMinimum => {
                    let num = item_data.to_i32()?;
                    Global::LogicalMinimum(num)
                }
                GlobalItem::LogicalMaximum => {
                    let num = item_data.to_i32()?;
                    Global::LogicalMaximum(num)
                }
                GlobalItem::PhysicalMinimum => {
                    let num = item_data.to_i32()?;
                    Global::PhysicalMinimum(num)
                }
                GlobalItem::PhysicalMaximum => {
                    let num = item_data.to_i32()?;
                    Global::PhysicalMaximum(num)
                }
                GlobalItem::UnitExponent => {
                    // There's some disagreement about the allowed size of the
                    // unit exponent value; the UnitExponent struct has methods
                    // to paper over the worst of the problem.
                    let num = item_data.to_i32()?;
                    Global::UnitExponent(UnitExponent(num))
                }
                GlobalItem::ReportSize => {
                    let num = item_data.to_u32()?;
                    Global::ReportSize(num)
                }
                GlobalItem::ReportId => {
                    let num = item_data.to_u8()?;
                    Global::ReportId(num)
                }
                GlobalItem::ReportCount => {
                    let num = item_data.to_u32()?;
                    Global::ReportCount(num)
                }
                GlobalItem::Unit => {
                    let num = item_data.to_u32()?;
                    let unit = Unit::from_integer(num);
                    Global::Unit(unit)
                }
                GlobalItem::Push => {
                    if !item_data.is_empty() {
                        return Err(LengthError::DataTooBig);
                    }
                    Global::Push
                }
                GlobalItem::Pop => {
                    if !item_data.is_empty() {
                        return Err(LengthError::DataTooBig);
                    }
                    Global::Pop
                }
                GlobalItem::Reserved => {
                    let data = item_data.to_option_i32()?;
                    Global::Reserved(tag.tag(), data)
                }
            };
            Ok(DecodedItem::new(Item::Global(decoded), iter))
        }
        TypeBits::Local => {
            let item = LocalItem::from(tag.tag());
            let decoded = match item {
                LocalItem::Usage => {
                    // If the payload is 1 or 2 bytes, we use the
                    // existing page number. If the payload is 4 bytes, it
                    // contains both the page number and page id.
                    if item_data.len() == 4 {
                        let value = item_data.to_u32()?;
                        Local::ExtendedUsage(ExtendedUsage::from_u32(value))
                    } else {
                        let usage = item_data.to_u16()?;
                        match context.usage_page {
                            Some(page) => Local::Usage(Usage::new(page, usage)),
                            None => Local::Usage(Usage::without_page(usage)),
                        }
                    }
                }
                LocalItem::UsageMinimum => {
                    let num = item_data.to_u32()?;
                    Local::UsageMinimum(num)
                }
                LocalItem::UsageMaximum => {
                    let num = item_data.to_u32()?;
                    Local::UsageMaximum(num)
                }
                LocalItem::DesignatorIndex => {
                    let num = item_data.to_u32()?;
                    Local::DesignatorIndex(num)
                }
                LocalItem::DesignatorMinimum => {
                    let num = item_data.to_u32()?;
                    Local::DesignatorMinimum(num)
                }
                LocalItem::DesignatorMaximum => {
                    let num = item_data.to_u32()?;
                    Local::DesignatorMaximum(num)
                }
                LocalItem::StringIndex => {
                    let num = item_data.to_u32()?;
                    Local::StringIndex(num)
                }
                LocalItem::StringMinimum => {
                    let num = item_data.to_u32()?;
                    Local::StringMinimum(num)
                }
                LocalItem::StringMaximum => {
                    let num = item_data.to_u32()?;
                    Local::StringMaximum(num)
                }
                LocalItem::Delimiter => {
                    let num = item_data.to_u8()?;
                    let param = match num {
                        0 => false,
                        1 => true,
                        _ => return Err(LengthError::DataTooBig),
                    };
                    Local::Delimiter(param)
                }
                LocalItem::Reserved => {
                    let data = item_data.to_option_i32()?;
                    Local::Reserved(tag.tag(), data)
                }
            };
            Ok(DecodedItem::new(Item::Local(decoded), iter))
        }
        TypeBits::Reserved => {
            let data = item_data.to_option_i32()?;
            let decoded = Item::Reserved(tag.tag(), data);
            Ok(DecodedItem::new(decoded, iter))
        }
    }
}

/// An iterator that yields values from an inner iterator, but also collects everything that was yielded.
struct Recorder<Iter> {
    inner: Iter,
    bytes: TinyVec<[u8; 4]>,
}

impl<Iter> Recorder<Iter> {
    /// Create a new recording iterator.
    fn new(iter: Iter) -> Self {
        Self {
            inner: iter,
            bytes: TinyVec::new(),
        }
    }

    /// Take the recorded bytes, consuming the iterator.
    fn take_bytes(self) -> TinyVec<[u8; 4]> {
        self.bytes
    }
}

impl<Iter> Iterator for Recorder<Iter>
where
    Iter: Iterator<Item = u8>,
{
    type Item = u8;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().inspect(|b| {
            self.bytes.push(*b);
        })
    }
}

/// An error that resulted from improper item encoding.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
pub enum LengthError {
    /// The data length was too big for this item.
    #[error("item data too big")]
    DataTooBig,
    /// A data length of zero is not allowed in this item.
    #[error("missing item data")]
    ZeroLength,
    /// Ran out of bytes trying to decode this item.
    #[error("item data truncated")]
    Truncated,
}

/// The data payload from an item using the short encoding.
struct ItemData {
    /// Item data will always be 0 to 4 bytes (using the short encoding).
    data: ArrayVec<[u8; 4]>,
    /// Should zero-length data be interpreted as a value of 0?
    ///
    /// If false, trying to interpret as an integer will return `LengthError::ZeroLength`.
    reject_zero_length: bool,
}

impl ItemData {
    /// Collect item bytes from an iterator.
    fn new<I>(size: usize, iter: &mut I, reject_zero_length: bool) -> Result<Self, LengthError>
    where
        I: Iterator<Item = u8>,
    {
        if size > 4 {
            panic!("ItemData::new can't be called with size > 4");
        }

        let mut data = ArrayVec::default();
        for _ in 0..size {
            let byte = iter.next().ok_or(LengthError::Truncated)?;
            data.push(byte);
        }
        Ok(Self {
            data,
            reject_zero_length,
        })
    }

    fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn handle_zero<T: Default>(&self) -> Result<T, LengthError> {
        if self.reject_zero_length {
            Err(LengthError::ZeroLength)
        } else {
            Ok(T::default())
        }
    }

    fn to_u8(&self) -> Result<u8, LengthError> {
        match self.data.len() {
            0 => self.handle_zero(),
            1 => Ok(self.data[0]),
            _ => Err(LengthError::DataTooBig),
        }
    }

    fn to_u16(&self) -> Result<u16, LengthError> {
        match self.data.len() {
            0 => self.handle_zero(),
            1 => Ok(self.data[0] as u16),
            2 => {
                let ar: &[u8; 2] = self.data.as_array().unwrap();
                Ok(u16::from_le_bytes(*ar))
            }
            _ => Err(LengthError::DataTooBig),
        }
    }

    fn to_u32(&self) -> Result<u32, LengthError> {
        match self.data.len() {
            0 => self.handle_zero(),
            1 => Ok(self.data[0] as u32),
            2 => {
                let ar: &[u8; 2] = self.data.as_array().unwrap();
                let value = u16::from_le_bytes(*ar);
                Ok(value as u32)
            }
            3 => Err(LengthError::Truncated),
            4 => {
                let ar: &[u8; 4] = self.data.as_array().unwrap();
                Ok(u32::from_le_bytes(*ar))
            }
            _ => Err(LengthError::DataTooBig),
        }
    }

    fn to_i32(&self) -> Result<i32, LengthError> {
        match self.data.len() {
            0 => self.handle_zero(),
            1 => Ok(self.data[0] as i8 as i32),
            2 => {
                let ar: &[u8; 2] = self.data.as_array().unwrap();
                let value = i16::from_le_bytes(*ar);
                Ok(value as i32)
            }
            3 => Err(LengthError::Truncated),
            4 => {
                let ar: &[u8; 4] = self.data.as_array().unwrap();
                Ok(i32::from_le_bytes(*ar))
            }
            _ => Err(LengthError::DataTooBig),
        }
    }

    fn to_option_i32(&self) -> Result<Option<i32>, LengthError> {
        if self.is_empty() {
            Ok(None)
        } else {
            let value = self.to_i32()?;
            Ok(Some(value))
        }
    }
}

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

    #[test]
    fn _error_traits() {
        use std::error::Error;
        use std::fmt::Display;
        let _err: Box<dyn Error> = Box::new(LengthError::DataTooBig);
        let _err: Box<dyn Display> = Box::new(LengthError::DataTooBig);
        assert_eq!(format!("{}", LengthError::Truncated), "item data truncated");
    }

    #[test]
    fn test_integer_decoding() {
        #[track_caller]
        fn idata(slice: &[u8]) -> ItemData {
            ItemData::new(slice.len(), &mut slice.iter().copied(), true)
                .expect("malformed item data")
        }

        assert_eq!(idata(&[0xFF]).to_u8().unwrap(), 0xFF);
        idata(&[]).to_u8().unwrap_err();
        idata(&[0xFF, 0xFF]).to_u8().unwrap_err();

        #[track_caller]
        fn test_u16(slice: &[u8], expected: Result<u16, LengthError>) {
            assert_eq!(idata(slice).to_u16(), expected);
        }

        test_u16(&[0xFF], Ok(0xFF));
        test_u16(&[0xFF, 0xFF], Ok(0xFFFF));
        test_u16(&[1, 2], Ok(0x0201));
        test_u16(&[], Err(LengthError::ZeroLength));
        test_u16(&[0xFF; 3], Err(LengthError::DataTooBig));
        test_u16(&[0xFF; 4], Err(LengthError::DataTooBig));

        #[track_caller]
        fn test_u32(slice: &[u8], expected: Result<u32, LengthError>) {
            assert_eq!(idata(slice).to_u32(), expected);
        }

        test_u32(&[0xFF], Ok(0xFF));
        test_u32(&[0xFF, 0xFF], Ok(0xFFFF));
        test_u32(&[1, 2], Ok(0x0201));
        test_u32(&[0xFF; 4], Ok(0xFFFFFFFF));
        test_u32(&[1, 2, 3, 4], Ok(0x04030201));
        test_u32(&[], Err(LengthError::ZeroLength));
        test_u32(&[0xFF; 3], Err(LengthError::Truncated));

        #[track_caller]
        fn test_i32(slice: &[u8], expected: Result<i32, LengthError>) {
            assert_eq!(idata(slice).to_i32(), expected);
        }

        test_i32(&[0], Ok(0));
        test_i32(&[0, 0], Ok(0));
        test_i32(&[0, 0, 0, 0], Ok(0));
        test_i32(&[1, 2], Ok(0x0201));
        test_i32(&[0; 4], Ok(0));
        test_i32(&[1, 2, 3, 4], Ok(0x04030201));
        test_i32(&[0xFF], Ok(-1));
        test_i32(&[0xFF, 0xFF], Ok(-1));
        test_i32(&[0xFF; 4], Ok(-1));
        test_i32(&[], Err(LengthError::ZeroLength));
        test_i32(&[0xFF; 3], Err(LengthError::Truncated));
    }
}