microrti_encoding/extendable.rs
1//! Wire layout of `HLAextendableVariantRecord` (IEEE 1516.2-2025 4.14.10.3), the variant record encoding
2//! that lets FOM modules add alternatives to an existing data type (4.14.8, annex C): the length of the
3//! alternative travels with it, so a receiver can skip an alternative it does not know, and adding one
4//! never moves the neighbours of the record. The dynamic container, the
5//! `hla_extendable_variant_record!` macro and the FOM-driven codec all use the functions of this module.
6//!
7//! Layout, offsets counted from the start of the outermost value (each record starts at a multiple of 8,
8//! so these are the offsets the clause counts from the start of the record):
9//!
10//! | Part | Rule |
11//! | --- | --- |
12//! | record | octet boundary [`OCTET_BOUNDARY`]: the alternatives count as 8, whatever they are |
13//! | discriminant | at offset 0, its own encoding |
14//! | padding | to a multiple of [`LENGTH_BOUNDARY`] (4), equation (3) |
15//! | encoded_length | `HLAinteger32BE`: octets of the alternative without padding; 0 when no alternative applies |
16//! | padding | to a multiple of [`ALTERNATIVE_BOUNDARY`] (8), equation (4) |
17//! | alternative | its own encoding, exactly encoded_length octets; nothing after it |
18//!
19//! The padding before the alternative is written whatever the length, also when no alternative applies:
20//! equation (4) computes it from the sizes of the discriminant and of the length field only, not from
21//! the presence of an alternative. The words "if required" around it allow another reading, padding
22//! only when an alternative follows (a receiver could apply that rule too, from the length); the two
23//! differ only for a discriminant of more than four octets (64 bits) and a length of 0, since after a
24//! smaller discriminant the length field ends at offset 8. MicroRTI 0.1.2 followed that other reading.
25//!
26//! When decoding, a length of 0 followed by fewer octets than that padding takes the 0.1.2 form: the
27//! padded form cannot be complete there. When more octets follow, they are read as padding: they could
28//! also be the next component of a 0.1.2 value, and nothing tells the two apart, padding content being
29//! ignored.
30//!
31//! Alternatives whose octet boundary exceeds 8 cannot use this encoding (4.14.10.3).
32
33use crate::buffer::{ByteReader, ByteWriter, padding_for};
34use crate::error::{DecoderError, EncoderError};
35
36/// Octet boundary of every `HLAextendableVariantRecord`, independent of its alternatives (4.14.10.3).
37pub const OCTET_BOUNDARY: usize = 8;
38/// Octet boundary of the encoded_length field, an `HLAinteger32BE`.
39pub const LENGTH_BOUNDARY: usize = 4;
40/// Octet boundary at which the alternative starts, and the largest one an alternative may have.
41pub const ALTERNATIVE_BOUNDARY: usize = 8;
42
43/// Aligns the writer for a record. The caller encodes the discriminant next.
44pub fn begin_encode(writer: &mut ByteWriter<'_>) {
45 writer.align(OCTET_BOUNDARY);
46}
47
48/// Writes the encoded_length field after the discriminant and the padding that follows it. The caller
49/// then encodes the alternative, which must take exactly `alternative_len` octets.
50///
51/// A length above `i32::MAX`, which the `HLAinteger32BE` field cannot hold, records
52/// [`EncoderError::AlternativeTooLong`].
53pub fn write_length(writer: &mut ByteWriter<'_>, alternative_len: usize) {
54 writer.align(LENGTH_BOUNDARY);
55 let length = match i32::try_from(alternative_len) {
56 Ok(length) => length,
57 Err(_) => {
58 writer.fail(EncoderError::AlternativeTooLong { length: alternative_len });
59 i32::MAX
60 }
61 };
62 writer.put_slice(&length.to_be_bytes());
63 writer.align(ALTERNATIVE_BOUNDARY);
64}
65
66/// Aligns the reader for a record. The caller decodes the discriminant next.
67pub fn begin_decode(reader: &mut ByteReader<'_>) -> Result<(), DecoderError> {
68 reader.align(OCTET_BOUNDARY)
69}
70
71/// Reads the encoded_length field after the discriminant, skips the padding that follows it and delimits
72/// the alternative. A negative length is [`DecoderError::InvalidValue`].
73///
74/// A length of 0 followed by fewer octets than the padding is read without padding (the form MicroRTI
75/// 0.1.2 wrote); see the module documentation.
76pub fn read_alternative<'a>(reader: &mut ByteReader<'a>) -> Result<Alternative<'a>, DecoderError> {
77 reader.align(LENGTH_BOUNDARY)?;
78 let raw = i32::from_be_bytes(reader.take_array()?);
79 let length = usize::try_from(raw).map_err(|_| DecoderError::InvalidValue {
80 type_name: "HLAextendableVariantRecord",
81 detail: format!("negative encoded_length {raw}"),
82 })?;
83 let unpadded = length == 0 && reader.remaining() < padding_for(reader.position(), ALTERNATIVE_BOUNDARY);
84 if !unpadded {
85 reader.align(ALTERNATIVE_BOUNDARY)?;
86 }
87 Ok(Alternative { reader: reader.window(length)?, length })
88}
89
90/// The octets of one alternative, as delimited by the length field.
91#[derive(Debug, Clone)]
92pub struct Alternative<'a> {
93 reader: ByteReader<'a>,
94 length: usize,
95}
96
97impl<'a> Alternative<'a> {
98 /// Announced length of the alternative in octets.
99 pub fn len(&self) -> usize {
100 self.length
101 }
102
103 /// True when the alternative carries no data.
104 pub fn is_empty(&self) -> bool {
105 self.length == 0
106 }
107
108 /// Reader limited to the alternative; decode the alternative datatype from it.
109 pub fn reader(&mut self) -> &mut ByteReader<'a> {
110 &mut self.reader
111 }
112
113 /// Checks that the alternative datatype used exactly the announced length.
114 pub fn finish(self) -> Result<(), DecoderError> {
115 match self.reader.remaining() {
116 0 => Ok(()),
117 unused => {
118 Err(DecoderError::LengthMismatch { declared: self.length, consumed: self.length - unused })
119 }
120 }
121 }
122
123 /// The octets not consumed so far; the whole alternative when it is skipped.
124 pub fn into_bytes(mut self) -> Vec<u8> {
125 let rest = self.reader.remaining();
126 self.reader.take(rest).map(<[u8]>::to_vec).unwrap_or_default()
127 }
128}