1pub const DESCRIPTOR_HEADER_LEN: usize = 2;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct DescriptorEntry<'a> {
19 pub tag: u8,
21 pub body: &'a [u8],
23 pub raw: &'a [u8],
25}
26
27pub fn frame_at(bytes: &[u8], offset: usize) -> crate::Result<DescriptorEntry<'_>> {
32 let Some(rem) = bytes.get(offset..) else {
33 return Err(crate::Error::DescriptorHeaderTruncated {
34 offset,
35 need: DESCRIPTOR_HEADER_LEN,
36 have: 0,
37 });
38 };
39 if rem.len() < DESCRIPTOR_HEADER_LEN {
40 return Err(crate::Error::DescriptorHeaderTruncated {
41 offset,
42 need: DESCRIPTOR_HEADER_LEN,
43 have: rem.len(),
44 });
45 }
46 let tag = rem[0];
47 let len = usize::from(rem[1]);
48 let total = DESCRIPTOR_HEADER_LEN + len;
49 if rem.len() < total {
50 return Err(crate::Error::DescriptorBodyTruncated {
51 offset,
52 tag,
53 declared: len,
54 have: rem.len() - DESCRIPTOR_HEADER_LEN,
55 });
56 }
57 Ok(DescriptorEntry {
58 tag,
59 body: &rem[DESCRIPTOR_HEADER_LEN..total],
60 raw: &rem[..total],
61 })
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67pub struct RawDescriptorLoop<'a>(&'a [u8]);
68
69impl<'a> RawDescriptorLoop<'a> {
70 #[must_use]
73 pub const fn new(raw: &'a [u8]) -> Self {
74 Self(raw)
75 }
76
77 #[must_use]
79 pub const fn raw(&self) -> &'a [u8] {
80 self.0
81 }
82
83 pub fn entries(&self) -> DescriptorEntryIter<'a> {
89 DescriptorEntryIter {
90 bytes: self.0,
91 pos: 0,
92 fused: false,
93 }
94 }
95
96 pub fn tags(&self) -> impl Iterator<Item = u8> + 'a {
101 let bytes = self.0;
102 let mut pos = 0usize;
103 core::iter::from_fn(move || {
104 let tag = *bytes.get(pos)?;
105 pos = match bytes.get(pos + 1) {
106 Some(&len) => pos + DESCRIPTOR_HEADER_LEN + usize::from(len),
107 None => bytes.len(),
108 };
109 Some(tag)
110 })
111 }
112
113 #[must_use]
115 pub fn is_empty(&self) -> bool {
116 self.0.is_empty()
117 }
118
119 #[must_use]
121 pub fn len(&self) -> usize {
122 self.0.len()
123 }
124
125 pub fn parse_with<T>(
135 &self,
136 parse: impl FnMut(u8, &'a [u8]) -> T,
137 ) -> ParseWith<'a, impl FnMut(u8, &'a [u8]) -> T, T> {
138 ParseWith {
139 inner: self.entries(),
140 parse,
141 out: core::marker::PhantomData,
142 }
143 }
144}
145
146impl<'a> From<&'a [u8]> for RawDescriptorLoop<'a> {
147 fn from(raw: &'a [u8]) -> Self {
148 Self(raw)
149 }
150}
151
152impl core::ops::Deref for RawDescriptorLoop<'_> {
153 type Target = [u8];
156 fn deref(&self) -> &[u8] {
157 self.0
158 }
159}
160
161impl<'a> IntoIterator for &RawDescriptorLoop<'a> {
162 type Item = crate::Result<DescriptorEntry<'a>>;
163 type IntoIter = DescriptorEntryIter<'a>;
164 fn into_iter(self) -> Self::IntoIter {
165 self.entries()
166 }
167}
168
169pub struct ParseWith<'a, F, T> {
172 inner: DescriptorEntryIter<'a>,
173 parse: F,
174 out: core::marker::PhantomData<fn(&'a [u8]) -> T>,
175}
176
177impl<'a, F, T> Iterator for ParseWith<'a, F, T>
178where
179 F: FnMut(u8, &'a [u8]) -> T,
180{
181 type Item = crate::Result<T>;
182
183 fn next(&mut self) -> Option<Self::Item> {
184 let entry = self.inner.next()?;
185 Some(entry.map(|e| (self.parse)(e.tag, e.body)))
186 }
187}
188
189#[derive(Debug, Clone)]
191pub struct DescriptorEntryIter<'a> {
192 bytes: &'a [u8],
193 pos: usize,
194 fused: bool,
195}
196
197impl<'a> Iterator for DescriptorEntryIter<'a> {
198 type Item = crate::Result<DescriptorEntry<'a>>;
199
200 fn next(&mut self) -> Option<Self::Item> {
201 if self.fused || self.pos >= self.bytes.len() {
202 return None;
203 }
204 let entry = frame_at(self.bytes, self.pos);
205 match &entry {
206 Ok(e) => self.pos += e.raw.len(),
207 Err(_) => self.fused = true,
208 }
209 Some(entry)
210 }
211}
212
213impl core::iter::FusedIterator for DescriptorEntryIter<'_> {}
214
215#[cfg(test)]
216mod tests {
217 use alloc::vec::Vec;
218
219 use super::*;
220
221 #[test]
222 fn an_empty_loop_has_no_entries() {
223 let loop_ = RawDescriptorLoop::new(&[]);
224 assert!(loop_.is_empty());
225 assert_eq!(loop_.entries().count(), 0);
226 }
227
228 #[test]
229 fn entries_carry_tag_and_body_verbatim() {
230 let raw = [0x05, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
232 let loop_ = RawDescriptorLoop::new(&raw);
233 let entries: Vec<_> = loop_.entries().map(|e| e.unwrap()).collect();
234 assert_eq!(entries.len(), 2);
235 assert_eq!(entries[0].tag, 0x05);
236 assert_eq!(entries[0].body, b"HDMV");
237 assert_eq!(entries[1].tag, 0xC0);
238 assert_eq!(entries[1].body, &[0x7F]);
239 assert_eq!(loop_.raw(), &raw[..]);
240 }
241
242 #[test]
243 fn a_truncated_header_is_reported_with_its_offset() {
244 let raw = [0x05, 0x01, 0x00, 0x06];
245 let err = RawDescriptorLoop::new(&raw)
246 .entries()
247 .last()
248 .unwrap()
249 .unwrap_err();
250 assert_eq!(
251 err,
252 crate::Error::DescriptorHeaderTruncated {
253 offset: 3,
254 need: DESCRIPTOR_HEADER_LEN,
255 have: 1,
256 }
257 );
258 }
259
260 #[test]
261 fn a_body_running_past_the_loop_is_reported_not_shortened() {
262 let raw = [0x05, 0x06, b'H', b'D'];
263 let err = RawDescriptorLoop::new(&raw)
264 .entries()
265 .last()
266 .unwrap()
267 .unwrap_err();
268 assert_eq!(
269 err,
270 crate::Error::DescriptorBodyTruncated {
271 offset: 0,
272 tag: 0x05,
273 declared: 6,
274 have: 2,
275 }
276 );
277 }
278
279 #[test]
280 fn a_trailing_zero_length_descriptor_is_an_entry() {
281 let raw = [0x05u8, 0x00];
282 let entries: Vec<_> = RawDescriptorLoop::new(&raw)
283 .entries()
284 .map(|e| e.unwrap())
285 .collect();
286 assert_eq!(entries.len(), 1);
287 assert_eq!(entries[0].tag, 0x05);
288 assert!(entries[0].body.is_empty());
289 }
290
291 #[test]
295 fn entries_tell_a_lone_tag_byte_from_a_truncated_body() {
296 let lone = [0x05u8, 0x00, 0x6A];
297 let last = RawDescriptorLoop::new(&lone).entries().last().unwrap();
298 assert!(matches!(
299 last,
300 Err(crate::Error::DescriptorHeaderTruncated { offset: 2, .. })
301 ));
302 let overrun = [0x05u8, 0x00, 0x6A, 0x04, 0x00];
303 let last = RawDescriptorLoop::new(&overrun).entries().last().unwrap();
304 assert!(matches!(
305 last,
306 Err(crate::Error::DescriptorBodyTruncated { tag: 0x6A, .. })
307 ));
308 }
309
310 #[test]
311 fn tags_report_a_truncated_entry_and_stop_without_a_header() {
312 let raw = [0x05u8, 0x01, 0xAA, 0x6A, 0x09, 0x01];
313 assert_eq!(
314 RawDescriptorLoop::new(&raw).tags().collect::<Vec<_>>(),
315 [0x05, 0x6A]
316 );
317 let lone_tag = [0x05u8, 0x00, 0x7B];
318 assert_eq!(
319 RawDescriptorLoop::new(&lone_tag).tags().collect::<Vec<_>>(),
320 [0x05, 0x7B]
321 );
322 assert_eq!(RawDescriptorLoop::new(&[]).tags().count(), 0);
323 }
324
325 #[test]
326 fn from_bytes_keeps_the_loop_and_is_empty_tracks_it() {
327 let raw = [0x01u8, 0x00];
328 let loop_ = RawDescriptorLoop::from(&raw[..]);
329 assert!(!loop_.is_empty());
330 assert_eq!(loop_.raw(), &raw[..]);
331 assert_eq!(loop_.len(), 2);
332 assert_eq!(loop_.entries().count(), 1);
333 assert!(RawDescriptorLoop::from(&[][..]).is_empty());
334 }
335
336 #[test]
337 fn a_body_truncated_right_after_its_header_reports_no_body_bytes() {
338 let raw = [0x05u8, 0x03];
339 let err = RawDescriptorLoop::new(&raw)
340 .entries()
341 .last()
342 .unwrap()
343 .unwrap_err();
344 assert_eq!(
345 err,
346 crate::Error::DescriptorBodyTruncated {
347 offset: 0,
348 tag: 0x05,
349 declared: 3,
350 have: 0,
351 }
352 );
353 }
354
355 #[test]
356 fn an_offset_past_the_end_is_a_truncated_header_not_a_panic() {
357 for (len, offset) in [(0usize, 0usize), (0, 1), (3, 4), (3, usize::MAX)] {
358 let bytes = alloc::vec![0x05u8; len];
359 assert_eq!(
360 frame_at(&bytes, offset).unwrap_err(),
361 crate::Error::DescriptorHeaderTruncated {
362 offset,
363 need: DESCRIPTOR_HEADER_LEN,
364 have: 0,
365 }
366 );
367 }
368 }
369
370 #[test]
371 fn parse_with_hands_each_entry_its_own_classification() {
372 let raw = [0x05u8, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
374 let kinds: Vec<_> = RawDescriptorLoop::new(&raw)
375 .parse_with(|tag, _| match tag {
376 0x05 => "registration",
377 0xC0 => "unknown",
378 _ => "other",
379 })
380 .map(|k| k.expect("framed loop"))
381 .collect();
382 assert_eq!(kinds, ["registration", "unknown"]);
383
384 let bodies: Vec<&[u8]> = RawDescriptorLoop::new(&raw)
385 .parse_with(|_, body| body)
386 .map(|b| b.expect("framed loop"))
387 .collect();
388 assert_eq!(bodies, [&b"HDMV"[..], &[0x7F][..]]);
389 }
390}