microrti-encoding 0.1.1

HLA data encoding helpers of IEEE 1516-2025: basic types, strings, handles, arrays, records and variant records.
Documentation
//! Wire layout of `HLAextendableVariantRecord`, the variant record encoding introduced in 2025 so that
//! FOM modules can add alternatives to an existing datatype.
//!
//! **This layout is an assumption.** IEEE 1516.2-2025, which defines it, was not available when this
//! crate was written. The API files and public descriptions only establish the intent: the encoding
//! states the alignment and the length of the alternative explicitly, so that a receiver can skip an
//! alternative it does not know, and adding an alternative never moves the neighbours of the record.
//! Everything that depends on the exact layout lives in this module; the dynamic container and the
//! `hla_extendable_variant_record!` macro only call these functions.
//!
//! Assumed layout, offsets counted from the start of the outermost value:
//!
//! | Part | Rule |
//! | --- | --- |
//! | record | starts at a multiple of [`OCTET_BOUNDARY`] (8, whatever the alternatives are) |
//! | discriminant | its own encoding |
//! | padding | to a multiple of [`LENGTH_BOUNDARY`] (4) |
//! | length | `HLAunsignedInteger32BE`: octets of the alternative, 0 when the alternative has no data |
//! | padding | to a multiple of [`ALTERNATIVE_BOUNDARY`] (8), only when the length is not 0 |
//! | alternative | its own encoding, exactly `length` octets |

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

/// Octet boundary of every `HLAextendableVariantRecord`, independent of its alternatives.
pub const OCTET_BOUNDARY: usize = 8;
/// Octet boundary of the length field.
pub const LENGTH_BOUNDARY: usize = 4;
/// Octet boundary at which the alternative starts.
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 length field after the discriminant and aligns for the alternative. The caller then
/// encodes the alternative, which must take exactly `alternative_len` octets.
pub fn write_length(writer: &mut ByteWriter<'_>, alternative_len: usize) {
    writer.align(LENGTH_BOUNDARY);
    let length = match u32::try_from(alternative_len) {
        Ok(length) => length,
        Err(_) => {
            writer.fail(EncoderError::AlternativeTooLong { length: alternative_len });
            u32::MAX
        }
    };
    writer.put_slice(&length.to_be_bytes());
    if alternative_len > 0 {
        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 length field after the discriminant and delimits the alternative.
pub fn read_alternative<'a>(reader: &mut ByteReader<'a>) -> Result<Alternative<'a>, DecoderError> {
    reader.align(LENGTH_BOUNDARY)?;
    let length = usize::try_from(u32::from_be_bytes(reader.take_array()?)).unwrap_or(usize::MAX);
    if length > 0 {
        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()
    }
}