Skip to main content

microrti_encoding/
typed.rs

1//! The typed layer: [`Encode`] / [`Decode`] for Rust types whose HLA datatype is known at compile time.
2
3use std::marker::PhantomData;
4
5use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY, max_boundary};
6use crate::error::{DecoderError, EncoderError};
7
8/// A Rust type with a fixed HLA encoding.
9///
10/// Implementations align the writer to [`Encode::OCTET_BOUNDARY`] before writing, so containers only have
11/// to encode their parts in order: the padding in front of each part is the padding the standard places
12/// after the previous one, and nothing is ever written after the last part.
13pub trait Encode {
14    /// Octet boundary of the datatype: its encoding starts at a multiple of this offset.
15    const OCTET_BOUNDARY: usize;
16
17    /// Appends the encoding of `self`, preceded by the padding its octet boundary requires.
18    fn encode(&self, writer: &mut ByteWriter<'_>);
19
20    /// Length in octets of the encoding when it starts at an aligned offset.
21    fn encoded_len(&self) -> usize {
22        let mut counter = ByteWriter::counter();
23        self.encode(&mut counter);
24        counter.position()
25    }
26}
27
28/// A Rust type that can be rebuilt from its HLA encoding.
29pub trait Decode: Encode + Sized {
30    /// Skips the padding the octet boundary requires and decodes one value.
31    ///
32    /// Never panics; never allocates more than a small multiple of the remaining input.
33    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError>;
34}
35
36/// An encoding marker: `Self` names the HLA datatype used to carry Rust values of type `V`.
37///
38/// Every [`Decode`] type represents itself. In addition the basic wrappers represent their native type
39/// (`HLAinteger32BE` represents `i32`, `HLAunicodeString` represents `String`...), which lets the record
40/// macros keep plain Rust field types: `count: i32 as HLAinteger32BE`.
41pub trait Representation<V> {
42    /// Octet boundary of the datatype.
43    const BOUNDARY: usize;
44
45    /// Encodes `value` as this datatype.
46    fn encode_value(value: &V, writer: &mut ByteWriter<'_>);
47
48    /// Decodes a value of this datatype.
49    fn decode_value(reader: &mut ByteReader<'_>) -> Result<V, DecoderError>;
50
51    /// Encoded length of `value` when it starts at an aligned offset.
52    fn encoded_len_of(value: &V) -> usize {
53        let mut counter = ByteWriter::counter();
54        Self::encode_value(value, &mut counter);
55        counter.position()
56    }
57}
58
59impl<T: Decode> Representation<T> for T {
60    const BOUNDARY: usize = <T as Encode>::OCTET_BOUNDARY;
61
62    fn encode_value(value: &T, writer: &mut ByteWriter<'_>) {
63        value.encode(writer);
64    }
65
66    fn decode_value(reader: &mut ByteReader<'_>) -> Result<T, DecoderError> {
67        T::decode(reader)
68    }
69
70    fn encoded_len_of(value: &T) -> usize {
71        value.encoded_len()
72    }
73}
74
75/// A basic data representation wrapping one native Rust value (`HLAinteger32BE` wraps `i32`).
76pub trait BasicData: Decode + Copy {
77    /// The wrapped Rust type.
78    type Native: Copy + PartialEq + std::fmt::Debug;
79
80    /// Wraps a native value.
81    fn from_native(value: Self::Native) -> Self;
82
83    /// Unwraps the native value.
84    fn to_native(self) -> Self::Native;
85}
86
87/// A datatype usable as the discriminant of a variant record: an enumerated datatype, or a basic
88/// representation used directly.
89///
90/// The representation is what travels on the wire. `HLAextendableVariantRecord` decoders read it first so
91/// that enumerators added by other FOM modules can be skipped instead of being an error.
92pub trait Enumerated: Sized {
93    /// Wire representation of the enumerators.
94    type Representation: Decode + Clone + PartialEq + std::fmt::Debug;
95
96    /// The wire value of this enumerator.
97    fn to_representation(&self) -> Self::Representation;
98
99    /// The enumerator with this wire value, if there is one.
100    fn from_representation(representation: &Self::Representation) -> Option<Self>;
101}
102
103/// Upper bound, in octets of memory, for what a decoder reserves before it has seen the elements.
104const PREALLOCATION_LIMIT: usize = 64 * 1024;
105
106fn bounded_capacity<V>(count: usize) -> usize {
107    count.min(PREALLOCATION_LIMIT / std::mem::size_of::<V>().max(1))
108}
109
110fn encode_variable<V>(
111    items: &[V],
112    boundary: usize,
113    writer: &mut ByteWriter<'_>,
114    encode: impl Fn(&V, &mut ByteWriter<'_>),
115) {
116    writer.align(boundary);
117    writer.put_count(items.len());
118    for item in items {
119        encode(item, writer);
120    }
121}
122
123fn decode_variable<V>(
124    boundary: usize,
125    reader: &mut ByteReader<'_>,
126    decode: impl Fn(&mut ByteReader<'_>) -> Result<V, DecoderError>,
127) -> Result<Vec<V>, DecoderError> {
128    reader.align(boundary)?;
129    let count = reader.read_count()?;
130    let mut items = Vec::with_capacity(bounded_capacity::<V>(count));
131    for _ in 0..count {
132        items.push(decode(reader)?);
133    }
134    Ok(items)
135}
136
137fn encode_fixed<V>(
138    items: &[V],
139    boundary: usize,
140    writer: &mut ByteWriter<'_>,
141    encode: impl Fn(&V, &mut ByteWriter<'_>),
142) {
143    writer.align(boundary);
144    for item in items {
145        encode(item, writer);
146    }
147}
148
149fn decode_fixed<V, const N: usize>(
150    boundary: usize,
151    reader: &mut ByteReader<'_>,
152    decode: impl Fn(&mut ByteReader<'_>) -> Result<V, DecoderError>,
153) -> Result<[V; N], DecoderError> {
154    reader.align(boundary)?;
155    let mut items = Vec::with_capacity(bounded_capacity::<V>(N));
156    for _ in 0..N {
157        items.push(decode(reader)?);
158    }
159    items.try_into().map_err(|rest: Vec<V>| DecoderError::CountMismatch {
160        type_name: "HLAfixedArray",
161        expected: N,
162        found: rest.len(),
163    })
164}
165
166/// `HLAvariableArray`: element count as `HLAinteger32BE`, then the elements, each at its own boundary.
167/// An empty array is the count alone.
168impl<T: Encode> Encode for [T] {
169    const OCTET_BOUNDARY: usize = max_boundary(&[COUNT_BOUNDARY, T::OCTET_BOUNDARY]);
170
171    fn encode(&self, writer: &mut ByteWriter<'_>) {
172        encode_variable(self, <Self as Encode>::OCTET_BOUNDARY, writer, T::encode);
173    }
174}
175
176/// `HLAvariableArray` of `T`.
177impl<T: Encode> Encode for Vec<T> {
178    const OCTET_BOUNDARY: usize = <[T] as Encode>::OCTET_BOUNDARY;
179
180    fn encode(&self, writer: &mut ByteWriter<'_>) {
181        self.as_slice().encode(writer);
182    }
183}
184
185impl<T: Decode> Decode for Vec<T> {
186    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
187        decode_variable(<Self as Encode>::OCTET_BOUNDARY, reader, T::decode)
188    }
189}
190
191/// `HLAfixedArray` of `N` elements of `T`: the elements without a count.
192impl<T: Encode, const N: usize> Encode for [T; N] {
193    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;
194
195    fn encode(&self, writer: &mut ByteWriter<'_>) {
196        encode_fixed(self, T::OCTET_BOUNDARY, writer, T::encode);
197    }
198}
199
200impl<T: Decode, const N: usize> Decode for [T; N] {
201    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
202        decode_fixed(T::OCTET_BOUNDARY, reader, T::decode)
203    }
204}
205
206impl<T: Encode + ?Sized> Encode for &T {
207    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;
208
209    fn encode(&self, writer: &mut ByteWriter<'_>) {
210        (**self).encode(writer);
211    }
212}
213
214impl<T: Encode + ?Sized> Encode for Box<T> {
215    const OCTET_BOUNDARY: usize = T::OCTET_BOUNDARY;
216
217    fn encode(&self, writer: &mut ByteWriter<'_>) {
218        (**self).encode(writer);
219    }
220}
221
222impl<T: Decode> Decode for Box<T> {
223    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
224        T::decode(reader).map(Box::new)
225    }
226}
227
228/// Encoding marker for `Vec<V>` carried as an `HLAvariableArray` whose elements use the marker `R`.
229///
230/// `values: Vec<f64> as VariableArrayOf<HLAfloat64BE>` in a record macro. Never instantiated.
231pub struct VariableArrayOf<R>(PhantomData<R>);
232
233impl<V, R: Representation<V>> Representation<Vec<V>> for VariableArrayOf<R> {
234    const BOUNDARY: usize = max_boundary(&[COUNT_BOUNDARY, <R as Representation<V>>::BOUNDARY]);
235
236    fn encode_value(value: &Vec<V>, writer: &mut ByteWriter<'_>) {
237        let boundary = <Self as Representation<Vec<V>>>::BOUNDARY;
238        encode_variable(value, boundary, writer, <R as Representation<V>>::encode_value);
239    }
240
241    fn decode_value(reader: &mut ByteReader<'_>) -> Result<Vec<V>, DecoderError> {
242        let boundary = <Self as Representation<Vec<V>>>::BOUNDARY;
243        decode_variable(boundary, reader, <R as Representation<V>>::decode_value)
244    }
245}
246
247/// Encoding marker for `[V; N]` carried as an `HLAfixedArray` whose elements use the marker `R`.
248///
249/// `position: [f64; 3] as FixedArrayOf<HLAfloat64BE>` in a record macro. Never instantiated.
250pub struct FixedArrayOf<R>(PhantomData<R>);
251
252impl<V, R: Representation<V>, const N: usize> Representation<[V; N]> for FixedArrayOf<R> {
253    const BOUNDARY: usize = <R as Representation<V>>::BOUNDARY;
254
255    fn encode_value(value: &[V; N], writer: &mut ByteWriter<'_>) {
256        let boundary = <R as Representation<V>>::BOUNDARY;
257        encode_fixed(value, boundary, writer, <R as Representation<V>>::encode_value);
258    }
259
260    fn decode_value(reader: &mut ByteReader<'_>) -> Result<[V; N], DecoderError> {
261        let boundary = <R as Representation<V>>::BOUNDARY;
262        decode_fixed(boundary, reader, <R as Representation<V>>::decode_value)
263    }
264}
265
266/// Encodes `value` as an outermost value, reporting values that have no encoding.
267///
268/// The only typed values without an encoding are collections with more than `i32::MAX` elements and
269/// `HLAextendableVariantRecord` alternatives longer than `u32::MAX` octets.
270pub fn try_encode_to_vec<T: Encode + ?Sized>(value: &T) -> Result<Vec<u8>, EncoderError> {
271    let mut buffer = Vec::new();
272    encode_into(value, &mut buffer)?;
273    Ok(buffer)
274}
275
276/// Encodes `value` as an outermost value.
277///
278/// # Panics
279///
280/// Panics if the value has no encoding, which takes a collection of more than `i32::MAX` elements (see
281/// [`try_encode_to_vec`] for the non-panicking form).
282pub fn encode_to_vec<T: Encode + ?Sized>(value: &T) -> Vec<u8> {
283    match try_encode_to_vec(value) {
284        Ok(buffer) => buffer,
285        Err(error) => panic!("value has no HLA encoding: {error}"),
286    }
287}
288
289/// Appends the encoding of `value` to `buffer` as a new outermost value: padding is computed from the
290/// first appended octet, whatever `buffer` already holds. On error `buffer` is left unchanged.
291pub fn encode_into<T: Encode + ?Sized>(value: &T, buffer: &mut Vec<u8>) -> Result<(), EncoderError> {
292    let start = buffer.len();
293    let mut writer = ByteWriter::new(buffer);
294    value.encode(&mut writer);
295    let status = writer.status();
296    if status.is_err() {
297        buffer.truncate(start);
298    }
299    status
300}
301
302/// Decodes one value from the start of `bytes` and returns it with the number of octets it used.
303pub fn decode_prefix<T: Decode>(bytes: &[u8]) -> Result<(T, usize), DecoderError> {
304    let mut reader = ByteReader::new(bytes);
305    let value = T::decode(&mut reader)?;
306    Ok((value, reader.position()))
307}
308
309/// Decodes one value from the start of `bytes`; octets after the value are ignored.
310pub fn decode_from_slice<T: Decode>(bytes: &[u8]) -> Result<T, DecoderError> {
311    decode_prefix(bytes).map(|(value, _)| value)
312}
313
314/// Decodes one value that must span `bytes` exactly: trailing octets are
315/// [`DecoderError::TrailingBytes`].
316pub fn decode_from_slice_strict<T: Decode>(bytes: &[u8]) -> Result<T, DecoderError> {
317    let mut reader = ByteReader::new(bytes);
318    let value = T::decode(&mut reader)?;
319    reader.expect_end()?;
320    Ok(value)
321}
322
323/// Support function of the record macros: the first length of the list, or zero.
324#[doc(hidden)]
325pub fn __first_or_zero(lengths: &[usize]) -> usize {
326    lengths.first().copied().unwrap_or(0)
327}