microrti-encoding 0.2.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! Byte buffers used while encoding and decoding.
//!
//! Both sides track the offset from the start of the outermost value, because every padding rule of the
//! HLA encodings is expressed relative to that offset (the Java API does the same in `ByteWrapper.align`).

use crate::error::{DecoderError, EncoderError};

/// Octet boundary of the element count that starts every `HLAvariableArray`.
pub(crate) const COUNT_BOUNDARY: usize = 4;

/// Largest of the given octet boundaries, 1 for an empty list. Usable in constants.
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
}

/// Number of padding octets needed at `offset` to reach the next multiple of `boundary`.
pub const fn padding_for(offset: usize, boundary: usize) -> usize {
    if boundary <= 1 { 0 } else { (boundary - offset % boundary) % boundary }
}

/// Destination of an encoding.
///
/// A writer either appends to a `Vec<u8>` or only counts octets ([`ByteWriter::counter`]), which is how
/// encoded lengths are computed with the very same code that encodes.
///
/// Typed encoders cannot return errors; the rare failures (an array with more than `i32::MAX` elements)
/// are recorded with [`ByteWriter::fail`] and reported by [`ByteWriter::status`].
#[derive(Debug)]
pub struct ByteWriter<'a> {
    buffer: Option<&'a mut Vec<u8>>,
    position: usize,
    error: Option<EncoderError>,
}

impl<'a> ByteWriter<'a> {
    /// Starts a new outermost value at the current end of `buffer`.
    pub fn new(buffer: &'a mut Vec<u8>) -> Self {
        Self { buffer: Some(buffer), position: 0, error: None }
    }

    /// A writer that stores nothing and only counts the octets written.
    pub fn counter() -> ByteWriter<'static> {
        ByteWriter { buffer: None, position: 0, error: None }
    }

    /// Octets written since the start of the outermost value.
    pub fn position(&self) -> usize {
        self.position
    }

    /// Writes zero octets until the position is a multiple of `boundary`.
    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;
        }
    }

    /// Writes one octet.
    pub fn put_u8(&mut self, octet: u8) {
        self.put_slice(&[octet]);
    }

    /// Writes octets as they are.
    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();
    }

    /// Writes the element count of a variable array (`HLAinteger32BE`, no alignment is performed).
    ///
    /// A count above `i32::MAX` records [`EncoderError::TooManyElements`].
    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());
    }

    /// Records that the value being written cannot be encoded. The first error wins.
    pub fn fail(&mut self, error: EncoderError) {
        self.error.get_or_insert(error);
    }

    /// `Err` with the first recorded error, `Ok` if the encoding is sound so far.
    pub fn status(&self) -> Result<(), EncoderError> {
        match &self.error {
            Some(error) => Err(error.clone()),
            None => Ok(()),
        }
    }
}

/// Source of a decoding: a cursor over a byte slice.
///
/// Every read is bounds checked and returns [`DecoderError::Truncated`] instead of panicking.
#[derive(Debug, Clone)]
pub struct ByteReader<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> ByteReader<'a> {
    /// Starts decoding an outermost value at the beginning of `data`.
    pub fn new(data: &'a [u8]) -> Self {
        Self { data, position: 0 }
    }

    /// Octets consumed since the start of the outermost value.
    pub fn position(&self) -> usize {
        self.position
    }

    /// Octets left.
    pub fn remaining(&self) -> usize {
        self.data.len() - self.position
    }

    /// True when every octet has been consumed.
    pub fn is_empty(&self) -> bool {
        self.remaining() == 0
    }

    /// Skips padding octets until the position is a multiple of `boundary`, whatever they hold.
    ///
    /// IEEE 1516.2 4.14.10 requires zero padding from the sender (and [`ByteWriter::align`] writes
    /// zeros); it says nothing of a receiver that finds other octets there. They are ignored, so a value
    /// decodes the same whatever its padding holds.
    pub fn align(&mut self, boundary: usize) -> Result<(), DecoderError> {
        self.take(padding_for(self.position, boundary)).map(|_| ())
    }

    /// Consumes `len` octets.
    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])
    }

    /// Consumes exactly `N` octets.
    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)
    }

    /// Consumes one octet.
    pub fn read_u8(&mut self) -> Result<u8, DecoderError> {
        let [octet] = self.take_array::<1>()?;
        Ok(octet)
    }

    /// Reads the element count of a variable array (`HLAinteger32BE`, IEEE 1516.2 4.14.10.5; no alignment
    /// is performed).
    ///
    /// Negative counts are rejected, and so are counts larger than the number of octets left: an element
    /// of almost every datatype takes at least one octet, and refusing early keeps hostile counts from
    /// driving allocations. The price is a limit of this implementation, not of the standard: an array of
    /// zero-length elements (`HLAtoken`, empty fixed arrays) only decodes while its count does not exceed
    /// the octets that follow it.
    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)
    }

    /// Splits off the next `len` octets as a reader of their own. Offsets (and therefore padding) stay
    /// relative to the outermost value.
    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 })
    }

    /// Fails with [`DecoderError::TrailingBytes`] unless every octet has been consumed.
    pub fn expect_end(&self) -> Result<(), DecoderError> {
        match self.remaining() {
            0 => Ok(()),
            count => Err(DecoderError::TrailingBytes { count }),
        }
    }
}