Skip to main content

usb_stack/
descriptor.rs

1//! USB descriptor builder.
2//!
3//! [`DescriptorWriter`] provides a cursor-based API for writing USB descriptors
4//! into a byte buffer without any unsafe or transmute operations.
5
6use crate::bus::{InterfaceNumber, StringIndex};
7use crate::endpoint::{EndpointAddress, EndpointType};
8use crate::error::{UsbError, UsbResult};
9
10// ─── Standard descriptor type codes ──────────────────────────────────────────
11
12/// `bDescriptorType` values (USB 2.0 §9.4).
13#[allow(missing_docs)]
14pub mod descriptor_type {
15    pub const DEVICE: u8 = 1;
16    pub const CONFIGURATION: u8 = 2;
17    pub const STRING: u8 = 3;
18    pub const INTERFACE: u8 = 4;
19    pub const ENDPOINT: u8 = 5;
20    pub const DEVICE_QUALIFIER: u8 = 6;
21    pub const OTHER_SPEED_CONFIGURATION: u8 = 7;
22    pub const INTERFACE_ASSOCIATION: u8 = 11;
23    /// Alias of [`INTERFACE_ASSOCIATION`].
24    pub const IAD: u8 = INTERFACE_ASSOCIATION;
25    pub const BOS: u8 = 15;
26    pub const DEVICE_CAPABILITY: u8 = 16;
27    /// Alias of [`DEVICE_CAPABILITY`].
28    pub const CAPABILITY: u8 = DEVICE_CAPABILITY;
29}
30
31/// USB language IDs (ISO 639).
32pub mod lang_id {
33    /// English (United States).
34    pub const EN_US: u16 = 0x0409;
35}
36
37// ─── USB class / subclass / protocol constants ────────────────────────────────
38
39/// USB class codes (`bDeviceClass` / `bInterfaceClass`).
40#[allow(missing_docs)]
41pub mod class_code {
42    pub const CDC: u8 = 0x02;
43    pub const CDC_DATA: u8 = 0x0A;
44    pub const HID: u8 = 0x03;
45    pub const MISC: u8 = 0xEF;
46    pub const NONE: u8 = 0x00;
47    /// Vendor-specific interface/device class.
48    pub const VENDOR: u8 = 0xFF;
49}
50
51/// CDC interface subclasses (`bInterfaceSubClass`).
52#[allow(missing_docs)]
53pub mod cdc_subclass {
54    pub const ACM: u8 = 0x02;
55}
56
57/// CDC interface protocols (`bInterfaceProtocol`).
58#[allow(missing_docs)]
59pub mod cdc_protocol {
60    pub const AT_COMMANDS: u8 = 0x01;
61    pub const NONE: u8 = 0x00;
62}
63
64/// CDC functional descriptors subtypes.
65#[allow(missing_docs)]
66pub mod cdc_descriptor {
67    /// bDescriptorType for class-specific interface descriptors.
68    pub const CS_INTERFACE: u8 = 0x24;
69    pub const HEADER: u8 = 0x00;
70    pub const CALL_MANAGEMENT: u8 = 0x01;
71    pub const ACM: u8 = 0x02;
72    pub const ABSTRACT_CONTROL_MANAGEMENT: u8 = 0x02;
73    pub const UNION: u8 = 0x06;
74}
75
76// ─── DescriptorWriter ─────────────────────────────────────────────────────────
77
78/// Cursor-based USB descriptor builder.
79///
80/// Wraps a `&mut [u8]` buffer and advances a position pointer as descriptors
81/// are appended.  The configuration-descriptor wTotalLength and bNumInterfaces
82/// fields are back-patched when [`end_configuration`](Self::end_configuration)
83/// is called.
84pub struct DescriptorWriter<'a> {
85    buf: &'a mut [u8],
86    pos: usize,
87    /// Byte offset of the wTotalLength field in the current configuration
88    /// descriptor, if one has been opened.
89    config_total_len_pos: Option<usize>,
90    /// Byte offset of the bNumInterfaces field.
91    config_num_ifaces_pos: Option<usize>,
92    /// Running interface count for the current configuration.
93    num_interfaces: u8,
94}
95
96impl<'a> DescriptorWriter<'a> {
97    /// Create a new writer over `buf`.
98    pub fn new(buf: &'a mut [u8]) -> Self {
99        Self {
100            buf,
101            pos: 0,
102            config_total_len_pos: None,
103            config_num_ifaces_pos: None,
104            num_interfaces: 0,
105        }
106    }
107
108    /// Bytes written so far.
109    pub fn position(&self) -> usize {
110        self.pos
111    }
112
113    // ── Low-level primitives ─────────────────────────────────────────────────
114
115    /// Append a raw byte sequence preceded by a 2-byte header (bLength, bDescriptorType).
116    ///
117    /// `f` receives a mutable slice of up to 254 bytes (max descriptor body size)
118    /// and should write the descriptor body, returning the body length.
119    pub fn write_with(
120        &mut self,
121        descriptor_type: u8,
122        f: impl FnOnce(&mut [u8]) -> UsbResult<usize>,
123    ) -> UsbResult<()> {
124        if self.pos + 2 > self.buf.len() {
125            return Err(UsbError::BufferOverflow);
126        }
127        let body_start = self.pos + 2;
128        let body_end = self.buf.len().min(body_start + 254);
129        let body_len = f(&mut self.buf[body_start..body_end])?;
130        let total_len = body_len + 2;
131        if self.pos + total_len > self.buf.len() {
132            return Err(UsbError::BufferOverflow);
133        }
134        self.buf[self.pos] = total_len as u8;
135        self.buf[self.pos + 1] = descriptor_type;
136        self.pos += total_len;
137        Ok(())
138    }
139
140    /// Append a descriptor with a fixed body slice.
141    pub fn write(&mut self, descriptor_type: u8, body: &[u8]) -> UsbResult<()> {
142        self.write_with(descriptor_type, |buf| {
143            if body.len() > buf.len() {
144                return Err(UsbError::BufferOverflow);
145            }
146            buf[..body.len()].copy_from_slice(body);
147            Ok(body.len())
148        })
149    }
150
151    // ── Configuration descriptor ─────────────────────────────────────────────
152
153    /// Begin a configuration descriptor.  Must be paired with
154    /// [`end_configuration`](Self::end_configuration).
155    pub fn configuration(&mut self, attributes: u8, max_power_ma: u8) -> UsbResult<()> {
156        self.config_total_len_pos = Some(self.pos + 2); // offset of wTotalLength[0]
157        self.config_num_ifaces_pos = Some(self.pos + 4); // offset of bNumInterfaces
158        self.num_interfaces = 0;
159        self.write(
160            descriptor_type::CONFIGURATION,
161            &[
162                0,
163                0, // wTotalLength — patched later
164                0, // bNumInterfaces — patched later
165                1, // bConfigurationValue
166                0, // iConfiguration
167                attributes,
168                max_power_ma,
169            ],
170        )
171    }
172
173    /// Finalise the open configuration descriptor (patch wTotalLength and
174    /// bNumInterfaces).
175    pub fn end_configuration(&mut self) {
176        if let (Some(tl_pos), Some(ni_pos)) =
177            (self.config_total_len_pos, self.config_num_ifaces_pos)
178        {
179            let total = self.pos as u16;
180            self.buf[tl_pos] = total as u8;
181            self.buf[tl_pos + 1] = (total >> 8) as u8;
182            self.buf[ni_pos] = self.num_interfaces;
183        }
184        self.config_total_len_pos = None;
185        self.config_num_ifaces_pos = None;
186    }
187
188    // ── Interface & endpoint ─────────────────────────────────────────────────
189
190    /// Write an Interface Association Descriptor (IAD), if the configuration was
191    /// built with `composite_with_iads = true`.
192    ///
193    /// Always safe to call — if the outer device was not configured for IADs the
194    /// call is a no-op.
195    pub fn iad(
196        &mut self,
197        first_interface: InterfaceNumber,
198        interface_count: u8,
199        function_class: u8,
200        function_subclass: u8,
201        function_protocol: u8,
202    ) -> UsbResult<()> {
203        self.write(
204            descriptor_type::IAD,
205            &[
206                first_interface.into(),
207                interface_count,
208                function_class,
209                function_subclass,
210                function_protocol,
211                0, // iFunction
212            ],
213        )
214    }
215
216    /// Write an Interface descriptor and increment the interface count.
217    pub fn interface(
218        &mut self,
219        number: InterfaceNumber,
220        num_endpoints: u8,
221        class: u8,
222        subclass: u8,
223        protocol: u8,
224    ) -> UsbResult<()> {
225        self.interface_with_string(
226            number,
227            num_endpoints,
228            class,
229            subclass,
230            protocol,
231            StringIndex::new(0),
232        )
233    }
234
235    /// Write an Interface descriptor with a string index.
236    pub fn interface_with_string(
237        &mut self,
238        number: InterfaceNumber,
239        num_endpoints: u8,
240        class: u8,
241        subclass: u8,
242        protocol: u8,
243        string: StringIndex,
244    ) -> UsbResult<()> {
245        self.num_interfaces += 1;
246        self.write(
247            descriptor_type::INTERFACE,
248            &[
249                number.into(),
250                0, // bAlternateSetting
251                num_endpoints,
252                class,
253                subclass,
254                protocol,
255                string.into(),
256            ],
257        )
258    }
259
260    /// Write an Interface descriptor with a non-zero alternate setting.
261    ///
262    /// Does **not** increment `bNumInterfaces` — alternate settings share the
263    /// same interface number and are not counted separately.
264    pub fn interface_alt(
265        &mut self,
266        number: InterfaceNumber,
267        alternate_setting: u8,
268        num_endpoints: u8,
269        class: u8,
270        subclass: u8,
271        protocol: u8,
272    ) -> UsbResult<()> {
273        self.write(
274            descriptor_type::INTERFACE,
275            &[
276                number.into(),
277                alternate_setting,
278                num_endpoints,
279                class,
280                subclass,
281                protocol,
282                0, // iInterface
283            ],
284        )
285    }
286
287    /// Write an Endpoint descriptor.
288    pub fn endpoint(
289        &mut self,
290        addr: EndpointAddress,
291        ep_type: EndpointType,
292        max_packet_size: u16,
293        interval: u8,
294    ) -> UsbResult<()> {
295        self.write(
296            descriptor_type::ENDPOINT,
297            &[
298                addr.raw(),
299                ep_type.bm_attributes(),
300                max_packet_size as u8,
301                (max_packet_size >> 8) as u8,
302                interval,
303            ],
304        )
305    }
306
307    // ── String descriptors ───────────────────────────────────────────────────
308
309    /// Encode a UTF-8 string as a USB string descriptor (UTF-16LE with header)
310    /// and write it into `buf`.  Returns the number of bytes written.
311    ///
312    /// Call this from the device layer when responding to GET_DESCRIPTOR(String).
313    pub fn write_string(buf: &mut [u8], s: &str) -> UsbResult<usize> {
314        if buf.len() < 2 {
315            return Err(UsbError::BufferOverflow);
316        }
317        let max_chars = (buf.len() - 2) / 2;
318        let mut n = 0usize;
319        for c in s.chars().take(max_chars) {
320            // Non-BMP code points are replaced with U+FFFD (replacement char).
321            let unit = if (c as u32) <= 0xFFFF {
322                c as u16
323            } else {
324                0xFFFD
325            };
326            buf[2 + n * 2] = unit as u8;
327            buf[3 + n * 2] = (unit >> 8) as u8;
328            n += 1;
329        }
330        let total = 2 + n * 2;
331        buf[0] = total as u8;
332        buf[1] = descriptor_type::STRING;
333        Ok(total)
334    }
335
336    /// Write the language ID list descriptor (index 0) into `buf`.
337    pub fn write_lang_ids(buf: &mut [u8], lang_ids: &[u16]) -> UsbResult<usize> {
338        let total = 2 + lang_ids.len() * 2;
339        if total > buf.len() {
340            return Err(UsbError::BufferOverflow);
341        }
342        buf[0] = total as u8;
343        buf[1] = descriptor_type::STRING;
344        for (i, &id) in lang_ids.iter().enumerate() {
345            buf[2 + i * 2] = id as u8;
346            buf[2 + i * 2 + 1] = (id >> 8) as u8;
347        }
348        Ok(total)
349    }
350}