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
//! Wire layout of `HLAextendableVariantRecord` (IEEE 1516.2-2025 4.14.10.3), the variant record encoding
//! that lets FOM modules add alternatives to an existing data type (4.14.8, annex C): the length of the
//! alternative travels with it, so a receiver can skip an alternative it does not know, and adding one
//! never moves the neighbours of the record. The dynamic container, the
//! `hla_extendable_variant_record!` macro and the FOM-driven codec all use the functions of this module.
//!
//! Layout, offsets counted from the start of the outermost value (each record starts at a multiple of 8,
//! so these are the offsets the clause counts from the start of the record):
//!
//! | Part | Rule |
//! | --- | --- |
//! | record | octet boundary [`OCTET_BOUNDARY`]: the alternatives count as 8, whatever they are |
//! | discriminant | at offset 0, its own encoding |
//! | padding | to a multiple of [`LENGTH_BOUNDARY`] (4), equation (3) |
//! | encoded_length | `HLAinteger32BE`: octets of the alternative without padding; 0 when no alternative applies |
//! | padding | to a multiple of [`ALTERNATIVE_BOUNDARY`] (8), equation (4) |
//! | alternative | its own encoding, exactly encoded_length octets; nothing after it |
//!
//! The padding before the alternative is written whatever the length, also when no alternative applies:
//! equation (4) computes it from the sizes of the discriminant and of the length field only, not from
//! the presence of an alternative. The words "if required" around it allow another reading, padding
//! only when an alternative follows (a receiver could apply that rule too, from the length); the two
//! differ only for a discriminant of more than four octets (64 bits) and a length of 0, since after a
//! smaller discriminant the length field ends at offset 8. MicroRTI 0.1.2 followed that other reading.
//!
//! When decoding, a length of 0 followed by fewer octets than that padding takes the 0.1.2 form: the
//! padded form cannot be complete there. When more octets follow, they are read as padding: they could
//! also be the next component of a 0.1.2 value, and nothing tells the two apart, padding content being
//! ignored.
//!
//! Alternatives whose octet boundary exceeds 8 cannot use this encoding (4.14.10.3).

use crate::buffer::{ByteReader, ByteWriter, padding_for};
use crate::error::{DecoderError, EncoderError};

/// Octet boundary of every `HLAextendableVariantRecord`, independent of its alternatives (4.14.10.3).
pub const OCTET_BOUNDARY: usize = 8;
/// Octet boundary of the encoded_length field, an `HLAinteger32BE`.
pub const LENGTH_BOUNDARY: usize = 4;
/// Octet boundary at which the alternative starts, and the largest one an alternative may have.
pub const ALTERNATIVE_BOUNDARY: usize = 8;

/// Aligns the writer for a record. The caller encodes the discriminant next.
pub fn begin_encode(writer: &mut ByteWriter<'_>) {
    writer.align(OCTET_BOUNDARY);
}

/// Writes the encoded_length field after the discriminant and the padding that follows it. The caller
/// then encodes the alternative, which must take exactly `alternative_len` octets.
///
/// A length above `i32::MAX`, which the `HLAinteger32BE` field cannot hold, records
/// [`EncoderError::AlternativeTooLong`].
pub fn write_length(writer: &mut ByteWriter<'_>, alternative_len: usize) {
    writer.align(LENGTH_BOUNDARY);
    let length = match i32::try_from(alternative_len) {
        Ok(length) => length,
        Err(_) => {
            writer.fail(EncoderError::AlternativeTooLong { length: alternative_len });
            i32::MAX
        }
    };
    writer.put_slice(&length.to_be_bytes());
    writer.align(ALTERNATIVE_BOUNDARY);
}

/// Aligns the reader for a record. The caller decodes the discriminant next.
pub fn begin_decode(reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
    reader.align(OCTET_BOUNDARY)
}

/// Reads the encoded_length field after the discriminant, skips the padding that follows it and delimits
/// the alternative. A negative length is [`DecoderError::InvalidValue`].
///
/// A length of 0 followed by fewer octets than the padding is read without padding (the form MicroRTI
/// 0.1.2 wrote); see the module documentation.
pub fn read_alternative<'a>(reader: &mut ByteReader<'a>) -> Result<Alternative<'a>, DecoderError> {
    reader.align(LENGTH_BOUNDARY)?;
    let raw = i32::from_be_bytes(reader.take_array()?);
    let length = usize::try_from(raw).map_err(|_| DecoderError::InvalidValue {
        type_name: "HLAextendableVariantRecord",
        detail: format!("negative encoded_length {raw}"),
    })?;
    let unpadded = length == 0 && reader.remaining() < padding_for(reader.position(), ALTERNATIVE_BOUNDARY);
    if !unpadded {
        reader.align(ALTERNATIVE_BOUNDARY)?;
    }
    Ok(Alternative { reader: reader.window(length)?, length })
}

/// The octets of one alternative, as delimited by the length field.
#[derive(Debug, Clone)]
pub struct Alternative<'a> {
    reader: ByteReader<'a>,
    length: usize,
}

impl<'a> Alternative<'a> {
    /// Announced length of the alternative in octets.
    pub fn len(&self) -> usize {
        self.length
    }

    /// True when the alternative carries no data.
    pub fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Reader limited to the alternative; decode the alternative datatype from it.
    pub fn reader(&mut self) -> &mut ByteReader<'a> {
        &mut self.reader
    }

    /// Checks that the alternative datatype used exactly the announced length.
    pub fn finish(self) -> Result<(), DecoderError> {
        match self.reader.remaining() {
            0 => Ok(()),
            unused => {
                Err(DecoderError::LengthMismatch { declared: self.length, consumed: self.length - unused })
            }
        }
    }

    /// The octets not consumed so far; the whole alternative when it is skipped.
    pub fn into_bytes(mut self) -> Vec<u8> {
        let rest = self.reader.remaining();
        self.reader.take(rest).map(<[u8]>::to_vec).unwrap_or_default()
    }
}