microrti-encoding 0.2.1

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! The dynamic layer: [`DataElement`], the object-safe counterpart of `DataElement` in the standard APIs.

use std::any::{Any, TypeId};
use std::fmt;

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

/// A data element behind a pointer, with the `'static` bound every element has anyway.
pub type DynElement = dyn DataElement;

/// A value that knows its HLA encoding at run time.
///
/// Every typed value ([`Decode`] + `Clone` + `Debug`) is a data element, and so are the dynamic containers
/// (`HLAfixedRecord`, `HLAvariableArray`...), which hold boxed data elements and can therefore describe
/// datatypes that are only known at run time, for example from a FOM.
///
/// Elements align themselves: [`DataElement::encode_into`] and [`DataElement::decode_from`] first move to
/// the next multiple of the element's octet boundary, counted from the start of the outermost value.
pub trait DataElement: Any + fmt::Debug + Send + Sync {
    /// Octet boundary of this element.
    fn octet_boundary(&self) -> usize;

    /// Appends the padding this element needs and its encoding.
    fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError>;

    /// Skips the padding this element needs and replaces its value by the decoded one.
    ///
    /// After an error the element holds an unspecified but valid value. Never panics.
    fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError>;

    /// A boxed copy of this element.
    fn clone_element(&self) -> Box<DynElement>;

    /// Length in octets of the encoding when it starts at an aligned offset.
    fn encoded_length(&self) -> Result<usize, EncoderError> {
        let mut counter = ByteWriter::counter();
        self.encode_into(&mut counter)?;
        counter.status()?;
        Ok(counter.position())
    }

    /// True if `other` has the same datatype: the same Rust type and, for dynamic containers, the same
    /// structure.
    fn is_same_type_as(&self, other: &DynElement) -> bool {
        self.element_type_id() == other.element_type_id()
    }

    /// Identity of the implementing Rust type.
    #[doc(hidden)]
    fn element_type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    /// Encodes this element as an outermost value.
    fn to_bytes(&self) -> Result<Vec<u8>, EncoderError> {
        let mut buffer = Vec::new();
        self.append_to(&mut buffer)?;
        Ok(buffer)
    }

    /// Appends the encoding to `buffer` as a new outermost value: padding is computed from the first
    /// appended octet. On error `buffer` is left unchanged.
    fn append_to(&self, buffer: &mut Vec<u8>) -> Result<(), EncoderError> {
        let start = buffer.len();
        let mut writer = ByteWriter::new(buffer);
        let result = self.encode_into(&mut writer).and_then(|()| writer.status());
        if result.is_err() {
            buffer.truncate(start);
        }
        result
    }

    /// Decodes this element from the start of `bytes`; octets after the value are ignored.
    fn decode_slice(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
        self.decode_from(&mut ByteReader::new(bytes))
    }

    /// Decodes this element from `bytes`, which must hold exactly one value.
    fn decode_slice_strict(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
        let mut reader = ByteReader::new(bytes);
        self.decode_from(&mut reader)?;
        reader.expect_end()
    }
}

impl<T> DataElement for T
where
    T: Decode + Clone + fmt::Debug + Send + Sync + 'static,
{
    fn octet_boundary(&self) -> usize {
        <T as Encode>::OCTET_BOUNDARY
    }

    fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
        Encode::encode(self, writer);
        writer.status()
    }

    fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
        *self = T::decode(reader)?;
        Ok(())
    }

    fn clone_element(&self) -> Box<DynElement> {
        Box::new(self.clone())
    }
}

impl dyn DataElement {
    /// True if the element is a `T`.
    pub fn is<T: DataElement>(&self) -> bool {
        let any: &dyn Any = self;
        any.is::<T>()
    }

    /// The element as a `T`, if it is one.
    pub fn downcast_ref<T: DataElement>(&self) -> Option<&T> {
        let any: &dyn Any = self;
        any.downcast_ref::<T>()
    }

    /// The element as a mutable `T`, if it is one.
    pub fn downcast_mut<T: DataElement>(&mut self) -> Option<&mut T> {
        let any: &mut dyn Any = self;
        any.downcast_mut::<T>()
    }
}

impl Clone for Box<DynElement> {
    fn clone(&self) -> Self {
        (**self).clone_element()
    }
}

/// Two elements are equal when they have the same datatype and the same encoding. An element that cannot
/// be encoded (a variant record without a variant for its discriminant) equals nothing.
impl PartialEq for dyn DataElement {
    fn eq(&self, other: &Self) -> bool {
        self.is_same_type_as(other)
            && matches!((self.to_bytes(), other.to_bytes()), (Ok(left), Ok(right)) if left == right)
    }
}