Skip to main content

usb_stack/device/
descriptor.rs

1//! Configuration descriptor builder.
2//!
3//! [`DescriptorWriter`] appends interface, endpoint and class-specific
4//! descriptors to the configuration buffer the device stack answers
5//! `GET_DESCRIPTOR(CONFIGURATION)` with.
6
7use crate::descriptor::descriptor_type;
8use crate::device::bus::{InterfaceNumber, StringIndex};
9use crate::device::error::{UsbError, UsbResult};
10use crate::endpoint::{EndpointAddress, EndpointType};
11
12// ─── DescriptorWriter ─────────────────────────────────────────────────────────
13
14/// Cursor-based USB descriptor builder.
15///
16/// Wraps a `&mut [u8]` buffer and advances a position pointer as descriptors
17/// are appended.  The configuration-descriptor wTotalLength and bNumInterfaces
18/// fields are back-patched when [`end_configuration`](Self::end_configuration)
19/// is called.
20pub struct DescriptorWriter<'a> {
21    buf: &'a mut [u8],
22    pos: usize,
23    /// Byte offset of the wTotalLength field in the current configuration
24    /// descriptor, if one has been opened.
25    config_total_len_pos: Option<usize>,
26    /// Byte offset of the bNumInterfaces field.
27    config_num_ifaces_pos: Option<usize>,
28    /// Running interface count for the current configuration.
29    num_interfaces: u8,
30}
31
32impl<'a> DescriptorWriter<'a> {
33    /// Create a new writer over `buf`.
34    pub fn new(buf: &'a mut [u8]) -> Self {
35        Self {
36            buf,
37            pos: 0,
38            config_total_len_pos: None,
39            config_num_ifaces_pos: None,
40            num_interfaces: 0,
41        }
42    }
43
44    /// Bytes written so far.
45    pub fn position(&self) -> usize {
46        self.pos
47    }
48
49    // ── Low-level primitives ─────────────────────────────────────────────────
50
51    /// Append a raw byte sequence preceded by a 2-byte header (bLength, bDescriptorType).
52    ///
53    /// `f` receives a mutable slice of up to 254 bytes (max descriptor body size)
54    /// and should write the descriptor body, returning the body length.
55    pub fn write_with(
56        &mut self,
57        descriptor_type: u8,
58        f: impl FnOnce(&mut [u8]) -> UsbResult<usize>,
59    ) -> UsbResult<()> {
60        if self.pos + 2 > self.buf.len() {
61            return Err(UsbError::BufferOverflow);
62        }
63        let body_start = self.pos + 2;
64        let body_end = self.buf.len().min(body_start + 254);
65        let body_len = f(&mut self.buf[body_start..body_end])?;
66        let total_len = body_len + 2;
67        if self.pos + total_len > self.buf.len() {
68            return Err(UsbError::BufferOverflow);
69        }
70        self.buf[self.pos] = total_len as u8;
71        self.buf[self.pos + 1] = descriptor_type;
72        self.pos += total_len;
73        Ok(())
74    }
75
76    /// Append a descriptor with a fixed body slice.
77    pub fn write(&mut self, descriptor_type: u8, body: &[u8]) -> UsbResult<()> {
78        self.write_with(descriptor_type, |buf| {
79            if body.len() > buf.len() {
80                return Err(UsbError::BufferOverflow);
81            }
82            buf[..body.len()].copy_from_slice(body);
83            Ok(body.len())
84        })
85    }
86
87    // ── Configuration descriptor ─────────────────────────────────────────────
88
89    /// Begin a configuration descriptor.  Must be paired with
90    /// [`end_configuration`](Self::end_configuration).
91    pub fn configuration(&mut self, attributes: u8, max_power_ma: u8) -> UsbResult<()> {
92        self.config_total_len_pos = Some(self.pos + 2); // offset of wTotalLength[0]
93        self.config_num_ifaces_pos = Some(self.pos + 4); // offset of bNumInterfaces
94        self.num_interfaces = 0;
95        self.write(
96            descriptor_type::CONFIGURATION,
97            &[
98                0,
99                0, // wTotalLength — patched later
100                0, // bNumInterfaces — patched later
101                1, // bConfigurationValue
102                0, // iConfiguration
103                attributes,
104                max_power_ma,
105            ],
106        )
107    }
108
109    /// Finalise the open configuration descriptor (patch wTotalLength and
110    /// bNumInterfaces).
111    pub fn end_configuration(&mut self) {
112        if let (Some(tl_pos), Some(ni_pos)) =
113            (self.config_total_len_pos, self.config_num_ifaces_pos)
114        {
115            let total = self.pos as u16;
116            self.buf[tl_pos] = total as u8;
117            self.buf[tl_pos + 1] = (total >> 8) as u8;
118            self.buf[ni_pos] = self.num_interfaces;
119        }
120        self.config_total_len_pos = None;
121        self.config_num_ifaces_pos = None;
122    }
123
124    // ── Interface & endpoint ─────────────────────────────────────────────────
125
126    /// Write an Interface Association Descriptor (IAD), if the configuration was
127    /// built with `composite_with_iads = true`.
128    ///
129    /// Always safe to call — if the outer device was not configured for IADs the
130    /// call is a no-op.
131    pub fn iad(
132        &mut self,
133        first_interface: InterfaceNumber,
134        interface_count: u8,
135        function_class: u8,
136        function_subclass: u8,
137        function_protocol: u8,
138    ) -> UsbResult<()> {
139        self.write(
140            descriptor_type::IAD,
141            &[
142                first_interface.into(),
143                interface_count,
144                function_class,
145                function_subclass,
146                function_protocol,
147                0, // iFunction
148            ],
149        )
150    }
151
152    /// Write an Interface descriptor and increment the interface count.
153    pub fn interface(
154        &mut self,
155        number: InterfaceNumber,
156        num_endpoints: u8,
157        class: u8,
158        subclass: u8,
159        protocol: u8,
160    ) -> UsbResult<()> {
161        self.interface_with_string(
162            number,
163            num_endpoints,
164            class,
165            subclass,
166            protocol,
167            StringIndex::new(0),
168        )
169    }
170
171    /// Write an Interface descriptor with a string index.
172    pub fn interface_with_string(
173        &mut self,
174        number: InterfaceNumber,
175        num_endpoints: u8,
176        class: u8,
177        subclass: u8,
178        protocol: u8,
179        string: StringIndex,
180    ) -> UsbResult<()> {
181        self.num_interfaces += 1;
182        self.write(
183            descriptor_type::INTERFACE,
184            &[
185                number.into(),
186                0, // bAlternateSetting
187                num_endpoints,
188                class,
189                subclass,
190                protocol,
191                string.into(),
192            ],
193        )
194    }
195
196    /// Write an Interface descriptor with a non-zero alternate setting.
197    ///
198    /// Does **not** increment `bNumInterfaces` — alternate settings share the
199    /// same interface number and are not counted separately.
200    pub fn interface_alt(
201        &mut self,
202        number: InterfaceNumber,
203        alternate_setting: u8,
204        num_endpoints: u8,
205        class: u8,
206        subclass: u8,
207        protocol: u8,
208    ) -> UsbResult<()> {
209        self.write(
210            descriptor_type::INTERFACE,
211            &[
212                number.into(),
213                alternate_setting,
214                num_endpoints,
215                class,
216                subclass,
217                protocol,
218                0, // iInterface
219            ],
220        )
221    }
222
223    /// Write an Endpoint descriptor.
224    pub fn endpoint(
225        &mut self,
226        addr: EndpointAddress,
227        ep_type: EndpointType,
228        max_packet_size: u16,
229        interval: u8,
230    ) -> UsbResult<()> {
231        self.write(
232            descriptor_type::ENDPOINT,
233            &[
234                addr.raw(),
235                ep_type.bm_attributes(),
236                max_packet_size as u8,
237                (max_packet_size >> 8) as u8,
238                interval,
239            ],
240        )
241    }
242
243    // ── String descriptors ───────────────────────────────────────────────────
244
245    /// Encode a UTF-8 string as a USB string descriptor (UTF-16LE with header)
246    /// and write it into `buf`.  Returns the number of bytes written.
247    ///
248    /// Call this from the device layer when responding to GET_DESCRIPTOR(String).
249    pub fn write_string(buf: &mut [u8], s: &str) -> UsbResult<usize> {
250        if buf.len() < 2 {
251            return Err(UsbError::BufferOverflow);
252        }
253        let max_chars = (buf.len() - 2) / 2;
254        let mut n = 0usize;
255        for c in s.chars().take(max_chars) {
256            // Non-BMP code points are replaced with U+FFFD (replacement char).
257            let unit = if (c as u32) <= 0xFFFF {
258                c as u16
259            } else {
260                0xFFFD
261            };
262            buf[2 + n * 2] = unit as u8;
263            buf[3 + n * 2] = (unit >> 8) as u8;
264            n += 1;
265        }
266        let total = 2 + n * 2;
267        buf[0] = total as u8;
268        buf[1] = descriptor_type::STRING;
269        Ok(total)
270    }
271
272    /// Write the language ID list descriptor (index 0) into `buf`.
273    pub fn write_lang_ids(buf: &mut [u8], lang_ids: &[u16]) -> UsbResult<usize> {
274        let total = 2 + lang_ids.len() * 2;
275        if total > buf.len() {
276            return Err(UsbError::BufferOverflow);
277        }
278        buf[0] = total as u8;
279        buf[1] = descriptor_type::STRING;
280        for (i, &id) in lang_ids.iter().enumerate() {
281            buf[2 + i * 2] = id as u8;
282            buf[2 + i * 2 + 1] = (id >> 8) as u8;
283        }
284        Ok(total)
285    }
286}