Skip to main content

microrti_encoding/
lib.rs

1//! HLA data encoding helpers of IEEE 1516-2025: the `encoding` package of the standard Java and C++ APIs
2//! (12.11.4.2, 12.12.4.2) as a Rust library.
3//!
4//! Attribute and parameter values are opaque octets for the RTI. Federates agree on their layout through
5//! the datatypes of the FOM, whose encodings are defined by IEEE 1516.2 (OMT). This crate implements
6//! those encodings, including the padding rules, in two layers.
7//!
8//! # Typed layer
9//!
10//! [`Encode`] and [`Decode`] are implemented by Rust types whose HLA datatype is known at compile time:
11//!
12//! * the basic representations as wrappers of the Rust type they carry: [`HLAinteger32BE`]`(i32)`,
13//!   [`HLAfloat64LE`]`(f64)`, [`HLAoctet`]`(u8)`...;
14//! * the simple datatypes [`HLAASCIIchar`], [`HLAunicodeChar`], [`HLAbyte`], [`HLAboolean`];
15//! * [`HLAASCIIstring`], [`HLAunicodeString`] (also `String`), [`HLAopaqueData`];
16//! * the handle elements ([`HLAfederateHandle`]...) and [`HLAlogicalTime`], [`HLAlogicalTimeInterval`];
17//! * `Vec<T>` (`HLAvariableArray`) and `[T; N]` (`HLAfixedArray`);
18//! * structs and enums declared with [`hla_fixed_record!`], [`hla_enumerated!`], [`hla_variant_record!`]
19//!   and [`hla_extendable_variant_record!`].
20//!
21//! Bare integers and floats have no encoding of their own because the datatype decides size and byte
22//! order; the macros accept them with an encoding marker (`speed: f32 as HLAfloat32BE`).
23//!
24//! ```
25//! use microrti_encoding::{
26//!     decode_from_slice_strict, encode_to_vec, hla_fixed_record, DecoderError, HLAfloat64BE, HLAoctet,
27//! };
28//!
29//! hla_fixed_record! {
30//!     /// A position report.
31//!     pub struct Report {
32//!         pub quality: HLAoctet,
33//!         pub position: [HLAfloat64BE; 2],
34//!         pub label: String,
35//!     }
36//! }
37//!
38//! let report = Report {
39//!     quality: HLAoctet(3),
40//!     position: [HLAfloat64BE(1.0), HLAfloat64BE(-2.0)],
41//!     label: "x".into(),
42//! };
43//! let bytes = encode_to_vec(&report);
44//! // 1 octet, 7 of padding, 2 x 8 octets, a count and one UTF-16 code unit.
45//! assert_eq!(bytes.len(), 1 + 7 + 16 + 4 + 2);
46//! assert_eq!(decode_from_slice_strict::<Report>(&bytes)?, report);
47//! # Ok::<(), DecoderError>(())
48//! ```
49//!
50//! # Dynamic layer
51//!
52//! [`DataElement`] is the object-safe trait of the standard APIs. Every typed value is a data element,
53//! and the containers [`HLAfixedRecord`], [`HLAfixedArray`], [`HLAvariableArray`], [`HLAvariantRecord`]
54//! and [`HLAextendableVariantRecord`] assemble datatypes at run time, for example from a parsed FOM.
55//!
56//! ```
57//! use microrti_encoding::{
58//!     DataElement, HLAboolean, HLAfixedRecord, HLAinteractionClassHandle, HLAvariableArray,
59//! };
60//!
61//! // MOM datatype HLAinteractionSubList: a variable array of HLAinteractionSubscription records.
62//! let subscription = |class: [u8; 4], active: bool| {
63//!     HLAfixedRecord::new().with(HLAinteractionClassHandle::new(class)).with(HLAboolean(active))
64//! };
65//! let mut list = HLAvariableArray::new(subscription([0; 4], false));
66//! list.push(subscription([0, 0, 0, 9], true))?;
67//! let bytes = list.to_bytes()?;
68//! assert_eq!(bytes, [0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 9, 0, 0, 0, 1]);
69//!
70//! let mut decoded = HLAvariableArray::new(subscription([0; 4], false));
71//! decoded.decode_slice_strict(&bytes)?;
72//! assert_eq!(decoded, list);
73//! # Ok::<(), Box<dyn std::error::Error>>(())
74//! ```
75//!
76//! # Padding
77//!
78//! Every datatype has an octet boundary (IEEE 1516.2 4.14.10), and its encoding starts at an offset,
79//! counted from the start of the outermost value, that is a multiple of it. Here each element aligns
80//! itself before it writes or reads, which yields the padding that 4.14.10.1 to 4.14.10.5 place between
81//! the parts of a constructed datatype and none after the last part: a constructed datatype starts at a
82//! multiple of its own boundary, the largest of its parts, so offsets counted from the outermost value
83//! and from the start of the datatype give the same padding. [`ByteWriter`] and [`ByteReader`] keep
84//! track of the offset. Encoding writes zero padding, as 4.14.10 requires of the sender; the clause says
85//! nothing of a receiver that finds other octets there, and decoding ignores what padding holds.
86//!
87//! # Robustness
88//!
89//! Decoding never panics. Errors are [`DecoderError`] values, element counts are checked against the
90//! octets that are left before anything is allocated, and memory use is bounded by a small multiple of
91//! the input size.
92//!
93//! # FOM-driven codec
94//!
95//! With the cargo feature `fom` the module `fom` adds a third layer: `FomCodec` encodes and decodes
96//! any data type of a merged FDD (`microrti-fom`) by its name, to and from a self-describing `Value`
97//! tree. The feature is off by default, and the default build does not depend on `microrti-fom`.
98#![warn(missing_docs)]
99
100mod basic;
101mod buffer;
102mod dynamic;
103mod element;
104mod error;
105pub mod extendable;
106#[cfg(feature = "fom")]
107pub mod fom;
108mod handles;
109mod macros;
110mod strings;
111mod time;
112mod typed;
113
114pub use basic::*;
115pub use buffer::{ByteReader, ByteWriter, max_boundary, padding_for};
116pub use dynamic::{
117    HLAextendableVariantRecord, HLAfixedArray, HLAfixedRecord, HLAvariableArray, HLAvariantRecord,
118};
119pub use element::{DataElement, DynElement};
120pub use error::{DecoderError, EncoderError};
121pub use handles::*;
122pub use strings::{HLAASCIIstring, HLAopaqueData, HLAunicodeString};
123pub use time::{HLAlogicalTime, HLAlogicalTimeInterval};
124#[doc(hidden)]
125pub use typed::__first_or_zero;
126pub use typed::{
127    BasicData, Decode, Encode, Enumerated, FixedArrayOf, Representation, VariableArrayOf, decode_from_slice,
128    decode_from_slice_strict, decode_prefix, encode_into, encode_to_vec, try_encode_to_vec,
129};