use crate::error::Error;
#[derive(Debug)]
pub(crate) struct Reader<'a> {
buf: &'a [u8],
pos: usize,
}
#[allow(dead_code)]
impl<'a> Reader<'a> {
pub(crate) fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0 }
}
pub(crate) fn at(buf: &'a [u8], start: usize) -> Result<Self, Error> {
if start > buf.len() {
return Err(Error::Truncated { what: "Reader::at" });
}
Ok(Self { buf, pos: start })
}
pub(crate) fn pos(&self) -> usize {
self.pos
}
pub(crate) fn remaining(&self) -> usize {
self.buf.len().saturating_sub(self.pos)
}
pub(crate) fn skip(&mut self, n: usize, what: &'static str) -> Result<(), Error> {
let new_pos = self.pos.checked_add(n).ok_or(Error::Overflow { what })?;
if new_pos > self.buf.len() {
return Err(Error::Truncated { what });
}
self.pos = new_pos;
Ok(())
}
pub(crate) fn take(&mut self, n: usize, what: &'static str) -> Result<&'a [u8], Error> {
let new_pos = self.pos.checked_add(n).ok_or(Error::Overflow { what })?;
let slice = self
.buf
.get(self.pos..new_pos)
.ok_or(Error::Truncated { what })?;
self.pos = new_pos;
Ok(slice)
}
pub(crate) fn array<const N: usize>(&mut self, what: &'static str) -> Result<[u8; N], Error> {
let bytes = self.take(N, what)?;
let mut out = [0u8; N];
out.copy_from_slice(bytes);
Ok(out)
}
pub(crate) fn u8(&mut self, what: &'static str) -> Result<u8, Error> {
let b = self
.buf
.get(self.pos)
.copied()
.ok_or(Error::Truncated { what })?;
self.pos = self.pos.saturating_add(1);
Ok(b)
}
pub(crate) fn u16_le(&mut self, what: &'static str) -> Result<u16, Error> {
Ok(u16::from_le_bytes(self.array::<2>(what)?))
}
pub(crate) fn u32_le(&mut self, what: &'static str) -> Result<u32, Error> {
Ok(u32::from_le_bytes(self.array::<4>(what)?))
}
pub(crate) fn i32_le(&mut self, what: &'static str) -> Result<i32, Error> {
Ok(i32::from_le_bytes(self.array::<4>(what)?))
}
pub(crate) fn u64_le(&mut self, what: &'static str) -> Result<u64, Error> {
Ok(u64::from_le_bytes(self.array::<8>(what)?))
}
pub(crate) fn i64_le(&mut self, what: &'static str) -> Result<i64, Error> {
Ok(i64::from_le_bytes(self.array::<8>(what)?))
}
pub(crate) fn set_bytes(
&mut self,
bit_count: usize,
pad_to_4: bool,
what: &'static str,
) -> Result<Vec<u8>, Error> {
let bytes_needed = bit_count
.checked_add(7)
.and_then(|n| n.checked_div(8))
.ok_or(Error::Overflow { what })?;
let primary = self.take(bytes_needed, what)?.to_vec();
if bytes_needed == 3 && pad_to_4 {
self.skip(1, what)?;
}
Ok(primary)
}
}
pub(crate) fn u32_le_at(buf: &[u8], offset: usize, what: &'static str) -> Result<u32, Error> {
let end = offset.checked_add(4).ok_or(Error::Overflow { what })?;
let bytes = buf.get(offset..end).ok_or(Error::Truncated { what })?;
let mut arr = [0u8; 4];
arr.copy_from_slice(bytes);
Ok(u32::from_le_bytes(arr))
}