hid-decode 0.1.0

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
//! # HID report descriptor decoding utilities
//!
//! This library can perform text decoding of USB HID report descriptors.
//!
//! It does not perform stateful functional decoding, so it can't (yet)
//! determine the size and layout of HID reports.
//!
//! See [Device Class Definition for Human Interface Devices](https://www.usb.org/document-library/device-class-definition-hid-111)
//! for a detailed description of HID report descriptors.
//!
//! # Example
//! ```rust
//! # // This descriptor was generated by an example in the `hid-descriptor` crate sources.
//! # static GAMEPAD_DESCRIPTOR: &[u8] = include_bytes!("../tests/gamepad.bin");
//! let mut output = Vec::new();
//! hid_decode::decode(&mut output, GAMEPAD_DESCRIPTOR.iter().copied()).expect("write error");
//! let output = String::try_from(output).expect("non-UTF8 output");
//! assert_eq!(
//!     output.lines().collect::<Vec<_>>(),
//!     [
//!         "Usage Page: GenericDesktop",
//!         "Usage: Gamepad",
//!         "Collection: Application",
//!         "Usage Page: Button",
//!         "Usage Minimum: 1",
//!         "Usage Maximum: 8",
//!         "Logical Minimum: 0",
//!         "Logical Maximum: 1",
//!         "Report Size: 1",
//!         "Report Count: 8",
//!         "Input: Data Variable Absolute No-Wrap Linear Preferred-State No-Null-Position Bit-Field",
//!         "EndCollection",
//!     ]
//! );
//! ```

#![warn(clippy::print_stderr, clippy::print_stdout, clippy::dbg_macro)]
#![warn(clippy::todo)]
#![warn(missing_docs)]

use std::io::Write;

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

/// Decode HID descriptor bytes as text.
///
/// The output text will be written to the `writer`.
pub fn decode<W, I>(writer: W, bytes: I) -> std::io::Result<()>
where
    W: Write,
    I: IntoIterator<Item = u8>,
{
    decode_with_options(writer, bytes, Verbosity::default())
}

/// Decode HID descriptor bytes as text.
///
/// The output text will be written to the `writer`.
/// Use `verbosity` to select the level of detail.
pub fn decode_with_options<W, I>(
    mut writer: W,
    bytes: I,
    verbosity: Verbosity,
) -> std::io::Result<()>
where
    W: Write,
    I: IntoIterator<Item = u8>,
{
    let mut iter = bytes.into_iter();
    let mut decoder = DecoderContext::new(verbosity);
    loop {
        match decoder.decode_one(&mut iter) {
            Ok(Some(item)) => {
                if decoder.verbosity.display_tag_type {
                    write!(writer, "{:9}", item.type_note())?;
                }
                writeln!(writer, "{item}")?;
            }
            Ok(None) => break,
            Err(_e) => return Err(std::io::Error::other("decoding failed")),
        }
    }
    Ok(())
}

/// Configuration for decoding descriptors to text.
#[derive(Clone, Default)]
pub struct Verbosity {
    /// Display the item tag types, i.e. Main, Global, Local.
    pub display_tag_type: bool,
}

/// HID Decoder state.
#[derive(Default)]
pub struct DecoderContext {
    /// Decoder verbosity.
    verbosity: Verbosity,
    /// The current usage page.
    usage_page: Option<UsagePage>,
}

impl DecoderContext {
    fn new(verbosity: Verbosity) -> Self {
        Self {
            verbosity,
            ..Default::default()
        }
    }

    /// Decode one item from its encoded bytes.
    ///
    /// This will consume a variable number of bytes from the input iterator.
    pub fn decode_one<Iter>(&mut self, iter: &mut Iter) -> Result<Option<Item>, LengthError>
    where
        Iter: Iterator<Item = u8>,
    {
        let Some(tag) = iter.next() else {
            // End of input iterator
            return Ok(None);
        };
        let tag = TagTypeSize::from_bits(tag);

        let more = match tag.size() {
            Size::Short(size_bytes) => {
                let iter_remaining = iter.take(size_bytes);
                iter_remaining.collect::<Vec<_>>()
            }
            Size::Long => {
                let (Some(size), Some(tag)) = (iter.next(), iter.next()) else {
                    return Err(LengthError::Truncated);
                };
                let iter_payload = iter.take(usize::from(size));
                let data = iter_payload.collect::<Vec<_>>();
                let item = Item::Long(LongItem { tag, data });
                return Ok(Some(item));
            }
        };

        match tag.ty() {
            TypeBits::Main => {
                let item = MainItem::from(tag.tag());
                let decoded = match item {
                    MainItem::Input => {
                        let data = slice_to_u32(&more)?;
                        let flags = InputFlags(IoFlags::from(data));
                        Main::Input(flags)
                    }
                    MainItem::Output => {
                        let data = slice_to_u32(&more)?;
                        let flags = OutputFeatureFlags(IoFlags::from(data));
                        Main::Output(flags)
                    }
                    MainItem::Feature => {
                        let data = slice_to_u32(&more)?;
                        let flags = OutputFeatureFlags(IoFlags::from(data));
                        Main::Feature(flags)
                    }
                    MainItem::Collection => {
                        assert_eq!(more.len(), 1);
                        let coll_type = CollectionType::from_integer(more[0]);
                        Main::Collection(coll_type)
                    }
                    MainItem::EndCollection => {
                        assert!(more.is_empty());
                        Main::EndCollection
                    }
                    MainItem::Reserved => Main::Reserved(tag.tag()),
                };
                Ok(Some(Item::Main(decoded)))
            }
            TypeBits::Global => {
                let item = GlobalItem::from(tag.tag());
                let decoded = match item {
                    GlobalItem::UsagePage => {
                        let page_number = slice_to_u16(&more)?;
                        let usage_page = UsagePage::from_integer(page_number);
                        self.usage_page = Some(usage_page);
                        Global::UsagePage(usage_page)
                    }
                    GlobalItem::LogicalMinimum => {
                        let num = slice_to_i32(&more)?;
                        Global::LogicalMinimum(num)
                    }
                    GlobalItem::LogicalMaximum => {
                        let num = slice_to_i32(&more)?;
                        Global::LogicalMaximum(num)
                    }
                    GlobalItem::PhysicalMinimum => {
                        let num = slice_to_i32(&more)?;
                        Global::PhysicalMinimum(num)
                    }
                    GlobalItem::PhysicalMaximum => {
                        let num = slice_to_i32(&more)?;
                        Global::PhysicalMaximum(num)
                    }
                    GlobalItem::UnitExponent => {
                        let num = slice_to_i32(&more)?;
                        Global::UnitExponent(num)
                    }
                    GlobalItem::ReportSize => {
                        let num = slice_to_u32(&more)?;
                        Global::ReportSize(num)
                    }
                    GlobalItem::ReportId => {
                        let num = slice_to_u32(&more)?;
                        Global::ReportId(num)
                    }
                    GlobalItem::ReportCount => {
                        let num = slice_to_u32(&more)?;
                        Global::ReportCount(num)
                    }
                    GlobalItem::Unit => {
                        let num = slice_to_u32(&more)?;
                        let unit = Unit::from_integer(num);
                        Global::Unit(unit)
                    }
                    GlobalItem::Push => Global::Push,
                    GlobalItem::Pop => Global::Pop,
                    GlobalItem::Reserved => Global::Reserved(tag.tag()),
                };
                Ok(Some(Item::Global(decoded)))
            }
            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.
                        match slice_to_u16(&more) {
                            Ok(page_id) => match self.usage_page {
                                Some(page) => Local::Usage(Usage::new(page, page_id)),

                                None => Local::Usage(Usage::without_page(page_id)),
                            },
                            Err(LengthError::DataTooBig) => {
                                let value = slice_to_u32(&more)?;
                                Local::ExtendedUsage(ExtendedUsage::from_u32(value))
                            }
                            Err(e) => return Err(e),
                        }
                    }
                    LocalItem::UsageMinimum => {
                        let num = slice_to_u32(&more)?;
                        Local::UsageMinimum(num)
                    }
                    LocalItem::UsageMaximum => {
                        let num = slice_to_u32(&more)?;
                        Local::UsageMaximum(num)
                    }
                    LocalItem::DesignatorIndex => {
                        let num = slice_to_u32(&more)?;
                        Local::DesignatorIndex(num)
                    }
                    LocalItem::DesignatorMinimum => {
                        let num = slice_to_u32(&more)?;
                        Local::DesignatorMinimum(num)
                    }
                    LocalItem::DesignatorMaximum => {
                        let num = slice_to_u32(&more)?;
                        Local::DesignatorMaximum(num)
                    }
                    LocalItem::StringIndex => {
                        let num = slice_to_u32(&more)?;
                        Local::StringIndex(num)
                    }
                    LocalItem::StringMinimum => {
                        let num = slice_to_u32(&more)?;
                        Local::StringMinimum(num)
                    }
                    LocalItem::StringMaximum => {
                        let num = slice_to_u32(&more)?;
                        Local::StringMaximum(num)
                    }
                    LocalItem::Delimiter => {
                        let num = slice_to_u8(&more)?;
                        let param = match num {
                            0 => false,
                            1 => true,
                            _ => return Err(LengthError::DataTooBig),
                        };
                        Local::Delimiter(param)
                    }
                    LocalItem::Reserved => Local::Reserved(tag.tag()),
                };
                Ok(Some(Item::Local(decoded)))
            }
            TypeBits::Reserved => {
                let decoded = Item::Reserved(tag.ty().into_bits());
                Ok(Some(decoded))
            }
        }
    }
}

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

fn slice_to_u8(slice: &[u8]) -> Result<u8, LengthError> {
    match slice.len() {
        0 => Err(LengthError::ZeroLength),
        1 => Ok(slice[0]),
        _ => Err(LengthError::DataTooBig),
    }
}

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

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

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

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

    #[test]
    fn test_integer_decoding() {
        assert_eq!(slice_to_u8(&[0xFF]).unwrap(), 0xFF);
        slice_to_u8(&[]).unwrap_err();
        slice_to_u8(&[0xFF, 0xFF]).unwrap_err();

        assert_eq!(slice_to_u16(&[0xFF]).unwrap(), 0xFF);
        assert_eq!(slice_to_u16(&[0xFF, 0xFF]).unwrap(), 0xFFFF);
        assert_eq!(slice_to_u16(&[1, 2]).unwrap(), 0x0201);
        slice_to_u16(&[]).unwrap_err();
        slice_to_u16(&[0xFF; 3]).unwrap_err();
        slice_to_u16(&[0xFF; 4]).unwrap_err();

        assert_eq!(slice_to_u32(&[0xFF]).unwrap(), 0xFF);
        assert_eq!(slice_to_u32(&[0xFF, 0xFF]).unwrap(), 0xFFFF);
        assert_eq!(slice_to_u32(&[1, 2]).unwrap(), 0x0201);
        assert_eq!(slice_to_u32(&[0xFF; 4]).unwrap(), 0xFFFFFFFF);
        assert_eq!(slice_to_u32(&[1, 2, 3, 4]).unwrap(), 0x04030201);
        slice_to_u32(&[]).unwrap_err();
        slice_to_u32(&[0xFF; 3]).unwrap_err();
        slice_to_u32(&[0xFF; 5]).unwrap_err();

        assert_eq!(slice_to_i32(&[0]).unwrap(), 0);
        assert_eq!(slice_to_i32(&[0, 0]).unwrap(), 0);
        assert_eq!(slice_to_i32(&[1, 2]).unwrap(), 0x0201);
        assert_eq!(slice_to_i32(&[0; 4]).unwrap(), 0);
        assert_eq!(slice_to_i32(&[1, 2, 3, 4]).unwrap(), 0x04030201);
        assert_eq!(slice_to_i32(&[0xFF]).unwrap(), -1);
        assert_eq!(slice_to_i32(&[0xFF, 0xFF]).unwrap(), -1);
        assert_eq!(slice_to_i32(&[0xFF; 4]).unwrap(), -1);
        slice_to_i32(&[]).unwrap_err();
        slice_to_i32(&[0xFF; 3]).unwrap_err();
        slice_to_i32(&[0xFF; 5]).unwrap_err();
    }
}