use crate::error::{Error, Result};
pub const CUEI: u32 = 0x4355_4549;
pub const HEADER_LEN: usize = 6;
pub fn descriptor_body<'a>(
bytes: &'a [u8],
expected_tag: u8,
what: &'static str,
) -> Result<(u32, &'a [u8])> {
if bytes.len() < 2 {
return Err(Error::BufferTooShort {
need: 2,
have: bytes.len(),
what,
});
}
if bytes[0] != expected_tag {
return Err(Error::UnexpectedDescriptorTag {
tag: bytes[0],
what,
expected: expected_tag,
});
}
let declared = bytes[1] as usize; let total = 2 + declared;
if bytes.len() < total {
return Err(Error::LengthOverflow {
declared,
available: bytes.len().saturating_sub(2),
what,
});
}
if declared < 4 {
return Err(Error::BufferTooShort {
need: 6,
have: total,
what,
});
}
let (id_bytes, _) = bytes[2..total]
.split_first_chunk::<4>()
.ok_or(Error::BufferTooShort {
need: 6,
have: total,
what,
})?;
let identifier = u32::from_be_bytes(*id_bytes);
Ok((identifier, &bytes[HEADER_LEN..total]))
}
pub fn write_header(buf: &mut [u8], tag: u8, identifier: u32, body_len: usize) {
buf[0] = tag;
buf[1] = (4 + body_len) as u8;
buf[2..6].copy_from_slice(&identifier.to_be_bytes());
}