pub const DESCRIPTOR_HEADER_LEN: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DescriptorEntry<'a> {
pub tag: u8,
pub body: &'a [u8],
pub raw: &'a [u8],
}
pub fn frame_at(bytes: &[u8], offset: usize) -> crate::Result<DescriptorEntry<'_>> {
let Some(rem) = bytes.get(offset..) else {
return Err(crate::Error::DescriptorHeaderTruncated {
offset,
need: DESCRIPTOR_HEADER_LEN,
have: 0,
});
};
if rem.len() < DESCRIPTOR_HEADER_LEN {
return Err(crate::Error::DescriptorHeaderTruncated {
offset,
need: DESCRIPTOR_HEADER_LEN,
have: rem.len(),
});
}
let tag = rem[0];
let len = usize::from(rem[1]);
let total = DESCRIPTOR_HEADER_LEN + len;
if rem.len() < total {
return Err(crate::Error::DescriptorBodyTruncated {
offset,
tag,
declared: len,
have: rem.len() - DESCRIPTOR_HEADER_LEN,
});
}
Ok(DescriptorEntry {
tag,
body: &rem[DESCRIPTOR_HEADER_LEN..total],
raw: &rem[..total],
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RawDescriptorLoop<'a>(&'a [u8]);
impl<'a> RawDescriptorLoop<'a> {
#[must_use]
pub const fn new(raw: &'a [u8]) -> Self {
Self(raw)
}
#[must_use]
pub const fn raw(&self) -> &'a [u8] {
self.0
}
pub fn entries(&self) -> DescriptorEntryIter<'a> {
DescriptorEntryIter {
bytes: self.0,
pos: 0,
fused: false,
}
}
pub fn tags(&self) -> impl Iterator<Item = u8> + 'a {
let bytes = self.0;
let mut pos = 0usize;
core::iter::from_fn(move || {
let tag = *bytes.get(pos)?;
pos = match bytes.get(pos + 1) {
Some(&len) => pos + DESCRIPTOR_HEADER_LEN + usize::from(len),
None => bytes.len(),
};
Some(tag)
})
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
pub fn parse_with<T>(
&self,
parse: impl FnMut(u8, &'a [u8]) -> T,
) -> ParseWith<'a, impl FnMut(u8, &'a [u8]) -> T, T> {
ParseWith {
inner: self.entries(),
parse,
out: core::marker::PhantomData,
}
}
}
impl<'a> From<&'a [u8]> for RawDescriptorLoop<'a> {
fn from(raw: &'a [u8]) -> Self {
Self(raw)
}
}
impl core::ops::Deref for RawDescriptorLoop<'_> {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.0
}
}
impl<'a> IntoIterator for &RawDescriptorLoop<'a> {
type Item = crate::Result<DescriptorEntry<'a>>;
type IntoIter = DescriptorEntryIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.entries()
}
}
pub struct ParseWith<'a, F, T> {
inner: DescriptorEntryIter<'a>,
parse: F,
out: core::marker::PhantomData<fn(&'a [u8]) -> T>,
}
impl<'a, F, T> Iterator for ParseWith<'a, F, T>
where
F: FnMut(u8, &'a [u8]) -> T,
{
type Item = crate::Result<T>;
fn next(&mut self) -> Option<Self::Item> {
let entry = self.inner.next()?;
Some(entry.map(|e| (self.parse)(e.tag, e.body)))
}
}
#[derive(Debug, Clone)]
pub struct DescriptorEntryIter<'a> {
bytes: &'a [u8],
pos: usize,
fused: bool,
}
impl<'a> Iterator for DescriptorEntryIter<'a> {
type Item = crate::Result<DescriptorEntry<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.fused || self.pos >= self.bytes.len() {
return None;
}
let entry = frame_at(self.bytes, self.pos);
match &entry {
Ok(e) => self.pos += e.raw.len(),
Err(_) => self.fused = true,
}
Some(entry)
}
}
impl core::iter::FusedIterator for DescriptorEntryIter<'_> {}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use super::*;
#[test]
fn an_empty_loop_has_no_entries() {
let loop_ = RawDescriptorLoop::new(&[]);
assert!(loop_.is_empty());
assert_eq!(loop_.entries().count(), 0);
}
#[test]
fn entries_carry_tag_and_body_verbatim() {
let raw = [0x05, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
let loop_ = RawDescriptorLoop::new(&raw);
let entries: Vec<_> = loop_.entries().map(|e| e.unwrap()).collect();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].tag, 0x05);
assert_eq!(entries[0].body, b"HDMV");
assert_eq!(entries[1].tag, 0xC0);
assert_eq!(entries[1].body, &[0x7F]);
assert_eq!(loop_.raw(), &raw[..]);
}
#[test]
fn a_truncated_header_is_reported_with_its_offset() {
let raw = [0x05, 0x01, 0x00, 0x06];
let err = RawDescriptorLoop::new(&raw)
.entries()
.last()
.unwrap()
.unwrap_err();
assert_eq!(
err,
crate::Error::DescriptorHeaderTruncated {
offset: 3,
need: DESCRIPTOR_HEADER_LEN,
have: 1,
}
);
}
#[test]
fn a_body_running_past_the_loop_is_reported_not_shortened() {
let raw = [0x05, 0x06, b'H', b'D'];
let err = RawDescriptorLoop::new(&raw)
.entries()
.last()
.unwrap()
.unwrap_err();
assert_eq!(
err,
crate::Error::DescriptorBodyTruncated {
offset: 0,
tag: 0x05,
declared: 6,
have: 2,
}
);
}
#[test]
fn a_trailing_zero_length_descriptor_is_an_entry() {
let raw = [0x05u8, 0x00];
let entries: Vec<_> = RawDescriptorLoop::new(&raw)
.entries()
.map(|e| e.unwrap())
.collect();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].tag, 0x05);
assert!(entries[0].body.is_empty());
}
#[test]
fn entries_tell_a_lone_tag_byte_from_a_truncated_body() {
let lone = [0x05u8, 0x00, 0x6A];
let last = RawDescriptorLoop::new(&lone).entries().last().unwrap();
assert!(matches!(
last,
Err(crate::Error::DescriptorHeaderTruncated { offset: 2, .. })
));
let overrun = [0x05u8, 0x00, 0x6A, 0x04, 0x00];
let last = RawDescriptorLoop::new(&overrun).entries().last().unwrap();
assert!(matches!(
last,
Err(crate::Error::DescriptorBodyTruncated { tag: 0x6A, .. })
));
}
#[test]
fn tags_report_a_truncated_entry_and_stop_without_a_header() {
let raw = [0x05u8, 0x01, 0xAA, 0x6A, 0x09, 0x01];
assert_eq!(
RawDescriptorLoop::new(&raw).tags().collect::<Vec<_>>(),
[0x05, 0x6A]
);
let lone_tag = [0x05u8, 0x00, 0x7B];
assert_eq!(
RawDescriptorLoop::new(&lone_tag).tags().collect::<Vec<_>>(),
[0x05, 0x7B]
);
assert_eq!(RawDescriptorLoop::new(&[]).tags().count(), 0);
}
#[test]
fn from_bytes_keeps_the_loop_and_is_empty_tracks_it() {
let raw = [0x01u8, 0x00];
let loop_ = RawDescriptorLoop::from(&raw[..]);
assert!(!loop_.is_empty());
assert_eq!(loop_.raw(), &raw[..]);
assert_eq!(loop_.len(), 2);
assert_eq!(loop_.entries().count(), 1);
assert!(RawDescriptorLoop::from(&[][..]).is_empty());
}
#[test]
fn a_body_truncated_right_after_its_header_reports_no_body_bytes() {
let raw = [0x05u8, 0x03];
let err = RawDescriptorLoop::new(&raw)
.entries()
.last()
.unwrap()
.unwrap_err();
assert_eq!(
err,
crate::Error::DescriptorBodyTruncated {
offset: 0,
tag: 0x05,
declared: 3,
have: 0,
}
);
}
#[test]
fn an_offset_past_the_end_is_a_truncated_header_not_a_panic() {
for (len, offset) in [(0usize, 0usize), (0, 1), (3, 4), (3, usize::MAX)] {
let bytes = alloc::vec![0x05u8; len];
assert_eq!(
frame_at(&bytes, offset).unwrap_err(),
crate::Error::DescriptorHeaderTruncated {
offset,
need: DESCRIPTOR_HEADER_LEN,
have: 0,
}
);
}
}
#[test]
fn parse_with_hands_each_entry_its_own_classification() {
let raw = [0x05u8, 0x04, b'H', b'D', b'M', b'V', 0xC0, 0x01, 0x7F];
let kinds: Vec<_> = RawDescriptorLoop::new(&raw)
.parse_with(|tag, _| match tag {
0x05 => "registration",
0xC0 => "unknown",
_ => "other",
})
.map(|k| k.expect("framed loop"))
.collect();
assert_eq!(kinds, ["registration", "unknown"]);
let bodies: Vec<&[u8]> = RawDescriptorLoop::new(&raw)
.parse_with(|_, body| body)
.map(|b| b.expect("framed loop"))
.collect();
assert_eq!(bodies, [&b"HDMV"[..], &[0x7F][..]]);
}
}