hid_decode/lib.rs
1//! # HID report descriptor decoding utilities
2//!
3//! This library can perform text or structured decoding of USB HID report descriptors.
4//! For text decoding, use [`decode()`] or [`TextDecoder`].
5//! For structured decoding, use [`decode_items()`] or [`ItemDecoder`].
6//!
7//! The decoders don't understand the meaning of HID report descriptors, so they can't be used
8//! to automatically determine the size and layout of HID reports.
9//!
10//! See [Device Class Definition for Human Interface Devices](https://www.usb.org/document-library/device-class-definition-hid-111)
11//! for a detailed description of HID report descriptors.
12//!
13//! # Example
14//! ```rust
15//! # // This descriptor was generated by an example in the `hid-descriptor` crate sources.
16//! # static GAMEPAD_DESCRIPTOR: &[u8] = include_bytes!("../tests/gamepad.bin");
17//! let mut output = Vec::new();
18//! hid_decode::decode(&mut output, &GAMEPAD_DESCRIPTOR).expect("write error");
19//! let output = String::try_from(output).expect("non-UTF8 output");
20//! assert_eq!(
21//! output.lines().collect::<Vec<_>>(),
22//! [
23//! "Usage Page: GenericDesktop",
24//! "Usage: Gamepad",
25//! "Collection: Application",
26//! "Usage Page: Button",
27//! "Usage Minimum: 1",
28//! "Usage Maximum: 8",
29//! "Logical Minimum: 0",
30//! "Logical Maximum: 1",
31//! "Report Size: 1",
32//! "Report Count: 8",
33//! "Input: Data Variable Absolute No-Wrap Linear Preferred-State No-Null-Position Bit-Field",
34//! "EndCollection",
35//! ]
36//! );
37//! ```
38
39#![warn(clippy::print_stderr, clippy::print_stdout, clippy::dbg_macro)]
40#![warn(clippy::todo)]
41#![warn(missing_docs)]
42
43use std::io::Write;
44
45use hid_types::item::Item;
46
47use crate::item::{DecoderContext, decode_one};
48
49#[doc(inline)]
50pub use crate::item::LengthError;
51
52pub mod item;
53
54/// Structured decode of an HID report descriptor.
55///
56/// An `ItemDecoder` is a decoder that returns a sequence of decoded [`Item`]s.
57pub struct ItemDecoder<'a> {
58 iter: std::iter::Copied<std::slice::Iter<'a, u8>>,
59 context: DecoderContext,
60}
61
62impl<'a> ItemDecoder<'a> {
63 /// Create a new [`ItemDecoder`].
64 pub fn new(bytes: &'a [u8]) -> Self {
65 let iter = bytes.iter().copied();
66 Self {
67 iter,
68 context: Default::default(),
69 }
70 }
71
72 /// Don't allow zero-length data on descriptor items with values.
73 pub fn reject_zero_length_values(mut self) -> Self {
74 self.context.reject_zero_length_values = true;
75 self
76 }
77}
78
79impl<'a> Iterator for ItemDecoder<'a> {
80 type Item = Result<Item, LengthError>;
81
82 fn next(&mut self) -> Option<Self::Item> {
83 decode_one(&mut self.iter, &mut self.context)
84 .map(|item_maybe| item_maybe.map(|item| item.item))
85 }
86}
87
88/// Structured decode of an HID report descriptor.
89///
90/// Decode an HID descriptor to a list of [`Item`]s.
91/// This is a shorter way of writing `ItemDecoder::new(bytes).collect()`.
92pub fn decode_items(bytes: &[u8]) -> Result<Vec<Item>, LengthError> {
93 ItemDecoder::new(bytes).collect()
94}
95
96/// Decode an HID report descriptor to text, using the default settings.
97///
98/// This is a shorter way of writing `TextDecoder::new(writer).decode(bytes)`.
99pub fn decode<W>(writer: W, bytes: &[u8]) -> std::io::Result<()>
100where
101 W: Write,
102{
103 TextDecoder::new(writer).decode(bytes)
104}
105
106/// Settings that control how a `TextDecoder` displays its output.
107#[derive(Default, Debug, Clone)]
108struct OutputOptions {
109 /// Display the item tag types, i.e. Main, Global, Local.
110 pub display_tag_type: bool,
111 /// Display the bytes that make up each item.
112 pub display_raw_bytes: bool,
113}
114
115/// Decode an HID report descriptor to plain text.
116///
117#[derive(Clone)]
118pub struct TextDecoder<W> {
119 // FIXME: add a way to abstract over both std::io::Write (files, stdout) and std::fmt::Write (String).
120 writer: W,
121 output_options: OutputOptions,
122 context: DecoderContext,
123}
124
125impl<W> TextDecoder<W>
126where
127 W: Write,
128{
129 /// Create a new [`TextDecoder`], by specifying where the output will be written.
130 ///
131 /// # Example
132 /// ```rust
133 /// # use hid_decode::TextDecoder;
134 /// let mut decoder = TextDecoder::new(std::io::stdout());
135 /// ```
136 pub fn new(writer: W) -> Self {
137 Self {
138 writer,
139 output_options: Default::default(),
140 context: Default::default(),
141 }
142 }
143
144 /// Display the item tag types, i.e. Main, Global, Local.
145 pub fn display_tag_type(mut self) -> Self {
146 self.output_options.display_tag_type = true;
147 self
148 }
149
150 /// Display the raw bytes that make up each item.
151 pub fn display_raw_bytes(mut self) -> Self {
152 self.output_options.display_raw_bytes = true;
153 self
154 }
155
156 /// Don't allow zero-length data on descriptor items with values.
157 pub fn reject_zero_length_values(mut self) -> Self {
158 self.context.reject_zero_length_values = true;
159 self
160 }
161
162 /// Decode HID descriptor bytes as text.
163 ///
164 /// This will consume the `Decoder`. If multiple descriptors will be decoded,
165 /// `clone()` the decoder _before_ calling `decode()`.
166 pub fn decode(mut self, bytes: &[u8]) -> std::io::Result<()> {
167 let mut iter = bytes.iter().copied();
168 loop {
169 match decode_one(&mut iter, &mut self.context) {
170 None => break,
171 Some(Ok(item)) => {
172 if self.output_options.display_raw_bytes {
173 let mut hex = String::new();
174 for byte in item.bytes {
175 use std::fmt::Write;
176 write!(hex, "{byte:02x} ").unwrap();
177 }
178 write!(self.writer, "{hex:9} ")?;
179 }
180 if self.output_options.display_tag_type {
181 write!(self.writer, "{:9}", item.item.type_note())?;
182 }
183 writeln!(self.writer, "{}", item.item)?;
184 }
185 Some(Err(e)) => return Err(std::io::Error::other(e)),
186 }
187 }
188 Ok(())
189 }
190}