microrti-encoding 0.2.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Declarative macros for the typed layer: enumerated datatypes, fixed records and variant records.

/// Picks the encoding marker of a field: the marker after `as`, or the field type itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __hla_repr {
    ($value:ty) => {
        $value
    };
    ($value:ty, $repr:ty) => {
        $repr
    };
}

/// `true` when an optional macro fragment is present.
#[doc(hidden)]
#[macro_export]
macro_rules! __hla_present {
    () => {
        false
    };
    ($value:ty) => {
        true
    };
}

/// Expands to a binding pattern; exists so that a pattern can depend on an optional macro fragment.
#[doc(hidden)]
#[macro_export]
macro_rules! __hla_pat {
    ($binding:ident, $value:ty) => {
        $binding
    };
}

/// Declares an enumerated datatype (IEEE 1516.2 4.14.5): a fieldless enum carried by a basic
/// representation.
///
/// The generated enum derives `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq` and `Hash`, implements
/// [`Encode`](crate::Encode), [`Decode`](crate::Decode) and [`Enumerated`](crate::Enumerated), and offers
/// `value()`, `from_value()` and `ALL`. Decoding a value that is no enumerator fails with
/// [`DecoderError::InvalidEnumerator`](crate::DecoderError::InvalidEnumerator).
///
/// ```
/// use microrti_encoding::{decode_from_slice, encode_to_vec, hla_enumerated, DecoderError, HLAinteger32BE};
///
/// hla_enumerated! {
///     /// `DrinkType` of the Restaurant sample FOM.
///     pub enum DrinkType: HLAinteger32BE {
///         Margarita = 1,
///         DryMartini = 2,
///     }
/// }
///
/// assert_eq!(encode_to_vec(&DrinkType::DryMartini), [0, 0, 0, 2]);
/// assert_eq!(decode_from_slice::<DrinkType>(&[0, 0, 0, 1])?, DrinkType::Margarita);
/// assert_eq!(DrinkType::Margarita.value(), 1);
/// assert_eq!(DrinkType::from_value(3), None);
/// assert!(matches!(
///     decode_from_slice::<DrinkType>(&[0, 0, 0, 3]),
///     Err(DecoderError::InvalidEnumerator { .. })
/// ));
/// # Ok::<(), DecoderError>(())
/// ```
#[macro_export]
macro_rules! hla_enumerated {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident : $repr:ty {
            $(
                $(#[$vmeta:meta])*
                $variant:ident = $value:expr
            ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        $vis enum $name {
            $(
                $(#[$vmeta])*
                $variant,
            )+
        }

        impl $name {
            /// Every enumerator, in declaration order.
            #[allow(dead_code)]
            pub const ALL: &'static [Self] = &[$(Self::$variant),+];

            /// The value of this enumerator.
            pub const fn value(self) -> <$repr as $crate::BasicData>::Native {
                match self {
                    $(Self::$variant => $value,)+
                }
            }

            /// The enumerator with this value, if there is one.
            pub fn from_value(
                value: <$repr as $crate::BasicData>::Native,
            ) -> ::core::option::Option<Self> {
                $(
                    if value == $value {
                        return ::core::option::Option::Some(Self::$variant);
                    }
                )+
                ::core::option::Option::None
            }
        }

        impl $crate::Enumerated for $name {
            type Representation = $repr;

            fn to_representation(&self) -> $repr {
                <$repr as $crate::BasicData>::from_native(self.value())
            }

            fn from_representation(representation: &$repr) -> ::core::option::Option<Self> {
                Self::from_value(<$repr as $crate::BasicData>::to_native(*representation))
            }
        }

        impl $crate::Encode for $name {
            const OCTET_BOUNDARY: usize = <$repr as $crate::Encode>::OCTET_BOUNDARY;

            fn encode(&self, writer: &mut $crate::ByteWriter<'_>) {
                $crate::Encode::encode(&<Self as $crate::Enumerated>::to_representation(self), writer);
            }
        }

        impl $crate::Decode for $name {
            fn decode(
                reader: &mut $crate::ByteReader<'_>,
            ) -> ::core::result::Result<Self, $crate::DecoderError> {
                let raw = <$repr as $crate::Decode>::decode(reader)?;
                match <Self as $crate::Enumerated>::from_representation(&raw) {
                    ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
                    ::core::option::Option::None => {
                        ::core::result::Result::Err($crate::DecoderError::InvalidEnumerator {
                            type_name: ::core::stringify!($name),
                            value: ::std::format!("{:?}", raw),
                        })
                    }
                }
            }
        }
    };
}

/// Declares an `HLAfixedRecord` datatype as a Rust struct.
///
/// Each field is either of a type that implements [`Decode`](crate::Decode) (`name: HLAunicodeString`,
/// `position: Position`, `tags: Vec<HLAinteger16BE>`), or a plain Rust type followed by `as` and its
/// encoding marker, a [`Representation`](crate::Representation) of that type (`count: i32 as
/// HLAinteger32BE`). The struct derives `Debug`, `Clone` and `PartialEq`; further attributes can be added.
///
/// Fields are encoded in declaration order, each at the octet boundary of its datatype; nothing follows
/// the last field (IEEE 1516.2 4.14.10.1). The octet boundary of the record is the largest boundary of
/// its fields.
///
/// ```
/// use microrti_encoding::{
///     decode_from_slice_strict, encode_to_vec, hla_fixed_record, DecoderError, Encode, HLAfloat64BE,
///     HLAinteger16BE, HLAinteger32BE, HLAoctet, VariableArrayOf,
/// };
///
/// hla_fixed_record! {
///     /// A sample with fields of different octet boundaries.
///     pub struct Sample {
///         /// One octet, followed by three octets of padding.
///         pub kind: HLAoctet,
///         pub count: i32 as HLAinteger32BE,
///         pub name: String,
///         pub marks: Vec<i16> as VariableArrayOf<HLAinteger16BE>,
///     }
/// }
///
/// let sample = Sample { kind: HLAoctet(9), count: 2, name: "ab".into(), marks: vec![5] };
/// let bytes = encode_to_vec(&sample);
/// assert_eq!(
///     bytes,
///     [
///         9, 0, 0, 0, // kind, padding to the boundary of count
///         0, 0, 0, 2, // count
///         0, 0, 0, 2, 0, b'a', 0, b'b', // name: two UTF-16 code units
///         0, 0, 0, 1, 0, 5, // marks: one element, no padding after the last field
///     ]
/// );
/// assert_eq!(decode_from_slice_strict::<Sample>(&bytes)?, sample);
/// assert_eq!(Sample::OCTET_BOUNDARY, 4);
///
/// hla_fixed_record! {
///     /// Records nest; this one has the octet boundary 8.
///     #[derive(Default)]
///     pub struct Wide {
///         pub flag: HLAoctet,
///         pub value: HLAfloat64BE,
///     }
/// }
/// assert_eq!(encode_to_vec(&Wide::default()).len(), 16);
/// # Ok::<(), DecoderError>(())
/// ```
#[macro_export]
macro_rules! hla_fixed_record {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $(
                $(#[$fmeta:meta])*
                $fvis:vis $field:ident : $fty:ty $(as $repr:ty)?
            ),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq)]
        $vis struct $name {
            $(
                $(#[$fmeta])*
                $fvis $field: $fty,
            )*
        }

        impl $crate::Encode for $name {
            const OCTET_BOUNDARY: usize = $crate::max_boundary(&[
                $(<$crate::__hla_repr!($fty $(, $repr)?) as $crate::Representation<$fty>>::BOUNDARY,)*
            ]);

            fn encode(&self, writer: &mut $crate::ByteWriter<'_>) {
                writer.align(<Self as $crate::Encode>::OCTET_BOUNDARY);
                $(
                    <$crate::__hla_repr!($fty $(, $repr)?) as $crate::Representation<$fty>>::encode_value(
                        &self.$field,
                        writer,
                    );
                )*
            }
        }

        impl $crate::Decode for $name {
            fn decode(
                reader: &mut $crate::ByteReader<'_>,
            ) -> ::core::result::Result<Self, $crate::DecoderError> {
                reader.align(<Self as $crate::Encode>::OCTET_BOUNDARY)?;
                ::core::result::Result::Ok(Self {
                    $(
                        $field: <$crate::__hla_repr!($fty $(, $repr)?) as $crate::Representation<$fty>>
                            ::decode_value(reader)?,
                    )*
                })
            }
        }
    };
}

/// Declares an `HLAvariantRecord` datatype as a Rust enum.
///
/// The type after the colon is the discriminant datatype: an enumerated datatype declared with
/// [`hla_enumerated!`](crate::hla_enumerated), or any other type implementing [`Decode`](crate::Decode),
/// `PartialEq` and `Debug`. Each variant names the discriminant value that selects it after `=`, and may
/// carry one alternative, written like a record field (`Type` or `RustType as Marker`). Enumerators that
/// share an alternative datatype get one variant each.
///
/// Encoding (IEEE 1516.2 4.14.10.2): the discriminant, padding to the largest octet boundary of all
/// alternatives, then the alternative. A variant without data is the discriminant alone, which is how
/// the clause encodes an enumerator that no alternative applies to: declare one such variant for each
/// enumerator that can occur. Decoding a discriminant that selects no variant fails with
/// [`DecoderError::UnknownDiscriminant`](crate::DecoderError::UnknownDiscriminant).
///
/// ```
/// use microrti_encoding::{
///     decode_from_slice_strict, encode_to_vec, hla_enumerated, hla_variant_record, DecoderError, Encode,
///     HLAboolean, HLAfloat64BE, HLAoctet,
/// };
///
/// hla_enumerated! {
///     /// How a quantity is given.
///     pub enum Unit: HLAoctet {
///         Unknown = 0,
///         Exact = 1,
///         Estimated = 2,
///     }
/// }
///
/// hla_variant_record! {
///     /// A quantity whose form depends on the unit.
///     pub enum Quantity: Unit {
///         Unknown = Unit::Unknown,
///         Exact(f64 as HLAfloat64BE) = Unit::Exact,
///         Estimated(HLAboolean) = Unit::Estimated,
///     }
/// }
///
/// assert_eq!(Quantity::OCTET_BOUNDARY, 8);
/// assert_eq!(encode_to_vec(&Quantity::Unknown), [0]);
/// // The boolean has the boundary 4, but the padding follows the largest alternative boundary, 8.
/// let estimated = encode_to_vec(&Quantity::Estimated(HLAboolean(true)));
/// assert_eq!(estimated, [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
/// assert_eq!(decode_from_slice_strict::<Quantity>(&estimated)?, Quantity::Estimated(HLAboolean(true)));
/// assert_eq!(encode_to_vec(&Quantity::Exact(1.0)), [1, 0, 0, 0, 0, 0, 0, 0, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
/// # Ok::<(), DecoderError>(())
/// ```
#[macro_export]
macro_rules! hla_variant_record {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident : $dty:ty {
            $(
                $(#[$vmeta:meta])*
                $variant:ident $(( $aty:ty $(as $repr:ty)? ))? = $dval:expr
            ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq)]
        $vis enum $name {
            $(
                $(#[$vmeta])*
                $variant $(($aty))?,
            )+
        }

        impl $name {
            /// Largest octet boundary of the alternatives: the alternative starts at a multiple of it.
            pub const ALTERNATIVE_BOUNDARY: usize = $crate::max_boundary(&[
                $($(
                    <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>::BOUNDARY,
                )?)+
            ]);
        }

        impl $crate::Encode for $name {
            const OCTET_BOUNDARY: usize = $crate::max_boundary(&[
                <$dty as $crate::Encode>::OCTET_BOUNDARY,
                Self::ALTERNATIVE_BOUNDARY,
            ]);

            fn encode(&self, writer: &mut $crate::ByteWriter<'_>) {
                writer.align(<Self as $crate::Encode>::OCTET_BOUNDARY);
                match self {
                    $(
                        Self::$variant $(($crate::__hla_pat!(value, $aty)))? => {
                            let discriminant: $dty = $dval;
                            <$dty as $crate::Encode>::encode(&discriminant, writer);
                            $(
                                writer.align(Self::ALTERNATIVE_BOUNDARY);
                                <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>
                                    ::encode_value(value, writer);
                            )?
                        }
                    )+
                }
            }
        }

        impl $crate::Decode for $name {
            fn decode(
                reader: &mut $crate::ByteReader<'_>,
            ) -> ::core::result::Result<Self, $crate::DecoderError> {
                reader.align(<Self as $crate::Encode>::OCTET_BOUNDARY)?;
                let discriminant = <$dty as $crate::Decode>::decode(reader)?;
                $(
                    if discriminant == $dval {
                        return ::core::result::Result::Ok(Self::$variant $(({
                            reader.align(Self::ALTERNATIVE_BOUNDARY)?;
                            <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>
                                ::decode_value(reader)?
                        }))?);
                    }
                )+
                ::core::result::Result::Err($crate::DecoderError::UnknownDiscriminant {
                    type_name: ::core::stringify!($name),
                    discriminant: ::std::format!("{:?}", discriminant),
                })
            }
        }
    };
}

/// Declares an `HLAextendableVariantRecord` datatype as a Rust enum.
///
/// The syntax is that of [`hla_variant_record!`](crate::hla_variant_record), but the discriminant type
/// must implement [`Enumerated`](crate::Enumerated), and the generated enum has one more variant,
/// `Unknown { discriminant, data }`. It receives every alternative this declaration does not list, for
/// example one added by a FOM module the federate was not built with, including data received for a
/// variant declared without data: `discriminant` is the raw enumerator value and `data` the octets of
/// the alternative. Such a value is re-encoded unchanged.
///
/// The encoding (IEEE 1516.2 4.14.10.3) states the length of the alternative and has the octet boundary
/// 8 whatever the alternatives are; see the [`extendable`](crate::extendable) module for the layout. An
/// alternative of octet boundary above 8 is not allowed: such a declaration does not compile.
///
/// ```
/// use microrti_encoding::{
///     decode_from_slice_strict, encode_to_vec, hla_extendable_variant_record, DecoderError, HLAboolean,
///     HLAinteger32BE,
/// };
///
/// hla_extendable_variant_record! {
///     /// `DrinkGarnish` as the base module of the Restaurant sample FOM declares it.
///     pub enum DrinkGarnish: HLAinteger32BE {
///         HasSaltRim(HLAboolean) = HLAinteger32BE(1),
///         OliveCount(i32 as HLAinteger32BE) = HLAinteger32BE(2),
///     }
/// }
///
/// hla_extendable_variant_record! {
///     /// The same datatype after the extension module added an alternative.
///     pub enum ExtendedDrinkGarnish: HLAinteger32BE {
///         HasSaltRim(HLAboolean) = HLAinteger32BE(1),
///         OliveCount(i32 as HLAinteger32BE) = HLAinteger32BE(2),
///         ExtraWhippedCream(HLAboolean) = HLAinteger32BE(3),
///     }
/// }
///
/// let olives = encode_to_vec(&DrinkGarnish::OliveCount(3));
/// assert_eq!(olives, [0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]); // discriminant, length, alternative
///
/// // A federate that only knows the base module skips the new alternative and can pass it on.
/// let cream = encode_to_vec(&ExtendedDrinkGarnish::ExtraWhippedCream(HLAboolean(true)));
/// let skipped = decode_from_slice_strict::<DrinkGarnish>(&cream)?;
/// assert_eq!(
///     skipped,
///     DrinkGarnish::Unknown { discriminant: HLAinteger32BE(3), data: vec![0, 0, 0, 1] }
/// );
/// assert_eq!(encode_to_vec(&skipped), cream);
/// # Ok::<(), DecoderError>(())
/// ```
///
/// An alternative whose octet boundary exceeds 8 is refused at compile time (IEEE 1516.2 4.14.10.3):
///
/// ```compile_fail,E0080
/// use microrti_encoding::{
///     encode_to_vec, hla_extendable_variant_record, ByteReader, ByteWriter, Decode, DecoderError, Encode,
///     HLAoctet,
/// };
///
/// /// A datatype aligned on 16 octets, which no predefined representation is.
/// #[derive(Debug, Clone, PartialEq)]
/// struct Aligned16(u8);
///
/// impl Encode for Aligned16 {
///     const OCTET_BOUNDARY: usize = 16;
///
///     fn encode(&self, writer: &mut ByteWriter<'_>) {
///         writer.align(16);
///         writer.put_u8(self.0);
///     }
/// }
///
/// impl Decode for Aligned16 {
///     fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
///         reader.align(16)?;
///         reader.read_u8().map(Self)
///     }
/// }
///
/// hla_extendable_variant_record! {
///     enum TooWide: HLAoctet {
///         Wide(Aligned16) = HLAoctet(1),
///     }
/// }
///
/// let _ = encode_to_vec(&TooWide::Wide(Aligned16(1)));
/// ```
#[macro_export]
macro_rules! hla_extendable_variant_record {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident : $dty:ty {
            $(
                $(#[$vmeta:meta])*
                $variant:ident $(( $aty:ty $(as $repr:ty)? ))? = $dval:expr
            ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq)]
        $vis enum $name {
            $(
                $(#[$vmeta])*
                $variant $(($aty))?,
            )+
            /// An alternative that this declaration does not list.
            Unknown {
                /// The enumerator value as it was received.
                discriminant: <$dty as $crate::Enumerated>::Representation,
                /// The octets of the alternative.
                data: ::std::vec::Vec<u8>,
            },
        }

        impl $name {
            /// Largest octet boundary of the alternatives. IEEE 1516.2 4.14.10.3 allows at most 8; a
            /// declaration with a larger one does not compile.
            pub const ALTERNATIVE_BOUNDARY: usize = {
                let boundary = $crate::max_boundary(&[
                    $($(
                        <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>::BOUNDARY,
                    )?)+
                ]);
                assert!(
                    boundary <= $crate::extendable::ALTERNATIVE_BOUNDARY,
                    "an HLAextendableVariantRecord alternative has an octet boundary above 8"
                );
                boundary
            };
        }

        impl $crate::Encode for $name {
            const OCTET_BOUNDARY: usize = $crate::extendable::OCTET_BOUNDARY;

            fn encode(&self, writer: &mut $crate::ByteWriter<'_>) {
                let _ = Self::ALTERNATIVE_BOUNDARY;
                $crate::extendable::begin_encode(writer);
                match self {
                    $(
                        Self::$variant $(($crate::__hla_pat!(value, $aty)))? => {
                            let discriminant: $dty = $dval;
                            $crate::Encode::encode(
                                &<$dty as $crate::Enumerated>::to_representation(&discriminant),
                                writer,
                            );
                            let length = $crate::__first_or_zero(&[$(
                                <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>
                                    ::encoded_len_of(value),
                            )?]);
                            $crate::extendable::write_length(writer, length);
                            $(
                                <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>
                                    ::encode_value(value, writer);
                            )?
                        }
                    )+
                    Self::Unknown { discriminant, data } => {
                        $crate::Encode::encode(discriminant, writer);
                        $crate::extendable::write_length(writer, data.len());
                        writer.put_slice(data);
                    }
                }
            }
        }

        impl $crate::Decode for $name {
            fn decode(
                reader: &mut $crate::ByteReader<'_>,
            ) -> ::core::result::Result<Self, $crate::DecoderError> {
                $crate::extendable::begin_decode(reader)?;
                let raw = <<$dty as $crate::Enumerated>::Representation as $crate::Decode>::decode(reader)?;
                let mut alternative = $crate::extendable::read_alternative(reader)?;
                if let ::core::option::Option::Some(discriminant) =
                    <$dty as $crate::Enumerated>::from_representation(&raw)
                {
                    $(
                        // A variant declared without data that receives some: another FOM module gives
                        // this enumerator an alternative (annex C merges alternatives); it is passed on.
                        if discriminant == $dval && ($crate::__hla_present!($($aty)?) || alternative.is_empty()) {
                            let decoded = Self::$variant $((
                                <$crate::__hla_repr!($aty $(, $repr)?) as $crate::Representation<$aty>>
                                    ::decode_value(alternative.reader())?
                            ))?;
                            alternative.finish()?;
                            return ::core::result::Result::Ok(decoded);
                        }
                    )+
                }
                ::core::result::Result::Ok(Self::Unknown { discriminant: raw, data: alternative.into_bytes() })
            }
        }
    };
}