Skip to main content

microrti_encoding/fom/
value.rs

1//! The self-describing value tree of the FOM-driven codec.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7/// An enumerator of an enumerated data type, given by name, by number or by both.
8///
9/// Decoding fills in the number and, when the number is an enumerator of the data type, the name.
10/// Encoding looks the name up when there is one (a number given with it must be one of the values of
11/// that enumerator) and otherwise requires the number to be the value of an enumerator.
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub struct Enumerator {
14    /// Name of the enumerator; `None` for a number that is no enumerator of the data type.
15    pub name: Option<String>,
16    /// Numeric value; `None` stands for the (first) value the FOM gives the name.
17    pub value: Option<i128>,
18}
19
20impl Enumerator {
21    /// An enumerator with its name and its number.
22    pub fn new(name: impl Into<String>, value: impl Into<i128>) -> Self {
23        Self { name: Some(name.into()), value: Some(value.into()) }
24    }
25
26    /// An enumerator given by name.
27    pub fn named(name: impl Into<String>) -> Self {
28        Self { name: Some(name.into()), value: None }
29    }
30
31    /// An enumerator given by number.
32    pub fn numbered(value: impl Into<i128>) -> Self {
33        Self { name: None, value: Some(value.into()) }
34    }
35}
36
37impl From<&str> for Enumerator {
38    fn from(name: &str) -> Self {
39        Self::named(name)
40    }
41}
42
43impl From<String> for Enumerator {
44    fn from(name: String) -> Self {
45        Self::named(name)
46    }
47}
48
49/// `Name(1)`, `Name` without a number, `?(7)` without a name.
50impl fmt::Display for Enumerator {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match (&self.name, self.value) {
53            (Some(name), Some(value)) => write!(f, "{name}({value})"),
54            (Some(name), None) => f.write_str(name),
55            (None, Some(value)) => write!(f, "?({value})"),
56            (None, None) => f.write_str("?"),
57        }
58    }
59}
60
61/// The content of a variant record value.
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct VariantValue {
64    /// The discriminant.
65    pub discriminant: Enumerator,
66    /// Name of the alternative the discriminant selects. Decoding sets it when the FOM names the
67    /// alternative; encoding checks it when it is given.
68    pub alternative: Option<String>,
69    /// The value of the alternative; `None` when the discriminant carries no data. An alternative of an
70    /// `HLAextendableVariantRecord` that the FDD does not define is [`Value::Raw`].
71    pub value: Option<Value>,
72}
73
74/// A value of any FOM data type; see the [module documentation](super) for the mapping.
75#[derive(Debug, Clone, PartialEq)]
76pub enum Value {
77    /// `HLAboolean`.
78    Bool(bool),
79    /// A signed or unsigned integer of up to 64 bits. Numbers outside `i64::MIN..=u64::MAX` fit no data
80    /// type and do not survive JSON.
81    Integer(i128),
82    /// A 32-bit or 64-bit floating point number.
83    Float(f64),
84    /// One uninterpreted octet (`HLAoctet`, `HLAbyte`).
85    Octet(u8),
86    /// One character (`HLAASCIIchar`, `HLAunicodeChar`).
87    Char(char),
88    /// An array of characters (`HLAASCIIstring`, `HLAunicodeString`...).
89    String(String),
90    /// An array of octets (`HLAopaqueData`, `HLAlogicalTime`...).
91    Bytes(Vec<u8>),
92    /// An enumerator of an enumerated data type.
93    Enum(Box<Enumerator>),
94    /// An array of any other element data type.
95    Array(Vec<Value>),
96    /// A fixed record: its fields by name, in the order of the data type.
97    Record(Vec<(String, Value)>),
98    /// A variant record.
99    Variant(Box<VariantValue>),
100    /// The encoded form of a handle (`HLAfederateHandle`...), see 12.2.
101    Handle(Vec<u8>),
102    /// The octets of a value whose data type cannot be resolved.
103    Raw(Vec<u8>),
104}
105
106impl Value {
107    /// An integer.
108    pub fn integer(value: impl Into<i128>) -> Self {
109        Value::Integer(value.into())
110    }
111
112    /// A string.
113    pub fn string(text: impl Into<String>) -> Self {
114        Value::String(text.into())
115    }
116
117    /// Opaque octets.
118    pub fn bytes(octets: impl Into<Vec<u8>>) -> Self {
119        Value::Bytes(octets.into())
120    }
121
122    /// The encoded form of a handle.
123    pub fn handle(octets: impl Into<Vec<u8>>) -> Self {
124        Value::Handle(octets.into())
125    }
126
127    /// Octets of an unresolved data type.
128    pub fn raw(octets: impl Into<Vec<u8>>) -> Self {
129        Value::Raw(octets.into())
130    }
131
132    /// An enumerator given by name.
133    pub fn enumerator(name: impl Into<String>) -> Self {
134        Value::Enum(Box::new(Enumerator::named(name)))
135    }
136
137    /// An enumerator given by number.
138    pub fn enumerator_value(value: impl Into<i128>) -> Self {
139        Value::Enum(Box::new(Enumerator::numbered(value)))
140    }
141
142    /// An enumerator with name and number, the form decoding produces.
143    pub fn enumerator_with(name: impl Into<String>, value: impl Into<i128>) -> Self {
144        Value::Enum(Box::new(Enumerator::new(name, value)))
145    }
146
147    /// An array of the given items.
148    pub fn array<T: Into<Value>>(items: impl IntoIterator<Item = T>) -> Self {
149        Value::Array(items.into_iter().map(Into::into).collect())
150    }
151
152    /// A record of the given fields.
153    pub fn record<N: Into<String>, T: Into<Value>>(fields: impl IntoIterator<Item = (N, T)>) -> Self {
154        Value::Record(fields.into_iter().map(|(name, value)| (name.into(), value.into())).collect())
155    }
156
157    /// A variant record whose alternative is not named; `value` is `None` for a discriminant without
158    /// data.
159    pub fn variant(discriminant: impl Into<Enumerator>, value: Option<Value>) -> Self {
160        Value::Variant(Box::new(VariantValue { discriminant: discriminant.into(), alternative: None, value }))
161    }
162
163    /// A variant record with a named alternative.
164    pub fn variant_named(
165        discriminant: impl Into<Enumerator>,
166        alternative: impl Into<String>,
167        value: impl Into<Value>,
168    ) -> Self {
169        Value::Variant(Box::new(VariantValue {
170            discriminant: discriminant.into(),
171            alternative: Some(alternative.into()),
172            value: Some(value.into()),
173        }))
174    }
175
176    /// Name of the variant, for messages: `integer`, `record`...
177    pub fn kind(&self) -> &'static str {
178        match self {
179            Value::Bool(_) => "boolean",
180            Value::Integer(_) => "integer",
181            Value::Float(_) => "float",
182            Value::Octet(_) => "octet",
183            Value::Char(_) => "character",
184            Value::String(_) => "string",
185            Value::Bytes(_) => "bytes",
186            Value::Enum(_) => "enumerator",
187            Value::Array(_) => "array",
188            Value::Record(_) => "record",
189            Value::Variant(_) => "variant record",
190            Value::Handle(_) => "handle",
191            Value::Raw(_) => "raw bytes",
192        }
193    }
194
195    /// The boolean of a `Bool`.
196    pub fn as_bool(&self) -> Option<bool> {
197        match self {
198            Value::Bool(value) => Some(*value),
199            _ => None,
200        }
201    }
202
203    /// The number of an `Integer`, an `Octet` or an `Enum` that has one.
204    pub fn as_integer(&self) -> Option<i128> {
205        match self {
206            Value::Integer(value) => Some(*value),
207            Value::Octet(value) => Some(i128::from(*value)),
208            Value::Enum(enumerator) => enumerator.value,
209            _ => None,
210        }
211    }
212
213    /// [`Value::as_integer`] when the number fits an `i64`.
214    pub fn as_i64(&self) -> Option<i64> {
215        self.as_integer().and_then(|value| i64::try_from(value).ok())
216    }
217
218    /// [`Value::as_integer`] when the number fits a `u64`.
219    pub fn as_u64(&self) -> Option<u64> {
220        self.as_integer().and_then(|value| u64::try_from(value).ok())
221    }
222
223    /// The number of a `Float`, or of an `Integer` converted to the nearest `f64`.
224    pub fn as_f64(&self) -> Option<f64> {
225        match self {
226            Value::Float(value) => Some(*value),
227            Value::Integer(value) => Some(*value as f64),
228            _ => None,
229        }
230    }
231
232    /// The character of a `Char`.
233    pub fn as_char(&self) -> Option<char> {
234        match self {
235            Value::Char(value) => Some(*value),
236            _ => None,
237        }
238    }
239
240    /// The text of a `String`, or the name of an `Enum` that has one.
241    pub fn as_str(&self) -> Option<&str> {
242        match self {
243            Value::String(text) => Some(text),
244            Value::Enum(enumerator) => enumerator.name.as_deref(),
245            _ => None,
246        }
247    }
248
249    /// The octets of `Bytes`, `Handle` or `Raw`.
250    pub fn as_bytes(&self) -> Option<&[u8]> {
251        match self {
252            Value::Bytes(octets) | Value::Handle(octets) | Value::Raw(octets) => Some(octets),
253            _ => None,
254        }
255    }
256
257    /// The enumerator of an `Enum`.
258    pub fn as_enumerator(&self) -> Option<&Enumerator> {
259        match self {
260            Value::Enum(enumerator) => Some(enumerator),
261            _ => None,
262        }
263    }
264
265    /// The content of a `Variant`.
266    pub fn as_variant(&self) -> Option<&VariantValue> {
267        match self {
268            Value::Variant(variant) => Some(variant),
269            _ => None,
270        }
271    }
272
273    /// The items of an `Array`.
274    pub fn items(&self) -> Option<&[Value]> {
275        match self {
276            Value::Array(items) => Some(items),
277            _ => None,
278        }
279    }
280
281    /// The item of an `Array` at `index`.
282    pub fn get(&self, index: usize) -> Option<&Value> {
283        self.items()?.get(index)
284    }
285
286    /// The fields of a `Record`, in order.
287    pub fn fields(&self) -> Option<&[(String, Value)]> {
288        match self {
289            Value::Record(fields) => Some(fields),
290            _ => None,
291        }
292    }
293
294    /// The field of a `Record` called `name`, or the value of a `Variant` whose alternative has that
295    /// name.
296    pub fn field(&self, name: &str) -> Option<&Value> {
297        match self {
298            Value::Record(fields) => fields.iter().find(|(field, _)| field == name).map(|(_, value)| value),
299            Value::Variant(variant) if variant.alternative.as_deref() == Some(name) => variant.value.as_ref(),
300            _ => None,
301        }
302    }
303}
304
305impl From<bool> for Value {
306    fn from(value: bool) -> Self {
307        Value::Bool(value)
308    }
309}
310
311macro_rules! integer_from {
312    ($($native:ty),+) => {$(
313        impl From<$native> for Value {
314            fn from(value: $native) -> Self {
315                Value::Integer(i128::from(value))
316            }
317        }
318    )+};
319}
320
321integer_from!(i8, i16, i32, i64, u8, u16, u32, u64);
322
323impl From<i128> for Value {
324    fn from(value: i128) -> Self {
325        Value::Integer(value)
326    }
327}
328
329impl From<f32> for Value {
330    fn from(value: f32) -> Self {
331        Value::Float(f64::from(value))
332    }
333}
334
335impl From<f64> for Value {
336    fn from(value: f64) -> Self {
337        Value::Float(value)
338    }
339}
340
341impl From<char> for Value {
342    fn from(value: char) -> Self {
343        Value::Char(value)
344    }
345}
346
347impl From<&str> for Value {
348    fn from(text: &str) -> Self {
349        Value::String(text.to_owned())
350    }
351}
352
353impl From<String> for Value {
354    fn from(text: String) -> Self {
355        Value::String(text)
356    }
357}
358
359/// Opaque octets ([`Value::Bytes`]).
360impl From<Vec<u8>> for Value {
361    fn from(octets: Vec<u8>) -> Self {
362        Value::Bytes(octets)
363    }
364}
365
366/// Opaque octets ([`Value::Bytes`]).
367impl From<&[u8]> for Value {
368    fn from(octets: &[u8]) -> Self {
369        Value::Bytes(octets.to_vec())
370    }
371}
372
373impl From<Vec<Value>> for Value {
374    fn from(items: Vec<Value>) -> Self {
375        Value::Array(items)
376    }
377}
378
379impl From<Enumerator> for Value {
380    fn from(enumerator: Enumerator) -> Self {
381        Value::Enum(Box::new(enumerator))
382    }
383}
384
385impl From<VariantValue> for Value {
386    fn from(variant: VariantValue) -> Self {
387        Value::Variant(Box::new(variant))
388    }
389}
390
391impl FromIterator<Value> for Value {
392    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
393        Value::Array(items.into_iter().collect())
394    }
395}
396
397fn write_hex(f: &mut fmt::Formatter<'_>, octets: &[u8]) -> fmt::Result {
398    f.write_str("0x")?;
399    octets.iter().try_for_each(|octet| write!(f, "{octet:02x}"))
400}
401
402/// A compact single-line form: `{Name: "Joe", Rate: 1.5, Tags: [1, 2], State: Serving(2)}`.
403///
404/// Strings and characters are quoted and escaped, octets are hexadecimal (`0x0a0b`, `handle(0x..)`,
405/// `raw(0x..)`), enumerators are `Name(number)`, variant records are `Discriminant(number){Alternative:
406/// value}`.
407impl fmt::Display for Value {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        match self {
410            Value::Bool(value) => write!(f, "{value}"),
411            Value::Integer(value) => write!(f, "{value}"),
412            Value::Float(value) => write!(f, "{value:?}"),
413            Value::Octet(value) => write!(f, "0x{value:02x}"),
414            Value::Char(value) => write!(f, "{value:?}"),
415            Value::String(text) => write!(f, "{text:?}"),
416            Value::Bytes(octets) => write_hex(f, octets),
417            Value::Enum(enumerator) => write!(f, "{enumerator}"),
418            Value::Array(items) => {
419                f.write_str("[")?;
420                for (index, item) in items.iter().enumerate() {
421                    if index > 0 {
422                        f.write_str(", ")?;
423                    }
424                    write!(f, "{item}")?;
425                }
426                f.write_str("]")
427            }
428            Value::Record(fields) => {
429                f.write_str("{")?;
430                for (index, (name, value)) in fields.iter().enumerate() {
431                    if index > 0 {
432                        f.write_str(", ")?;
433                    }
434                    write!(f, "{name}: {value}")?;
435                }
436                f.write_str("}")
437            }
438            Value::Variant(variant) => {
439                write!(f, "{}{{", variant.discriminant)?;
440                match (&variant.alternative, &variant.value) {
441                    (Some(name), Some(value)) => write!(f, "{name}: {value}")?,
442                    (Some(name), None) => f.write_str(name)?,
443                    (None, Some(value)) => write!(f, "{value}")?,
444                    (None, None) => {}
445                }
446                f.write_str("}")
447            }
448            Value::Handle(octets) => {
449                f.write_str("handle(")?;
450                write_hex(f, octets)?;
451                f.write_str(")")
452            }
453            Value::Raw(octets) => {
454                f.write_str("raw(")?;
455                write_hex(f, octets)?;
456                f.write_str(")")
457            }
458        }
459    }
460}