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
//! The self-describing value tree of the FOM-driven codec.

use std::fmt;

use serde::{Deserialize, Serialize};

/// An enumerator of an enumerated data type, given by name, by number or by both.
///
/// Decoding fills in the number and, when the number is an enumerator of the data type, the name.
/// Encoding looks the name up when there is one (a number given with it must be one of the values of
/// that enumerator) and otherwise requires the number to be the value of an enumerator.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Enumerator {
    /// Name of the enumerator; `None` for a number that is no enumerator of the data type.
    pub name: Option<String>,
    /// Numeric value; `None` stands for the (first) value the FOM gives the name.
    pub value: Option<i128>,
}

impl Enumerator {
    /// An enumerator with its name and its number.
    pub fn new(name: impl Into<String>, value: impl Into<i128>) -> Self {
        Self { name: Some(name.into()), value: Some(value.into()) }
    }

    /// An enumerator given by name.
    pub fn named(name: impl Into<String>) -> Self {
        Self { name: Some(name.into()), value: None }
    }

    /// An enumerator given by number.
    pub fn numbered(value: impl Into<i128>) -> Self {
        Self { name: None, value: Some(value.into()) }
    }
}

impl From<&str> for Enumerator {
    fn from(name: &str) -> Self {
        Self::named(name)
    }
}

impl From<String> for Enumerator {
    fn from(name: String) -> Self {
        Self::named(name)
    }
}

/// `Name(1)`, `Name` without a number, `?(7)` without a name.
impl fmt::Display for Enumerator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (&self.name, self.value) {
            (Some(name), Some(value)) => write!(f, "{name}({value})"),
            (Some(name), None) => f.write_str(name),
            (None, Some(value)) => write!(f, "?({value})"),
            (None, None) => f.write_str("?"),
        }
    }
}

/// The content of a variant record value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VariantValue {
    /// The discriminant.
    pub discriminant: Enumerator,
    /// Name of the alternative the discriminant selects. Decoding sets it when the FOM names the
    /// alternative; encoding checks it when it is given.
    pub alternative: Option<String>,
    /// The value of the alternative; `None` when the discriminant carries no data. An alternative of an
    /// `HLAextendableVariantRecord` that the FDD does not define is [`Value::Raw`].
    pub value: Option<Value>,
}

/// A value of any FOM data type; see the [module documentation](super) for the mapping.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// `HLAboolean`.
    Bool(bool),
    /// A signed or unsigned integer of up to 64 bits. Numbers outside `i64::MIN..=u64::MAX` fit no data
    /// type and do not survive JSON.
    Integer(i128),
    /// A 32-bit or 64-bit floating point number.
    Float(f64),
    /// One uninterpreted octet (`HLAoctet`, `HLAbyte`).
    Octet(u8),
    /// One character (`HLAASCIIchar`, `HLAunicodeChar`).
    Char(char),
    /// An array of characters (`HLAASCIIstring`, `HLAunicodeString`...).
    String(String),
    /// An array of octets (`HLAopaqueData`, `HLAlogicalTime`...).
    Bytes(Vec<u8>),
    /// An enumerator of an enumerated data type.
    Enum(Box<Enumerator>),
    /// An array of any other element data type.
    Array(Vec<Value>),
    /// A fixed record: its fields by name, in the order of the data type.
    Record(Vec<(String, Value)>),
    /// A variant record.
    Variant(Box<VariantValue>),
    /// The encoded form of a handle (`HLAfederateHandle`...), see 12.2.
    Handle(Vec<u8>),
    /// The octets of a value whose data type cannot be resolved.
    Raw(Vec<u8>),
}

impl Value {
    /// An integer.
    pub fn integer(value: impl Into<i128>) -> Self {
        Value::Integer(value.into())
    }

    /// A string.
    pub fn string(text: impl Into<String>) -> Self {
        Value::String(text.into())
    }

    /// Opaque octets.
    pub fn bytes(octets: impl Into<Vec<u8>>) -> Self {
        Value::Bytes(octets.into())
    }

    /// The encoded form of a handle.
    pub fn handle(octets: impl Into<Vec<u8>>) -> Self {
        Value::Handle(octets.into())
    }

    /// Octets of an unresolved data type.
    pub fn raw(octets: impl Into<Vec<u8>>) -> Self {
        Value::Raw(octets.into())
    }

    /// An enumerator given by name.
    pub fn enumerator(name: impl Into<String>) -> Self {
        Value::Enum(Box::new(Enumerator::named(name)))
    }

    /// An enumerator given by number.
    pub fn enumerator_value(value: impl Into<i128>) -> Self {
        Value::Enum(Box::new(Enumerator::numbered(value)))
    }

    /// An enumerator with name and number, the form decoding produces.
    pub fn enumerator_with(name: impl Into<String>, value: impl Into<i128>) -> Self {
        Value::Enum(Box::new(Enumerator::new(name, value)))
    }

    /// An array of the given items.
    pub fn array<T: Into<Value>>(items: impl IntoIterator<Item = T>) -> Self {
        Value::Array(items.into_iter().map(Into::into).collect())
    }

    /// A record of the given fields.
    pub fn record<N: Into<String>, T: Into<Value>>(fields: impl IntoIterator<Item = (N, T)>) -> Self {
        Value::Record(fields.into_iter().map(|(name, value)| (name.into(), value.into())).collect())
    }

    /// A variant record whose alternative is not named; `value` is `None` for a discriminant without
    /// data.
    pub fn variant(discriminant: impl Into<Enumerator>, value: Option<Value>) -> Self {
        Value::Variant(Box::new(VariantValue { discriminant: discriminant.into(), alternative: None, value }))
    }

    /// A variant record with a named alternative.
    pub fn variant_named(
        discriminant: impl Into<Enumerator>,
        alternative: impl Into<String>,
        value: impl Into<Value>,
    ) -> Self {
        Value::Variant(Box::new(VariantValue {
            discriminant: discriminant.into(),
            alternative: Some(alternative.into()),
            value: Some(value.into()),
        }))
    }

    /// Name of the variant, for messages: `integer`, `record`...
    pub fn kind(&self) -> &'static str {
        match self {
            Value::Bool(_) => "boolean",
            Value::Integer(_) => "integer",
            Value::Float(_) => "float",
            Value::Octet(_) => "octet",
            Value::Char(_) => "character",
            Value::String(_) => "string",
            Value::Bytes(_) => "bytes",
            Value::Enum(_) => "enumerator",
            Value::Array(_) => "array",
            Value::Record(_) => "record",
            Value::Variant(_) => "variant record",
            Value::Handle(_) => "handle",
            Value::Raw(_) => "raw bytes",
        }
    }

    /// The boolean of a `Bool`.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(value) => Some(*value),
            _ => None,
        }
    }

    /// The number of an `Integer`, an `Octet` or an `Enum` that has one.
    pub fn as_integer(&self) -> Option<i128> {
        match self {
            Value::Integer(value) => Some(*value),
            Value::Octet(value) => Some(i128::from(*value)),
            Value::Enum(enumerator) => enumerator.value,
            _ => None,
        }
    }

    /// [`Value::as_integer`] when the number fits an `i64`.
    pub fn as_i64(&self) -> Option<i64> {
        self.as_integer().and_then(|value| i64::try_from(value).ok())
    }

    /// [`Value::as_integer`] when the number fits a `u64`.
    pub fn as_u64(&self) -> Option<u64> {
        self.as_integer().and_then(|value| u64::try_from(value).ok())
    }

    /// The number of a `Float`, or of an `Integer` converted to the nearest `f64`.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Value::Float(value) => Some(*value),
            Value::Integer(value) => Some(*value as f64),
            _ => None,
        }
    }

    /// The character of a `Char`.
    pub fn as_char(&self) -> Option<char> {
        match self {
            Value::Char(value) => Some(*value),
            _ => None,
        }
    }

    /// The text of a `String`, or the name of an `Enum` that has one.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(text) => Some(text),
            Value::Enum(enumerator) => enumerator.name.as_deref(),
            _ => None,
        }
    }

    /// The octets of `Bytes`, `Handle` or `Raw`.
    pub fn as_bytes(&self) -> Option<&[u8]> {
        match self {
            Value::Bytes(octets) | Value::Handle(octets) | Value::Raw(octets) => Some(octets),
            _ => None,
        }
    }

    /// The enumerator of an `Enum`.
    pub fn as_enumerator(&self) -> Option<&Enumerator> {
        match self {
            Value::Enum(enumerator) => Some(enumerator),
            _ => None,
        }
    }

    /// The content of a `Variant`.
    pub fn as_variant(&self) -> Option<&VariantValue> {
        match self {
            Value::Variant(variant) => Some(variant),
            _ => None,
        }
    }

    /// The items of an `Array`.
    pub fn items(&self) -> Option<&[Value]> {
        match self {
            Value::Array(items) => Some(items),
            _ => None,
        }
    }

    /// The item of an `Array` at `index`.
    pub fn get(&self, index: usize) -> Option<&Value> {
        self.items()?.get(index)
    }

    /// The fields of a `Record`, in order.
    pub fn fields(&self) -> Option<&[(String, Value)]> {
        match self {
            Value::Record(fields) => Some(fields),
            _ => None,
        }
    }

    /// The field of a `Record` called `name`, or the value of a `Variant` whose alternative has that
    /// name.
    pub fn field(&self, name: &str) -> Option<&Value> {
        match self {
            Value::Record(fields) => fields.iter().find(|(field, _)| field == name).map(|(_, value)| value),
            Value::Variant(variant) if variant.alternative.as_deref() == Some(name) => variant.value.as_ref(),
            _ => None,
        }
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Value::Bool(value)
    }
}

macro_rules! integer_from {
    ($($native:ty),+) => {$(
        impl From<$native> for Value {
            fn from(value: $native) -> Self {
                Value::Integer(i128::from(value))
            }
        }
    )+};
}

integer_from!(i8, i16, i32, i64, u8, u16, u32, u64);

impl From<i128> for Value {
    fn from(value: i128) -> Self {
        Value::Integer(value)
    }
}

impl From<f32> for Value {
    fn from(value: f32) -> Self {
        Value::Float(f64::from(value))
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Value::Float(value)
    }
}

impl From<char> for Value {
    fn from(value: char) -> Self {
        Value::Char(value)
    }
}

impl From<&str> for Value {
    fn from(text: &str) -> Self {
        Value::String(text.to_owned())
    }
}

impl From<String> for Value {
    fn from(text: String) -> Self {
        Value::String(text)
    }
}

/// Opaque octets ([`Value::Bytes`]).
impl From<Vec<u8>> for Value {
    fn from(octets: Vec<u8>) -> Self {
        Value::Bytes(octets)
    }
}

/// Opaque octets ([`Value::Bytes`]).
impl From<&[u8]> for Value {
    fn from(octets: &[u8]) -> Self {
        Value::Bytes(octets.to_vec())
    }
}

impl From<Vec<Value>> for Value {
    fn from(items: Vec<Value>) -> Self {
        Value::Array(items)
    }
}

impl From<Enumerator> for Value {
    fn from(enumerator: Enumerator) -> Self {
        Value::Enum(Box::new(enumerator))
    }
}

impl From<VariantValue> for Value {
    fn from(variant: VariantValue) -> Self {
        Value::Variant(Box::new(variant))
    }
}

impl FromIterator<Value> for Value {
    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
        Value::Array(items.into_iter().collect())
    }
}

fn write_hex(f: &mut fmt::Formatter<'_>, octets: &[u8]) -> fmt::Result {
    f.write_str("0x")?;
    octets.iter().try_for_each(|octet| write!(f, "{octet:02x}"))
}

/// A compact single-line form: `{Name: "Joe", Rate: 1.5, Tags: [1, 2], State: Serving(2)}`.
///
/// Strings and characters are quoted and escaped, octets are hexadecimal (`0x0a0b`, `handle(0x..)`,
/// `raw(0x..)`), enumerators are `Name(number)`, variant records are `Discriminant(number){Alternative:
/// value}`.
impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Bool(value) => write!(f, "{value}"),
            Value::Integer(value) => write!(f, "{value}"),
            Value::Float(value) => write!(f, "{value:?}"),
            Value::Octet(value) => write!(f, "0x{value:02x}"),
            Value::Char(value) => write!(f, "{value:?}"),
            Value::String(text) => write!(f, "{text:?}"),
            Value::Bytes(octets) => write_hex(f, octets),
            Value::Enum(enumerator) => write!(f, "{enumerator}"),
            Value::Array(items) => {
                f.write_str("[")?;
                for (index, item) in items.iter().enumerate() {
                    if index > 0 {
                        f.write_str(", ")?;
                    }
                    write!(f, "{item}")?;
                }
                f.write_str("]")
            }
            Value::Record(fields) => {
                f.write_str("{")?;
                for (index, (name, value)) in fields.iter().enumerate() {
                    if index > 0 {
                        f.write_str(", ")?;
                    }
                    write!(f, "{name}: {value}")?;
                }
                f.write_str("}")
            }
            Value::Variant(variant) => {
                write!(f, "{}{{", variant.discriminant)?;
                match (&variant.alternative, &variant.value) {
                    (Some(name), Some(value)) => write!(f, "{name}: {value}")?,
                    (Some(name), None) => f.write_str(name)?,
                    (None, Some(value)) => write!(f, "{value}")?,
                    (None, None) => {}
                }
                f.write_str("}")
            }
            Value::Handle(octets) => {
                f.write_str("handle(")?;
                write_hex(f, octets)?;
                f.write_str(")")
            }
            Value::Raw(octets) => {
                f.write_str("raw(")?;
                write_hex(f, octets)?;
                f.write_str(")")
            }
        }
    }
}