microrti-encoding 0.4.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! The value tree of the FOM-driven codec on its own: constructors, accessors, `Display`, JSON and
//! postcard.
#![cfg(feature = "fom")]

use microrti_encoding::fom::{Enumerator, FomCodec, Value, VariantValue};
use microrti_fom::Fdd;

/// One value of every variant, with the JSON text it must have.
fn samples() -> Vec<(Value, &'static str)> {
    vec![
        (Value::Bool(true), "true"),
        (Value::from(-5), "-5"),
        (Value::from(u64::MAX), "18446744073709551615"),
        (Value::from(i64::MIN), "-9223372036854775808"),
        (Value::from(1.5), "1.5"),
        (Value::from(2.0), "2.0"),
        (Value::from(-0.1f64), "-0.1"),
        (Value::Float(f64::INFINITY), r#"{"$float":"inf"}"#),
        (Value::Float(f64::NEG_INFINITY), r#"{"$float":"-inf"}"#),
        (Value::Octet(7), r#"{"$octet":7}"#),
        (Value::Char('a'), r#"{"$char":"a"}"#),
        (Value::from("Jo \"e\""), r#""Jo \"e\"""#),
        (Value::from(""), r#""""#),
        (Value::bytes([0x0au8, 0xff]), r#"{"$bytes":"0aff"}"#),
        (Value::Bytes(vec![]), r#"{"$bytes":""}"#),
        (Value::handle([0u8, 0, 0, 1]), r#"{"$handle":"00000001"}"#),
        (Value::raw([0xdeu8, 0xad]), r#"{"$raw":"dead"}"#),
        (Value::enumerator_with("TimeGranted", 0), r#"{"$enum":{"name":"TimeGranted","value":0}}"#),
        (Value::enumerator("TimeGranted"), r#"{"$enum":{"name":"TimeGranted","value":null}}"#),
        (Value::enumerator_value(7), r#"{"$enum":{"name":null,"value":7}}"#),
        (Value::array([1, 2, 3]), "[1,2,3]"),
        (Value::Array(vec![]), "[]"),
        (Value::Record(vec![]), "{}"),
        (
            Value::record([
                ("Name", Value::from("Joe")),
                ("Count", Value::from(3)),
                ("Rate", Value::from(1.5)),
                ("Ok", Value::from(true)),
                ("Tags", Value::array(["a", "b"])),
                ("Home", Value::record([("Zip", "12345")])),
            ]),
            r#"{"Name":"Joe","Count":3,"Rate":1.5,"Ok":true,"Tags":["a","b"],"Home":{"Zip":"12345"}}"#,
        ),
        // A field name that starts with '$' is escaped, so that it cannot be taken for a tag.
        (Value::record([("$bytes", "00")]), r#"{"$$bytes":"00"}"#),
        (Value::record([("a", 1), ("$b", 2), ("$$c", 3)]), r#"{"a":1,"$$b":2,"$$$c":3}"#),
        (
            Value::variant_named(Enumerator::new("Trainee", 0), "CoursePassed", true),
            r#"{"$variant":{"discriminant":{"name":"Trainee","value":0},"alternative":"CoursePassed","value":true}}"#,
        ),
        (
            Value::variant(Enumerator::numbered(3), Some(Value::raw([1u8]))),
            r#"{"$variant":{"discriminant":{"name":null,"value":3},"alternative":null,"value":{"$raw":"01"}}}"#,
        ),
        (
            Value::variant("Nothing", None),
            r#"{"$variant":{"discriminant":{"name":"Nothing","value":null},"alternative":null,"value":null}}"#,
        ),
    ]
}

/// The value with the fields of every record in alphabetical order.
fn sorted(value: Value) -> Value {
    match value {
        Value::Record(mut fields) => {
            fields.sort_by(|left, right| left.0.cmp(&right.0));
            Value::Record(fields.into_iter().map(|(name, field)| (name, sorted(field))).collect())
        }
        Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()),
        Value::Variant(mut variant) => {
            variant.value = variant.value.map(sorted);
            Value::Variant(variant)
        }
        other => other,
    }
}

#[test]
fn json_uses_natural_shapes_and_round_trips() {
    for (value, expected) in samples() {
        let json = serde_json::to_string(&value).unwrap();
        assert_eq!(json, expected, "{value:?}");
        assert_eq!(serde_json::from_str::<Value>(&json).unwrap(), value, "{json}");
        // Through the generic JSON tree as well, the way a tool would hold a document. That tree sorts
        // the keys of an object, so record fields may come back in another order (which the encoder
        // accepts).
        let tree = serde_json::to_value(&value).unwrap();
        assert_eq!(sorted(serde_json::from_value::<Value>(tree).unwrap()), sorted(value), "{json}");
    }

    let nan = serde_json::to_string(&Value::Float(f64::NAN)).unwrap();
    assert_eq!(nan, r#"{"$float":"NaN"}"#);
    assert!(serde_json::from_str::<Value>(&nan).unwrap().as_f64().is_some_and(f64::is_nan));

    // Text written by hand: white space, any numbers, upper case hex digits.
    let written = r#" { "Speed" : 1e3, "Count" : 12, "Id" : { "$handle" : "0A0B" }, "Big" : 1e400 } "#;
    let read = serde_json::from_str::<Value>(written);
    assert!(read.is_err(), "1e400 is no number");
    let written = r#" { "Speed" : 1e3, "Count" : 12, "Id" : { "$handle" : "0A0B" } } "#;
    let read: Value = serde_json::from_str(written).unwrap();
    assert_eq!(
        read,
        Value::record([
            ("Speed", Value::from(1000.0)),
            ("Count", Value::from(12)),
            ("Id", Value::handle([0x0au8, 0x0b]))
        ])
    );
}

#[test]
fn json_that_is_no_value_is_rejected() {
    for text in [
        "null",
        "[1, null]",
        r#"{"a": null}"#,
        r#"{"$nope": 1}"#,
        r#"{"$octet": 256}"#,
        r#"{"$octet": 1, "more": 2}"#,
        r#"{"$char": "ab"}"#,
        r#"{"$float": "fast"}"#,
        r#"{"$bytes": "0"}"#,
        r#"{"$bytes": "zz"}"#,
        r#"{"$handle": 5}"#,
        r#"{"$enum": "TimeGranted"}"#,
        r#"{"$enum": {"value": "one"}}"#,
        r#"{"$variant": {"alternative": "A"}}"#,
        r#"{"a": 1, "$bytes": "00"}"#,
        "{\"a\": 1",
        "",
    ] {
        assert!(serde_json::from_str::<Value>(text).is_err(), "{text} must be rejected");
    }
    // Parts that may be absent can be left out when writing by hand.
    let named: Value = serde_json::from_str(r#"{"$enum": {"name": "A"}}"#).unwrap();
    assert_eq!(named, Value::enumerator("A"));
    let empty: Value = serde_json::from_str(r#"{"$variant": {"discriminant": {"value": 3}}}"#).unwrap();
    assert_eq!(empty, Value::variant(Enumerator::numbered(3), None));
}

#[test]
fn postcard_round_trips() {
    for (value, _) in samples() {
        let wire = postcard::to_allocvec(&value).unwrap();
        assert_eq!(postcard::from_bytes::<Value>(&wire).unwrap(), value, "{value:?}");
    }
    let nan = postcard::to_allocvec(&Value::Float(f64::NAN)).unwrap();
    assert!(postcard::from_bytes::<Value>(&nan).unwrap().as_f64().is_some_and(f64::is_nan));
    // The binary form is a tagged enum: one octet of tag, then the content.
    assert_eq!(postcard::to_allocvec(&Value::Bool(true)).unwrap(), [0, 1]);
    assert_eq!(postcard::to_allocvec(&Value::from("ab")).unwrap(), [5, 2, b'a', b'b']);
    assert_eq!(postcard::to_allocvec(&Value::raw([9u8])).unwrap(), [12, 1, 9]);
    // Hostile input is an error, not a panic or a huge allocation.
    let hostile: [&[u8]; 5] =
        [&[], &[99], &[8, 0xff, 0xff, 0xff, 0xff, 0x0f], &[5, 200, b'a'], &[4, 0xff, 0xff, 0xff, 0xff, 0x7f]];
    for wire in hostile {
        assert!(postcard::from_bytes::<Value>(wire).is_err(), "{wire:?}");
    }
    // Arrays inside arrays, a hundred thousand deep: postcard has no depth limit of its own.
    let mut nested = [8u8, 1].repeat(100_000);
    nested.extend([0, 1]);
    assert_eq!(postcard::from_bytes::<Value>(&nested), Err(postcard::Error::SerdeDeCustom));
    // 127 arrays around a boolean are 128 levels, the limit; the count starts anew for every value.
    let levels = |arrays: usize| &nested[nested.len() - 2 * arrays - 2..];
    assert_eq!(postcard::from_bytes::<Value>(levels(128)), Err(postcard::Error::SerdeDeCustom));
    let mut deepest = postcard::from_bytes::<Value>(levels(127)).unwrap();
    for _ in 0..127 {
        let Value::Array(mut items) = deepest else { panic!("an array") };
        assert_eq!(items.len(), 1);
        deepest = items.remove(0);
    }
    assert_eq!(deepest, Value::Bool(true));
    let text = format!("{}true{}", "[".repeat(200), "]".repeat(200));
    assert!(serde_json::from_str::<Value>(&text).is_err());
}

#[test]
fn decoded_mom_values_serialize_like_any_other() {
    let codec = FomCodec::new(&Fdd::with_standard_mim()).unwrap();
    let bytes = [0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 9, 0, 0, 0, 1, 0, 0, 0, 2, 0xab, 0xcd, 0, 0, 0, 0, 0, 0];
    let list = codec.decode("HLAinteractionSubList", &bytes).unwrap();
    let json = serde_json::to_string(&list).unwrap();
    assert_eq!(
        json,
        r#"[{"HLAinteractionClass":{"$handle":"00000009"},"HLAactive":true},{"HLAinteractionClass":{"$handle":"abcd"},"HLAactive":false}]"#
    );
    // A script may write the natural forms the encoder accepts: fields in any order, an enumerator
    // by its name.
    let scripted: Value = serde_json::from_str(
        r#"[{"HLAactive": "HLAtrue", "HLAinteractionClass": {"$handle": "00000009"}},
            {"HLAactive": 0, "HLAinteractionClass": {"$bytes": "abcd"}}]"#,
    )
    .unwrap();
    assert_eq!(codec.encode("HLAinteractionSubList", &scripted).unwrap(), bytes);
    let state: Value = serde_json::from_str(r#""TimeAdvancing""#).unwrap();
    assert_eq!(codec.encode("HLAtimeState", &state).unwrap(), [0, 0, 0, 1]);
}

#[test]
fn display_is_compact_and_readable() {
    let cases: Vec<(Value, &str)> = vec![
        (Value::Bool(false), "false"),
        (Value::from(-12), "-12"),
        (Value::from(u64::MAX), "18446744073709551615"),
        (Value::from(2.0), "2.0"),
        (Value::from(-0.25), "-0.25"),
        (Value::Float(f64::NAN), "NaN"),
        (Value::Octet(0x0a), "0x0a"),
        (Value::Char('a'), "'a'"),
        (Value::from("a \"b\"\n"), r#""a \"b\"\n""#),
        (Value::bytes([0x0au8, 0xff]), "0x0aff"),
        (Value::Bytes(vec![]), "0x"),
        (Value::handle([0u8, 0, 0, 1]), "handle(0x00000001)"),
        (Value::raw([0xffu8]), "raw(0xff)"),
        (Value::enumerator_with("Serving", 2), "Serving(2)"),
        (Value::enumerator("Serving"), "Serving"),
        (Value::enumerator_value(9), "?(9)"),
        (Value::array([1, 2, 3]), "[1, 2, 3]"),
        (Value::Array(vec![]), "[]"),
        (Value::Record(vec![]), "{}"),
        (
            Value::record([
                ("Name", Value::from("Joe")),
                ("Rate", Value::from(1.5)),
                ("Tags", Value::array([1, 2])),
                ("State", Value::enumerator_with("Serving", 2)),
            ]),
            r#"{Name: "Joe", Rate: 1.5, Tags: [1, 2], State: Serving(2)}"#,
        ),
        (
            Value::variant_named(Enumerator::new("Trainee", 0), "CoursePassed", true),
            "Trainee(0){CoursePassed: true}",
        ),
        (Value::variant(Enumerator::new("Nothing", 3), None), "Nothing(3){}"),
        (Value::variant(Enumerator::numbered(3), Some(Value::raw([1u8]))), "?(3){raw(0x01)}"),
    ];
    for (value, expected) in cases {
        assert_eq!(value.to_string(), expected, "{value:?}");
    }
    assert_eq!(Enumerator { name: None, value: None }.to_string(), "?");
}

#[test]
fn constructors_and_accessors() {
    // From impls and the kind names used in messages.
    let kinds: Vec<(Value, &str)> = vec![
        (Value::from(true), "boolean"),
        (Value::from(1u8), "integer"),
        (Value::from(1i128 << 70), "integer"),
        (Value::from(1.5f32), "float"),
        (Value::Octet(1), "octet"),
        (Value::from('x'), "character"),
        (Value::from(String::from("x")), "string"),
        (Value::from(vec![1u8, 2]), "bytes"),
        (Value::from(&[1u8, 2][..]), "bytes"),
        (Value::from(Enumerator::named("A")), "enumerator"),
        (Value::from(vec![Value::from(1)]), "array"),
        (Value::record([("a", 1)]), "record"),
        (
            Value::from(VariantValue { discriminant: "A".into(), alternative: None, value: None }),
            "variant record",
        ),
        (Value::handle([1u8]), "handle"),
        (Value::raw([1u8]), "raw bytes"),
    ];
    for (value, kind) in kinds {
        assert_eq!(value.kind(), kind, "{value:?}");
    }
    assert_eq!(Value::integer(7u16), Value::Integer(7));
    assert_eq!(Value::string("x"), Value::from("x"));
    assert_eq!([1, 2].into_iter().map(Value::from).collect::<Value>(), Value::array([1, 2]));
    assert_eq!(Enumerator::from(String::from("A")), Enumerator::named("A"));

    // Scalars.
    assert_eq!(Value::Bool(true).as_bool(), Some(true));
    assert_eq!(Value::from(1).as_bool(), None);
    assert_eq!(Value::from(-3).as_i64(), Some(-3));
    assert_eq!(Value::from(-3).as_u64(), None);
    assert_eq!(Value::from(u64::MAX).as_u64(), Some(u64::MAX));
    assert_eq!(Value::from(u64::MAX).as_i64(), None);
    assert_eq!(Value::from(u64::MAX).as_integer(), Some(i128::from(u64::MAX)));
    assert_eq!(Value::Octet(9).as_i64(), Some(9));
    assert_eq!(Value::enumerator_with("A", 4).as_i64(), Some(4));
    assert_eq!(Value::enumerator("A").as_i64(), None);
    assert_eq!(Value::from("3").as_i64(), None);
    assert_eq!(Value::from(1.5).as_f64(), Some(1.5));
    assert_eq!(Value::from(3).as_f64(), Some(3.0));
    assert_eq!(Value::from("x").as_f64(), None);
    assert_eq!(Value::from('x').as_char(), Some('x'));
    assert_eq!(Value::from("x").as_char(), None);
    assert_eq!(Value::from("x").as_str(), Some("x"));
    assert_eq!(Value::enumerator_with("A", 4).as_str(), Some("A"));
    assert_eq!(Value::enumerator_value(4).as_str(), None);
    assert_eq!(Value::from(1).as_str(), None);
    for value in [Value::bytes([1u8]), Value::handle([1u8]), Value::raw([1u8])] {
        assert_eq!(value.as_bytes(), Some(&[1u8][..]));
    }
    assert_eq!(Value::from("x").as_bytes(), None);
    assert_eq!(Value::enumerator("A").as_enumerator(), Some(&Enumerator::named("A")));
    assert_eq!(Value::from("A").as_enumerator(), None);

    // Containers.
    let record = Value::record([
        ("Name", Value::from("Joe")),
        ("Tags", Value::array(["a", "b"])),
        ("Job", Value::variant_named("Trainee", "CoursePassed", true)),
    ]);
    assert_eq!(record.field("Name").and_then(Value::as_str), Some("Joe"));
    assert_eq!(record.field("Nope"), None);
    assert_eq!(record.fields().map(<[_]>::len), Some(3));
    assert_eq!(record.items(), None);
    let tags = record.field("Tags").unwrap();
    assert_eq!(tags.items().map(<[_]>::len), Some(2));
    assert_eq!(tags.get(1).and_then(Value::as_str), Some("b"));
    assert_eq!(tags.get(2), None);
    assert_eq!(tags.fields(), None);
    assert_eq!(tags.field("a"), None);
    let job = record.field("Job").unwrap();
    assert_eq!(job.field("CoursePassed"), Some(&Value::Bool(true)));
    assert_eq!(job.field("Rating"), None);
    let variant = job.as_variant().unwrap();
    assert_eq!(variant.discriminant, Enumerator::named("Trainee"));
    assert_eq!(variant.alternative.as_deref(), Some("CoursePassed"));
    assert_eq!(record.as_variant(), None);
}