Skip to main content

microrti_encoding/
element.rs

1//! The dynamic layer: [`DataElement`], the object-safe counterpart of `DataElement` in the standard APIs.
2
3use std::any::{Any, TypeId};
4use std::fmt;
5
6use crate::buffer::{ByteReader, ByteWriter};
7use crate::error::{DecoderError, EncoderError};
8use crate::typed::{Decode, Encode};
9
10/// A data element behind a pointer, with the `'static` bound every element has anyway.
11pub type DynElement = dyn DataElement;
12
13/// A value that knows its HLA encoding at run time.
14///
15/// Every typed value ([`Decode`] + `Clone` + `Debug`) is a data element, and so are the dynamic containers
16/// (`HLAfixedRecord`, `HLAvariableArray`...), which hold boxed data elements and can therefore describe
17/// datatypes that are only known at run time, for example from a FOM.
18///
19/// Elements align themselves: [`DataElement::encode_into`] and [`DataElement::decode_from`] first move to
20/// the next multiple of the element's octet boundary, counted from the start of the outermost value.
21pub trait DataElement: Any + fmt::Debug + Send + Sync {
22    /// Octet boundary of this element.
23    fn octet_boundary(&self) -> usize;
24
25    /// Appends the padding this element needs and its encoding.
26    fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError>;
27
28    /// Skips the padding this element needs and replaces its value by the decoded one.
29    ///
30    /// After an error the element holds an unspecified but valid value. Never panics.
31    fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError>;
32
33    /// A boxed copy of this element.
34    fn clone_element(&self) -> Box<DynElement>;
35
36    /// Length in octets of the encoding when it starts at an aligned offset.
37    fn encoded_length(&self) -> Result<usize, EncoderError> {
38        let mut counter = ByteWriter::counter();
39        self.encode_into(&mut counter)?;
40        counter.status()?;
41        Ok(counter.position())
42    }
43
44    /// True if `other` has the same datatype: the same Rust type and, for dynamic containers, the same
45    /// structure.
46    fn is_same_type_as(&self, other: &DynElement) -> bool {
47        self.element_type_id() == other.element_type_id()
48    }
49
50    /// Identity of the implementing Rust type.
51    #[doc(hidden)]
52    fn element_type_id(&self) -> TypeId {
53        TypeId::of::<Self>()
54    }
55
56    /// Encodes this element as an outermost value.
57    fn to_bytes(&self) -> Result<Vec<u8>, EncoderError> {
58        let mut buffer = Vec::new();
59        self.append_to(&mut buffer)?;
60        Ok(buffer)
61    }
62
63    /// Appends the encoding to `buffer` as a new outermost value: padding is computed from the first
64    /// appended octet. On error `buffer` is left unchanged.
65    fn append_to(&self, buffer: &mut Vec<u8>) -> Result<(), EncoderError> {
66        let start = buffer.len();
67        let mut writer = ByteWriter::new(buffer);
68        let result = self.encode_into(&mut writer).and_then(|()| writer.status());
69        if result.is_err() {
70            buffer.truncate(start);
71        }
72        result
73    }
74
75    /// Decodes this element from the start of `bytes`; octets after the value are ignored.
76    fn decode_slice(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
77        self.decode_from(&mut ByteReader::new(bytes))
78    }
79
80    /// Decodes this element from `bytes`, which must hold exactly one value.
81    fn decode_slice_strict(&mut self, bytes: &[u8]) -> Result<(), DecoderError> {
82        let mut reader = ByteReader::new(bytes);
83        self.decode_from(&mut reader)?;
84        reader.expect_end()
85    }
86}
87
88impl<T> DataElement for T
89where
90    T: Decode + Clone + fmt::Debug + Send + Sync + 'static,
91{
92    fn octet_boundary(&self) -> usize {
93        <T as Encode>::OCTET_BOUNDARY
94    }
95
96    fn encode_into(&self, writer: &mut ByteWriter<'_>) -> Result<(), EncoderError> {
97        Encode::encode(self, writer);
98        writer.status()
99    }
100
101    fn decode_from(&mut self, reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
102        *self = T::decode(reader)?;
103        Ok(())
104    }
105
106    fn clone_element(&self) -> Box<DynElement> {
107        Box::new(self.clone())
108    }
109}
110
111impl dyn DataElement {
112    /// True if the element is a `T`.
113    pub fn is<T: DataElement>(&self) -> bool {
114        let any: &dyn Any = self;
115        any.is::<T>()
116    }
117
118    /// The element as a `T`, if it is one.
119    pub fn downcast_ref<T: DataElement>(&self) -> Option<&T> {
120        let any: &dyn Any = self;
121        any.downcast_ref::<T>()
122    }
123
124    /// The element as a mutable `T`, if it is one.
125    pub fn downcast_mut<T: DataElement>(&mut self) -> Option<&mut T> {
126        let any: &mut dyn Any = self;
127        any.downcast_mut::<T>()
128    }
129}
130
131impl Clone for Box<DynElement> {
132    fn clone(&self) -> Self {
133        (**self).clone_element()
134    }
135}
136
137/// Two elements are equal when they have the same datatype and the same encoding. An element that cannot
138/// be encoded (a variant record without a variant for its discriminant) equals nothing.
139impl PartialEq for dyn DataElement {
140    fn eq(&self, other: &Self) -> bool {
141        self.is_same_type_as(other)
142            && matches!((self.to_bytes(), other.to_bytes()), (Ok(left), Ok(right)) if left == right)
143    }
144}