use crate::error::{DecoderError, EncoderError};
pub(crate) const COUNT_BOUNDARY: usize = 4;
pub const fn max_boundary(boundaries: &[usize]) -> usize {
let mut max = 1;
let mut index = 0;
while index < boundaries.len() {
if boundaries[index] > max {
max = boundaries[index];
}
index += 1;
}
max
}
pub const fn padding_for(offset: usize, boundary: usize) -> usize {
if boundary <= 1 { 0 } else { (boundary - offset % boundary) % boundary }
}
#[derive(Debug)]
pub struct ByteWriter<'a> {
buffer: Option<&'a mut Vec<u8>>,
position: usize,
error: Option<EncoderError>,
}
impl<'a> ByteWriter<'a> {
pub fn new(buffer: &'a mut Vec<u8>) -> Self {
Self { buffer: Some(buffer), position: 0, error: None }
}
pub fn counter() -> ByteWriter<'static> {
ByteWriter { buffer: None, position: 0, error: None }
}
pub fn position(&self) -> usize {
self.position
}
pub fn align(&mut self, boundary: usize) {
let padding = padding_for(self.position, boundary);
if padding > 0 {
if let Some(buffer) = self.buffer.as_deref_mut() {
buffer.resize(buffer.len() + padding, 0);
}
self.position += padding;
}
}
pub fn put_u8(&mut self, octet: u8) {
self.put_slice(&[octet]);
}
pub fn put_slice(&mut self, octets: &[u8]) {
if let Some(buffer) = self.buffer.as_deref_mut() {
buffer.extend_from_slice(octets);
}
self.position += octets.len();
}
pub fn put_count(&mut self, count: usize) {
let encoded = match i32::try_from(count) {
Ok(value) => value,
Err(_) => {
self.fail(EncoderError::TooManyElements { count });
i32::MAX
}
};
self.put_slice(&encoded.to_be_bytes());
}
pub fn fail(&mut self, error: EncoderError) {
self.error.get_or_insert(error);
}
pub fn status(&self) -> Result<(), EncoderError> {
match &self.error {
Some(error) => Err(error.clone()),
None => Ok(()),
}
}
}
#[derive(Debug, Clone)]
pub struct ByteReader<'a> {
data: &'a [u8],
position: usize,
}
impl<'a> ByteReader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self { data, position: 0 }
}
pub fn position(&self) -> usize {
self.position
}
pub fn remaining(&self) -> usize {
self.data.len() - self.position
}
pub fn is_empty(&self) -> bool {
self.remaining() == 0
}
pub fn align(&mut self, boundary: usize) -> Result<(), DecoderError> {
self.take(padding_for(self.position, boundary)).map(|_| ())
}
pub fn take(&mut self, len: usize) -> Result<&'a [u8], DecoderError> {
let remaining = self.remaining();
if len > remaining {
return Err(DecoderError::Truncated { offset: self.position, needed: len, remaining });
}
let start = self.position;
self.position += len;
Ok(&self.data[start..self.position])
}
pub fn take_array<const N: usize>(&mut self) -> Result<[u8; N], DecoderError> {
let mut octets = [0u8; N];
octets.copy_from_slice(self.take(N)?);
Ok(octets)
}
pub fn read_u8(&mut self) -> Result<u8, DecoderError> {
let [octet] = self.take_array::<1>()?;
Ok(octet)
}
pub fn read_count(&mut self) -> Result<usize, DecoderError> {
let raw = i32::from_be_bytes(self.take_array()?);
let count = usize::try_from(raw).map_err(|_| DecoderError::InvalidCount { count: raw })?;
let remaining = self.remaining();
if count > remaining {
return Err(DecoderError::CountExceedsInput { count, remaining });
}
Ok(count)
}
pub fn window(&mut self, len: usize) -> Result<ByteReader<'a>, DecoderError> {
let remaining = self.remaining();
if len > remaining {
return Err(DecoderError::Truncated { offset: self.position, needed: len, remaining });
}
let start = self.position;
self.position += len;
Ok(ByteReader { data: &self.data[..self.position], position: start })
}
pub fn expect_end(&self) -> Result<(), DecoderError> {
match self.remaining() {
0 => Ok(()),
count => Err(DecoderError::TrailingBytes { count }),
}
}
}