microrti-encoding 0.1.1

HLA data encoding helpers of IEEE 1516-2025: basic types, strings, handles, arrays, records and variant records.
Documentation
//! The typed layer: [`Encode`] / [`Decode`] for Rust types whose HLA datatype is known at compile time.

use std::marker::PhantomData;

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

/// A Rust type with a fixed HLA encoding.
///
/// Implementations align the writer to [`Encode::OCTET_BOUNDARY`] before writing, so containers only have
/// to encode their parts in order: the padding in front of each part is the padding the standard places
/// after the previous one, and nothing is ever written after the last part.
pub trait Encode {
    /// Octet boundary of the datatype: its encoding starts at a multiple of this offset.
    const OCTET_BOUNDARY: usize;

    /// Appends the encoding of `self`, preceded by the padding its octet boundary requires.
    fn encode(&self, writer: &mut ByteWriter<'_>);

    /// Length in octets of the encoding when it starts at an aligned offset.
    fn encoded_len(&self) -> usize {
        let mut counter = ByteWriter::counter();
        self.encode(&mut counter);
        counter.position()
    }
}

/// A Rust type that can be rebuilt from its HLA encoding.
pub trait Decode: Encode + Sized {
    /// Skips the padding the octet boundary requires and decodes one value.
    ///
    /// Never panics; never allocates more than a small multiple of the remaining input.
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError>;
}

/// An encoding marker: `Self` names the HLA datatype used to carry Rust values of type `V`.
///
/// Every [`Decode`] type represents itself. In addition the basic wrappers represent their native type
/// (`HLAinteger32BE` represents `i32`, `HLAunicodeString` represents `String`...), which lets the record
/// macros keep plain Rust field types: `count: i32 as HLAinteger32BE`.
pub trait Representation<V> {
    /// Octet boundary of the datatype.
    const BOUNDARY: usize;

    /// Encodes `value` as this datatype.
    fn encode_value(value: &V, writer: &mut ByteWriter<'_>);

    /// Decodes a value of this datatype.
    fn decode_value(reader: &mut ByteReader<'_>) -> Result<V, DecoderError>;

    /// Encoded length of `value` when it starts at an aligned offset.
    fn encoded_len_of(value: &V) -> usize {
        let mut counter = ByteWriter::counter();
        Self::encode_value(value, &mut counter);
        counter.position()
    }
}

impl<T: Decode> Representation<T> for T {
    const BOUNDARY: usize = <T as Encode>::OCTET_BOUNDARY;

    fn encode_value(value: &T, writer: &mut ByteWriter<'_>) {
        value.encode(writer);
    }

    fn decode_value(reader: &mut ByteReader<'_>) -> Result<T, DecoderError> {
        T::decode(reader)
    }

    fn encoded_len_of(value: &T) -> usize {
        value.encoded_len()
    }
}

/// A basic data representation wrapping one native Rust value (`HLAinteger32BE` wraps `i32`).
pub trait BasicData: Decode + Copy {
    /// The wrapped Rust type.
    type Native: Copy + PartialEq + std::fmt::Debug;

    /// Wraps a native value.
    fn from_native(value: Self::Native) -> Self;

    /// Unwraps the native value.
    fn to_native(self) -> Self::Native;
}

/// A datatype usable as the discriminant of a variant record: an enumerated datatype, or a basic
/// representation used directly.
///
/// The representation is what travels on the wire. `HLAextendableVariantRecord` decoders read it first so
/// that enumerators added by other FOM modules can be skipped instead of being an error.
pub trait Enumerated: Sized {
    /// Wire representation of the enumerators.
    type Representation: Decode + Clone + PartialEq + std::fmt::Debug;

    /// The wire value of this enumerator.
    fn to_representation(&self) -> Self::Representation;

    /// The enumerator with this wire value, if there is one.
    fn from_representation(representation: &Self::Representation) -> Option<Self>;
}

/// Upper bound, in octets of memory, for what a decoder reserves before it has seen the elements.
const PREALLOCATION_LIMIT: usize = 64 * 1024;

fn bounded_capacity<V>(count: usize) -> usize {
    count.min(PREALLOCATION_LIMIT / std::mem::size_of::<V>().max(1))
}

fn encode_variable<V>(
    items: &[V],
    boundary: usize,
    writer: &mut ByteWriter<'_>,
    encode: impl Fn(&V, &mut ByteWriter<'_>),
) {
    writer.align(boundary);
    writer.put_count(items.len());
    for item in items {
        encode(item, writer);
    }
}

fn decode_variable<V>(
    boundary: usize,
    reader: &mut ByteReader<'_>,
    decode: impl Fn(&mut ByteReader<'_>) -> Result<V, DecoderError>,
) -> Result<Vec<V>, DecoderError> {
    reader.align(boundary)?;
    let count = reader.read_count()?;
    let mut items = Vec::with_capacity(bounded_capacity::<V>(count));
    for _ in 0..count {
        items.push(decode(reader)?);
    }
    Ok(items)
}

fn encode_fixed<V>(
    items: &[V],
    boundary: usize,
    writer: &mut ByteWriter<'_>,
    encode: impl Fn(&V, &mut ByteWriter<'_>),
) {
    writer.align(boundary);
    for item in items {
        encode(item, writer);
    }
}

fn decode_fixed<V, const N: usize>(
    boundary: usize,
    reader: &mut ByteReader<'_>,
    decode: impl Fn(&mut ByteReader<'_>) -> Result<V, DecoderError>,
) -> Result<[V; N], DecoderError> {
    reader.align(boundary)?;
    let mut items = Vec::with_capacity(bounded_capacity::<V>(N));
    for _ in 0..N {
        items.push(decode(reader)?);
    }
    items.try_into().map_err(|rest: Vec<V>| DecoderError::CountMismatch {
        type_name: "HLAfixedArray",
        expected: N,
        found: rest.len(),
    })
}

/// `HLAvariableArray`: element count as `HLAinteger32BE`, then the elements, each at its own boundary.
/// An empty array is the count alone.
impl<T: Encode> Encode for [T] {
    const OCTET_BOUNDARY: usize = max_boundary(&[COUNT_BOUNDARY, T::OCTET_BOUNDARY]);

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_variable(self, <Self as Encode>::OCTET_BOUNDARY, writer, T::encode);
    }
}

/// `HLAvariableArray` of `T`.
impl<T: Encode> Encode for Vec<T> {
    const OCTET_BOUNDARY: usize = <[T] as Encode>::OCTET_BOUNDARY;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        self.as_slice().encode(writer);
    }
}

impl<T: Decode> Decode for Vec<T> {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        decode_variable(<Self as Encode>::OCTET_BOUNDARY, reader, T::decode)
    }
}

/// `HLAfixedArray` of `N` elements of `T`: the elements without a count.
impl<T: Encode, const N: usize> Encode for [T; N] {
    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        encode_fixed(self, T::OCTET_BOUNDARY, writer, T::encode);
    }
}

impl<T: Decode, const N: usize> Decode for [T; N] {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        decode_fixed(T::OCTET_BOUNDARY, reader, T::decode)
    }
}

impl<T: Encode + ?Sized> Encode for &T {
    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        (**self).encode(writer);
    }
}

impl<T: Encode + ?Sized> Encode for Box<T> {
    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;

    fn encode(&self, writer: &mut ByteWriter<'_>) {
        (**self).encode(writer);
    }
}

impl<T: Decode> Decode for Box<T> {
    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
        T::decode(reader).map(Box::new)
    }
}

/// Encoding marker for `Vec<V>` carried as an `HLAvariableArray` whose elements use the marker `R`.
///
/// `values: Vec<f64> as VariableArrayOf<HLAfloat64BE>` in a record macro. Never instantiated.
pub struct VariableArrayOf<R>(PhantomData<R>);

impl<V, R: Representation<V>> Representation<Vec<V>> for VariableArrayOf<R> {
    const BOUNDARY: usize = max_boundary(&[COUNT_BOUNDARY, <R as Representation<V>>::BOUNDARY]);

    fn encode_value(value: &Vec<V>, writer: &mut ByteWriter<'_>) {
        let boundary = <Self as Representation<Vec<V>>>::BOUNDARY;
        encode_variable(value, boundary, writer, <R as Representation<V>>::encode_value);
    }

    fn decode_value(reader: &mut ByteReader<'_>) -> Result<Vec<V>, DecoderError> {
        let boundary = <Self as Representation<Vec<V>>>::BOUNDARY;
        decode_variable(boundary, reader, <R as Representation<V>>::decode_value)
    }
}

/// Encoding marker for `[V; N]` carried as an `HLAfixedArray` whose elements use the marker `R`.
///
/// `position: [f64; 3] as FixedArrayOf<HLAfloat64BE>` in a record macro. Never instantiated.
pub struct FixedArrayOf<R>(PhantomData<R>);

impl<V, R: Representation<V>, const N: usize> Representation<[V; N]> for FixedArrayOf<R> {
    const BOUNDARY: usize = <R as Representation<V>>::BOUNDARY;

    fn encode_value(value: &[V; N], writer: &mut ByteWriter<'_>) {
        let boundary = <R as Representation<V>>::BOUNDARY;
        encode_fixed(value, boundary, writer, <R as Representation<V>>::encode_value);
    }

    fn decode_value(reader: &mut ByteReader<'_>) -> Result<[V; N], DecoderError> {
        let boundary = <R as Representation<V>>::BOUNDARY;
        decode_fixed(boundary, reader, <R as Representation<V>>::decode_value)
    }
}

/// Encodes `value` as an outermost value, reporting values that have no encoding.
///
/// The only typed values without an encoding are collections with more than `i32::MAX` elements and
/// `HLAextendableVariantRecord` alternatives longer than `u32::MAX` octets.
pub fn try_encode_to_vec<T: Encode + ?Sized>(value: &T) -> Result<Vec<u8>, EncoderError> {
    let mut buffer = Vec::new();
    encode_into(value, &mut buffer)?;
    Ok(buffer)
}

/// Encodes `value` as an outermost value.
///
/// # Panics
///
/// Panics if the value has no encoding, which takes a collection of more than `i32::MAX` elements (see
/// [`try_encode_to_vec`] for the non-panicking form).
pub fn encode_to_vec<T: Encode + ?Sized>(value: &T) -> Vec<u8> {
    match try_encode_to_vec(value) {
        Ok(buffer) => buffer,
        Err(error) => panic!("value has no HLA encoding: {error}"),
    }
}

/// Appends the encoding of `value` to `buffer` as a new outermost value: padding is computed from the
/// first appended octet, whatever `buffer` already holds. On error `buffer` is left unchanged.
pub fn encode_into<T: Encode + ?Sized>(value: &T, buffer: &mut Vec<u8>) -> Result<(), EncoderError> {
    let start = buffer.len();
    let mut writer = ByteWriter::new(buffer);
    value.encode(&mut writer);
    let status = writer.status();
    if status.is_err() {
        buffer.truncate(start);
    }
    status
}

/// Decodes one value from the start of `bytes` and returns it with the number of octets it used.
pub fn decode_prefix<T: Decode>(bytes: &[u8]) -> Result<(T, usize), DecoderError> {
    let mut reader = ByteReader::new(bytes);
    let value = T::decode(&mut reader)?;
    Ok((value, reader.position()))
}

/// Decodes one value from the start of `bytes`; octets after the value are ignored.
pub fn decode_from_slice<T: Decode>(bytes: &[u8]) -> Result<T, DecoderError> {
    decode_prefix(bytes).map(|(value, _)| value)
}

/// Decodes one value that must span `bytes` exactly: trailing octets are
/// [`DecoderError::TrailingBytes`].
pub fn decode_from_slice_strict<T: Decode>(bytes: &[u8]) -> Result<T, DecoderError> {
    let mut reader = ByteReader::new(bytes);
    let value = T::decode(&mut reader)?;
    reader.expect_end()?;
    Ok(value)
}

/// Support function of the record macros: the first length of the list, or zero.
#[doc(hidden)]
pub fn __first_or_zero(lengths: &[usize]) -> usize {
    lengths.first().copied().unwrap_or(0)
}