#![cfg(feature = "fom")]
mod common;
use std::collections::BTreeMap;
use common::XorShift;
use microrti_core::{ExceptionKind, RtiError};
use microrti_encoding::fom::{CodecError, Enumerator, FomCodec, Reason, Value, VariantValue};
use microrti_encoding::*;
use microrti_fom::{AttributeId, DataType, Fdd, FomModule, ObjectClassId, ParameterId, parse_module};
fn sample_module(name: &str) -> FomModule {
let path = format!("{}/../../fom/{name}", env!("CARGO_MANIFEST_DIR"));
let content = std::fs::read(&path).unwrap_or_else(|error| panic!("cannot read {path}: {error}"));
parse_module(name, &content).unwrap_or_else(|error| panic!("{name}: {error}"))
}
fn base_restaurant_fdd() -> Fdd {
Fdd::create(None, &[sample_module("RestaurantFOMmodule-2025.xml")]).expect("the Restaurant FOM merges").0
}
fn restaurant_fdd() -> Fdd {
let modules = [
sample_module("RestaurantFOMmodule-2025.xml"),
sample_module("RestaurantExtensionFOMmodule-2025.xml"),
];
Fdd::create(None, &modules).expect("the Restaurant FOM and its extension merge").0
}
fn fdd_with(body: &str) -> Fdd {
let document = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<objectModel xmlns=\"http://standards.ieee.org/IEEE1516-2025\">{body}</objectModel>"
);
let module = parse_module("test.xml", document.as_bytes())
.unwrap_or_else(|error| panic!("the test module does not parse: {error}"));
Fdd::create(None, &[module]).unwrap_or_else(|error| panic!("the test module does not merge: {error}")).0
}
#[derive(Default)]
struct Tables {
basic: Vec<String>,
simple: Vec<String>,
enumerated: Vec<String>,
arrays: Vec<String>,
records: Vec<String>,
variants: Vec<String>,
}
impl Tables {
fn basic(mut self, name: &str, size: u32, interpretation: &str, endian: &str) -> Self {
let endian = if endian.is_empty() { String::new() } else { format!("<endian>{endian}</endian>") };
self.basic.push(format!(
"<basicData><name>{name}</name><size>{size}</size>\
<interpretation>{interpretation}</interpretation>{endian}</basicData>"
));
self
}
fn simple(mut self, name: &str, representation: &str) -> Self {
self.simple.push(format!(
"<simpleData><name>{name}</name><representation>{representation}</representation></simpleData>"
));
self
}
fn enumerated(mut self, name: &str, representation: &str, enumerators: &[(&str, i64)]) -> Self {
let enumerators: String = enumerators
.iter()
.map(|(name, value)| {
format!("<enumerator><name>{name}</name><value>{value}</value></enumerator>")
})
.collect();
self.enumerated.push(format!(
"<enumeratedData><name>{name}</name><representation>{representation}</representation>\
{enumerators}</enumeratedData>"
));
self
}
fn array(mut self, name: &str, element: &str, cardinality: &str, encoding: &str) -> Self {
self.arrays.push(format!(
"<arrayData><name>{name}</name><dataType>{element}</dataType>\
<cardinality>{cardinality}</cardinality><encoding>{encoding}</encoding></arrayData>"
));
self
}
fn record(mut self, name: &str, encoding: &str, fields: &[(&str, &str)]) -> Self {
let fields: String = fields
.iter()
.map(|(name, data_type)| {
format!("<field><name>{name}</name><dataType>{data_type}</dataType></field>")
})
.collect();
self.records.push(format!(
"<fixedRecordData><name>{name}</name><encoding>{encoding}</encoding>{fields}</fixedRecordData>"
));
self
}
fn variant(
mut self,
name: &str,
encoding: &str,
(discriminant, discriminant_type): (&str, &str),
alternatives: &[(&str, &str, &str)],
) -> Self {
let alternatives: String = alternatives
.iter()
.map(|(enumerator, name, data_type)| {
let data = if name.is_empty() {
String::new()
} else {
format!("<name>{name}</name><dataType>{data_type}</dataType>")
};
format!("<alternative><enumerator>{enumerator}</enumerator>{data}</alternative>")
})
.collect();
self.variants.push(format!(
"<variantRecordData><name>{name}</name><discriminant>{discriminant}</discriminant>\
<dataType>{discriminant_type}</dataType>{alternatives}<encoding>{encoding}</encoding>\
</variantRecordData>"
));
self
}
fn xml(&self) -> String {
let table = |element: &str, entries: &[String]| {
if entries.is_empty() {
String::new()
} else {
format!("<{element}>{}</{element}>", entries.concat())
}
};
format!(
"<dataTypes>{}{}{}{}{}{}</dataTypes>",
table("basicDataRepresentations", &self.basic),
table("simpleDataTypes", &self.simple),
table("enumeratedDataTypes", &self.enumerated),
table("arrayDataTypes", &self.arrays),
table("fixedRecordDataTypes", &self.records),
table("variantRecordDataTypes", &self.variants),
)
}
fn fdd(&self) -> Fdd {
fdd_with(&self.xml())
}
fn codec(&self) -> FomCodec {
FomCodec::new(&self.fdd()).expect("the test data types resolve")
}
}
fn attribute(fdd: &Fdd, class: &str, name: &str) -> AttributeId {
let class = fdd.object_class_by_name(class).unwrap_or_else(|| panic!("no object class {class}"));
fdd.attribute_by_name(class, name).unwrap_or_else(|| panic!("no attribute {name}"))
}
fn parameter(fdd: &Fdd, class: &str, name: &str) -> ParameterId {
let class =
fdd.interaction_class_by_name(class).unwrap_or_else(|| panic!("no interaction class {class}"));
fdd.parameter_by_name(class, name).unwrap_or_else(|| panic!("no parameter {name}"))
}
struct Sampler<'a> {
fdd: &'a Fdd,
rng: XorShift,
}
impl<'a> Sampler<'a> {
fn new(fdd: &'a Fdd, seed: u64) -> Self {
Self { fdd, rng: XorShift(seed) }
}
fn text(&mut self, units: usize, ascii: bool) -> String {
const ASCII: [char; 6] = ['a', 'Z', '0', ' ', '~', '!'];
const BMP: [char; 6] = ['a', '\u{e9}', '\u{3a9}', '\u{4e2d}', '\u{ffff}', '0'];
(0..units).map(|_| if ascii { ASCII[self.rng.below(6)] } else { BMP[self.rng.below(6)] }).collect()
}
fn basic(&mut self, name: &str) -> Value {
let bits = self.rng.next();
match name {
"HLAoctet" => Value::Octet(bits as u8),
"HLAunsignedInteger8" => Value::integer(bits as u8),
"HLAoctetPairBE"
| "HLAoctetPairLE"
| "HLAunsignedInteger16BE"
| "HLAunsignedInteger16LE"
| "UnsignedShort" => Value::integer(bits as u16),
"HLAunsignedInteger32BE" | "HLAunsignedInteger32LE" => Value::integer(bits as u32),
"HLAunsignedInteger64BE" | "HLAunsignedInteger64LE" => Value::integer(bits),
"HLAinteger16BE" | "HLAinteger16LE" => Value::integer(bits as i16),
"HLAinteger32BE" | "HLAinteger32LE" => Value::integer(bits as i32),
"HLAinteger64BE" | "HLAinteger64LE" => Value::integer(bits as i64),
"HLAfloat32BE" | "HLAfloat32LE" => Value::Float(f64::from(bits as i16) / 4.0),
"HLAfloat64BE" | "HLAfloat64LE" => Value::Float(f64::from(bits as i32) / 1024.0),
other => panic!("the sampler does not know the basic representation {other}"),
}
}
fn array(&mut self, name: &str, element: &str, dimensions: &[Option<usize>]) -> Value {
let count = dimensions[0].unwrap_or_else(|| self.rng.below(4));
if dimensions.len() > 1 {
return Value::Array((0..count).map(|_| self.array(name, element, &dimensions[1..])).collect());
}
match element {
"HLAASCIIchar" => Value::String(self.text(count, true)),
"HLAunicodeChar" => Value::String(self.text(count, false)),
"HLAbyte" | "HLAoctet" if name.ends_with("Handle") => Value::Handle(self.rng.bytes(count)),
"HLAbyte" | "HLAoctet" => Value::Bytes(self.rng.bytes(count)),
element => Value::Array((0..count).map(|_| self.sample(element)).collect()),
}
}
fn sample(&mut self, name: &str) -> Value {
let fdd = self.fdd;
let data_type = fdd.data_type(name).unwrap_or_else(|| panic!("no data type {name}"));
match data_type {
DataType::Basic(basic) => self.basic(&basic.name),
DataType::Simple(simple) => match simple.name.as_str() {
"HLAASCIIchar" => Value::Char(self.text(1, true).remove(0)),
"HLAunicodeChar" => Value::Char(self.text(1, false).remove(0)),
_ => self.sample(simple.representation.as_deref().expect("a representation")),
},
DataType::Reference(reference) => self.sample(&reference.representation),
DataType::Enumerated(enumerated) => {
if enumerated.name == "HLAboolean" {
return Value::Bool(self.rng.below(2) == 1);
}
let enumerator = &enumerated.enumerators[self.rng.below(enumerated.enumerators.len())];
let value: i64 = enumerator.values[0].parse().expect("a numeric enumerator value");
Value::enumerator_with(enumerator.name.clone(), value)
}
DataType::Array(array) => {
let dimensions: Vec<Option<usize>> = array
.cardinality
.as_deref()
.unwrap_or("Dynamic")
.split(',')
.map(|dimension| dimension.trim().parse().ok())
.collect();
let element = array.data_type.as_deref().expect("an element data type");
self.array(&array.name, element, &dimensions)
}
DataType::FixedRecord(record) => Value::Record(
record
.fields
.iter()
.map(|field| {
(field.name.clone(), self.sample(field.data_type.as_deref().expect("a field type")))
})
.collect(),
),
DataType::VariantRecord(variant) => {
let Some(DataType::Enumerated(enumerated)) =
fdd.data_type(variant.data_type.as_deref().expect("a discriminant type"))
else {
panic!("the discriminant of {name} is not enumerated");
};
let listed: Vec<_> = variant
.alternatives
.iter()
.filter(|alternative| alternative.enumerator.as_deref() != Some("HLAother"))
.collect();
let alternative = listed[self.rng.below(listed.len())];
let enumerator = enumerated
.enumerators
.iter()
.find(|enumerator| Some(enumerator.name.as_str()) == alternative.enumerator.as_deref())
.expect("the enumerator of the alternative");
let number: i64 = enumerator.values[0].parse().expect("a numeric enumerator value");
Value::Variant(Box::new(VariantValue {
discriminant: Enumerator::new(enumerator.name.clone(), number),
alternative: alternative.name.clone(),
value: alternative.data_type.as_deref().map(|data_type| self.sample(data_type)),
}))
}
}
}
}
fn round_trip(codec: &FomCodec, name: &str, value: &Value) -> Vec<u8> {
let bytes = codec.encode(name, value).unwrap_or_else(|error| panic!("{error} for {value}"));
assert_eq!(codec.decode(name, &bytes).as_ref(), Ok(value), "{name}: {bytes:?}");
assert_eq!(codec.decode_prefix(name, &bytes).map(|(_, used)| used), Ok(bytes.len()), "{name}");
let json = serde_json::to_string(value).expect("a value serializes to JSON");
assert_eq!(serde_json::from_str::<Value>(&json).as_ref().ok(), Some(value), "{json}");
let wire = postcard::to_allocvec(value).expect("a value serializes to postcard");
assert_eq!(postcard::from_bytes::<Value>(&wire).as_ref().ok(), Some(value), "{name}");
bytes
}
fn walk(fdd: &Fdd, seed: u64) -> usize {
let codec = FomCodec::new(fdd).expect("the FDD resolves");
let mut sampler = Sampler::new(fdd, seed);
for data_type in fdd.data_types() {
let name = data_type.name();
assert_eq!(codec.raw_reason(name), None, "{name} must resolve");
assert!(codec.has_data_type(name));
for _ in 0..25 {
let value = sampler.sample(name);
let bytes = round_trip(&codec, name, &value);
for cut in 0..bytes.len() {
if let Ok((_, used)) = codec.decode_prefix(name, &bytes[..cut]) {
assert!(used <= cut, "{name}");
}
}
}
}
fdd.data_types().len()
}
#[test]
fn every_data_type_of_the_standard_mim_round_trips() {
let fdd = Fdd::with_standard_mim();
let count = walk(&fdd, 0x9e37_79b9_7f4a_7c15);
assert!(count >= 79, "the MIM has {count} data types");
let codec = FomCodec::new(&fdd).unwrap();
assert_eq!(codec.data_type_names().count(), count);
assert!(fdd.data_types().iter().all(|data_type| !matches!(data_type, DataType::VariantRecord(_))));
}
#[test]
fn every_mom_attribute_and_parameter_round_trips() {
let fdd = Fdd::with_standard_mim();
let codec = FomCodec::new(&fdd).unwrap();
let mut sampler = Sampler::new(&fdd, 0x0123_4567_89ab_cdef);
for attribute in fdd.attributes() {
let data_type = attribute.data_type.as_deref().expect("every MOM attribute has a data type");
assert_eq!(codec.attribute_data_type(attribute.id), Some(data_type));
for _ in 0..10 {
let value = sampler.sample(data_type);
let bytes = codec.encode_attribute(attribute.id, &value).unwrap();
assert_eq!(
codec.decode_attribute(attribute.id, &bytes).as_ref(),
Ok(&value),
"{}",
attribute.name
);
assert_eq!(codec.encode(data_type, &value), Ok(bytes));
}
}
for parameter in fdd.parameters() {
let data_type = parameter.data_type.as_deref().expect("every MOM parameter has a data type");
assert_eq!(codec.parameter_data_type(parameter.id), Some(data_type));
for _ in 0..10 {
let value = sampler.sample(data_type);
let bytes = codec.encode_parameter(parameter.id, &value).unwrap();
assert_eq!(
codec.decode_parameter(parameter.id, &bytes).as_ref(),
Ok(&value),
"{}",
parameter.name
);
assert_eq!(codec.encode(data_type, &value), Ok(bytes));
}
}
assert!(fdd.attributes().len() >= 59, "{} attributes", fdd.attributes().len());
assert!(fdd.parameters().len() >= 126, "{} parameters", fdd.parameters().len());
}
fn argument_list() -> (Value, Vec<u8>) {
let argument = |kind: (&str, i32), name: &str, value: &str| {
Value::record([
("HLAargumentType", Value::enumerator_with(kind.0, kind.1)),
("HLAargumentName", Value::from(name)),
("HLAargumentValue", Value::from(value)),
])
};
let list = Value::array([
argument(("AttributeSetRegionSetPair", 3), "a", "b"),
argument(("AttributeSetRegionSetPairList", 4), "cd", ""),
]);
let mut expected = vec![0, 0, 0, 2];
expected.extend([0, 0, 0, 3]); expected.extend([0, 0, 0, 1, 0, 0x61, 0, 0]); expected.extend([0, 0, 0, 1, 0, 0x62, 0, 0]); expected.extend([0, 0, 0, 4]);
expected.extend([0, 0, 0, 2, 0, 0x63, 0, 0x64]); expected.extend([0, 0, 0, 0]); (list, expected)
}
#[test]
fn mom_attributes_have_the_expected_octets() {
let fdd = Fdd::with_standard_mim();
let codec = FomCodec::new(&fdd).unwrap();
let federate = "HLAmanager.HLAfederate";
let federation = "HLAmanager.HLAfederation";
let cases: Vec<(&str, &str, Value, Vec<u8>)> = vec![
("HLAobjectRoot", "HLAprivilegeToDeleteObject", Value::Bytes(vec![]), vec![]),
(federate, "HLAfederateHandle", Value::handle([0u8, 0, 0, 7]), vec![0, 0, 0, 4, 0, 0, 0, 7]),
(federate, "HLAfederateName", Value::from("Fed"), vec![0, 0, 0, 3, 0, 0x46, 0, 0x65, 0, 0x64]),
(
federate,
"HLAFOMmoduleDesignatorList",
Value::array(["a", "bc"]),
vec![0, 0, 0, 2, 0, 0, 0, 1, 0, 0x61, 0, 0, 0, 0, 0, 2, 0, 0x62, 0, 0x63],
),
(federate, "HLAtimeConstrained", Value::Bool(true), vec![0, 0, 0, 1]),
(federate, "HLAasynchronousDelivery", Value::Bool(false), vec![0, 0, 0, 0]),
(
federate,
"HLAfederateState",
Value::enumerator_with("FederateRestoreInProgress", 5),
vec![0, 0, 0, 5],
),
(federate, "HLAtimeManagerState", Value::enumerator_with("TimeAdvancing", 1), vec![0, 0, 0, 1]),
(
federate,
"HLAlogicalTime",
Value::bytes(2.0f64.to_be_bytes()),
vec![0, 0, 0, 8, 0x40, 0, 0, 0, 0, 0, 0, 0],
),
(
federate,
"HLAlookahead",
Value::bytes(0.5f64.to_be_bytes()),
vec![0, 0, 0, 8, 0x3f, 0xe0, 0, 0, 0, 0, 0, 0],
),
(federate, "HLAGALT", Value::bytes(7i64.to_be_bytes()), vec![0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 7]),
(federate, "HLAROlength", Value::from(42), vec![0, 0, 0, 42]),
(federate, "HLAtimeGrantedTime", Value::from(250), vec![0, 0, 0, 250]),
(federate, "HLAserviceReporting", Value::enumerator_with("Enabled", 1), vec![0, 0, 0, 1]),
(federate, "HLAexceptionReporting", Value::enumerator_with("Disabled", 0), vec![0, 0, 0, 0]),
(federate, "HLAautomaticResignAction", Value::enumerator_with("NoAction", 5), vec![0, 0, 0, 5]),
(federate, "HLAreportServiceFile", Value::from(""), vec![0, 0, 0, 0]),
(
federation,
"HLAfederatesInFederation",
Value::array([Value::handle([0u8, 0, 0, 1]), Value::handle([0u8, 0, 0, 2])]),
vec![0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2],
),
(federation, "HLAfederatesInFederation", Value::Array(vec![]), vec![0, 0, 0, 0]),
(federation, "HLAlastSaveTime", Value::Bytes(vec![]), vec![0, 0, 0, 0]),
(federation, "HLAautoProvide", Value::enumerator_with("Enabled", 1), vec![0, 0, 0, 1]),
];
for (class, name, value, expected) in cases {
let id = attribute(&fdd, class, name);
assert_eq!(codec.encode_attribute(id, &value).as_deref(), Ok(expected.as_slice()), "{class}.{name}");
assert_eq!(codec.decode_attribute(id, &expected).as_ref(), Ok(&value), "{class}.{name}");
}
}
#[test]
fn mom_parameters_have_the_expected_octets() {
let fdd = Fdd::with_standard_mim();
let codec = FomCodec::new(&fdd).unwrap();
let subscription = |class: &[u8], active: bool| {
Value::record([("HLAinteractionClass", Value::handle(class)), ("HLAactive", Value::Bool(active))])
};
let class_count = |class: &[u8], count: i32| {
Value::record([("HLAobjectClass", Value::handle(class)), ("HLAcount", Value::from(count))])
};
let interaction_count = |class: &[u8], count: i32| {
Value::record([
("HLAinteractionClass", Value::handle(class)),
("HLAinteractionCount", Value::from(count)),
])
};
let counts = vec![0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 10];
let (arguments, argument_octets) = argument_list();
let cases: Vec<(&str, &str, Value, Vec<u8>)> = vec![
("HLAfederate", "HLAfederate", Value::handle([0u8, 0, 0, 3]), vec![0, 0, 0, 4, 0, 0, 0, 3]),
("HLAfederate.HLAadjust.HLAsetTiming", "HLAreportPeriod", Value::from(30), vec![0, 0, 0, 30]),
(
"HLAfederate.HLAadjust.HLAmodifyAttributeState",
"HLAobjectInstance",
Value::handle(3u64.to_be_bytes()),
vec![0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 3],
),
(
"HLAfederate.HLAadjust.HLAmodifyAttributeState",
"HLAattribute",
Value::handle([0u8, 0, 0, 12]),
vec![0, 0, 0, 4, 0, 0, 0, 12],
),
(
"HLAfederate.HLAadjust.HLAmodifyAttributeState",
"HLAattributeState",
Value::enumerator_with("Owned", 1),
vec![0, 0, 0, 1],
),
(
"HLAfederate.HLAadjust.HLAsetSwitches",
"HLAautomaticResignAction",
Value::enumerator_with("DeleteObjectInstances", 1),
vec![0, 0, 0, 1],
),
(
"HLAfederate.HLAreport.HLAreportObjectClassPublication",
"HLAattributeList",
Value::array([Value::handle([1u8, 2, 3]), Value::handle([4u8, 5, 6])]),
vec![0, 0, 0, 2, 0, 0, 0, 3, 1, 2, 3, 0, 0, 0, 0, 3, 4, 5, 6],
),
(
"HLAfederate.HLAreport.HLAreportInteractionPublication",
"HLAinteractionClassList",
Value::array([Value::handle([0u8, 0, 0, 5])]),
vec![0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 5],
),
(
"HLAfederate.HLAreport.HLAreportObjectClassSubscription",
"HLAmaxUpdateRate",
Value::from("Hi"),
vec![0, 0, 0, 2, 0, 0x48, 0, 0x69],
),
(
"HLAfederate.HLAreport.HLAreportInteractionSubscription",
"HLAinteractionClassList",
Value::array([subscription(&[0, 0, 0, 9], true), subscription(&[0xab, 0xcd], false)]),
vec![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],
),
(
"HLAfederate.HLAreport.HLAreportObjectInstancesUpdated",
"HLAobjectInstanceCounts",
Value::array([class_count(&[0, 0, 0, 1], 3), class_count(&[0, 0, 0, 2], 10)]),
counts.clone(),
),
(
"HLAfederate.HLAreport.HLAreportObjectInstancesUpdated",
"HLAobjectInstanceCounts",
Value::Array(vec![]),
vec![0, 0, 0, 0],
),
(
"HLAfederate.HLAreport.HLAreportInteractionsSent",
"HLAinteractionCounts",
Value::array([interaction_count(&[0, 0, 0, 1], 3), interaction_count(&[0, 0, 0, 2], 10)]),
counts,
),
(
"HLAfederate.HLAreport.HLAreportInteractionsSent",
"HLAtransportation",
Value::handle([0u8, 0, 0, 1]),
vec![0, 0, 0, 4, 0, 0, 0, 1],
),
(
"HLAfederate.HLAreport.HLAreportObjectInstanceInformation",
"HLAobjectInstance",
Value::handle(0x0102u64.to_be_bytes()),
vec![0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 1, 2],
),
(
"HLAfederate.HLAreport.HLAreportServiceInvocation",
"HLAserviceType",
Value::enumerator_with("TimeManagement", 4),
vec![0, 4], ),
(
"HLAfederate.HLAreport.HLAreportServiceInvocation",
"HLAsuppliedArguments",
arguments,
argument_octets,
),
(
"HLAfederate.HLAreport.HLAreportServiceInvocation",
"HLAreturnedArgument",
Value::record([
("HLAargumentType", Value::enumerator_with("Null", 34)),
("HLAargumentName", Value::from("")),
("HLAargumentValue", Value::from("")),
]),
vec![0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0],
),
(
"HLAfederate.HLAreport.HLAreportFederateLost",
"HLAtimeStamp",
Value::bytes(2.0f64.to_be_bytes()),
vec![0, 0, 0, 8, 0x40, 0, 0, 0, 0, 0, 0, 0],
),
(
"HLAfederate.HLAservice.HLAdeleteObjectInstance",
"HLAtag",
Value::bytes([1u8, 2, 3]),
vec![0, 0, 0, 3, 1, 2, 3],
),
(
"HLAfederate.HLAservice.HLAenableTimeRegulation",
"HLAlookahead",
Value::bytes(0.5f64.to_be_bytes()),
vec![0, 0, 0, 8, 0x3f, 0xe0, 0, 0, 0, 0, 0, 0],
),
(
"HLAfederate.HLAservice.HLAchangeAttributeOrderType",
"HLAsendOrder",
Value::enumerator_with("TimeStamp", 2),
vec![0, 0, 0, 2],
),
(
"HLAfederation.HLAreport.HLAreportSynchronizationPoints",
"HLAsyncPoints",
Value::array(["a", "bc"]),
vec![0, 0, 0, 2, 0, 0, 0, 1, 0, 0x61, 0, 0, 0, 0, 0, 2, 0, 0x62, 0, 0x63],
),
(
"HLAfederation.HLAreport.HLAreportSynchronizationPointStatus",
"HLAsyncPointFederates",
Value::array([Value::record([
("HLAfederate", Value::handle([0u8, 0, 0, 5])),
("HLAfederateSyncStatus", Value::enumerator_with("MovingToSyncPoint", 2)),
])]),
vec![0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 2],
),
(
"HLAfederation.HLAadjust.HLAsetSwitches",
"HLAautoProvide",
Value::enumerator_with("Disabled", 0),
vec![0, 0, 0, 0],
),
];
for (class, name, value, expected) in cases {
let id = parameter(&fdd, &format!("HLAmanager.{class}"), name);
assert_eq!(codec.encode_parameter(id, &value).as_deref(), Ok(expected.as_slice()), "{class}.{name}");
assert_eq!(codec.decode_parameter(id, &expected).as_ref(), Ok(&value), "{class}.{name}");
}
}
#[test]
fn class_maps_translate_between_names_and_handles() {
let fdd = Fdd::with_standard_mim();
let codec = FomCodec::new(&fdd).unwrap();
let report = fdd
.interaction_class_by_name("HLAmanager.HLAfederate.HLAreport.HLAreportServiceInvocation")
.expect("the class of the MIM");
let (arguments, argument_octets) = argument_list();
let values: BTreeMap<String, Value> = [
("HLAfederate", Value::handle([0u8, 0, 0, 1])), ("HLAservice", Value::from("joinFederationExecution")),
("HLAserviceType", Value::enumerator_with("FederationManagement", 0)),
("HLAsuccessIndicator", Value::Bool(true)),
("HLAsuppliedArguments", arguments),
("HLAexception", Value::from("")),
("HLAserialNumber", Value::from(17)),
]
.into_iter()
.map(|(name, value)| (name.to_owned(), value))
.collect();
let encoded = codec.encode_parameters(report, &values).unwrap();
assert_eq!(encoded.len(), values.len());
let arguments_id = fdd.parameter_by_name(report, "HLAsuppliedArguments").unwrap();
assert_eq!(encoded.get(&arguments_id), Some(&argument_octets));
let serial_id = fdd.parameter_by_name(report, "HLAserialNumber").unwrap();
assert_eq!(encoded.get(&serial_id), Some(&vec![0, 0, 0, 17]));
assert_eq!(codec.decode_parameters(report, &encoded), Ok(values));
let pairs = codec.encode_parameters(report, [("HLAserialNumber", Value::from(17))]).unwrap();
assert_eq!(pairs, BTreeMap::from([(serial_id, vec![0, 0, 0, 17])]));
let decoded = codec.decode_parameters(report, [(serial_id, [0u8, 0, 0, 18])]).unwrap();
assert_eq!(decoded, BTreeMap::from([("HLAserialNumber".to_owned(), Value::from(18))]));
let federation = fdd.object_class_by_name("HLAmanager.HLAfederation").expect("the class of the MIM");
let values: BTreeMap<String, Value> = [
("HLAfederationName", Value::from("Demo")),
("HLAfederatesInFederation", Value::array([Value::handle([0u8, 0, 0, 1])])),
("HLAFOMmoduleDesignatorList", Value::array(["Restaurant"])),
("HLAnextSaveTime", Value::bytes(1.0f64.to_be_bytes())),
("HLAautoProvide", Value::enumerator_with("Enabled", 1)),
("HLAprivilegeToDeleteObject", Value::Bytes(vec![])), ]
.into_iter()
.map(|(name, value)| (name.to_owned(), value))
.collect();
let encoded = codec.encode_attributes(federation, &values).unwrap();
assert_eq!(encoded.len(), values.len());
assert_eq!(codec.decode_attributes(federation, &encoded), Ok(values));
let federate_name = attribute(&fdd, "HLAmanager.HLAfederate", "HLAfederateName");
assert_eq!(
codec.encode_attributes(federation, [("HLAfederateName", Value::from("x"))]),
Err(CodecError::NotAMember {
kind: "an attribute",
class: "HLAobjectRoot.HLAmanager.HLAfederation".to_owned(),
member: "HLAfederateName".to_owned(),
})
);
assert!(matches!(
codec.decode_attributes(federation, [(federate_name, [0u8; 4])]),
Err(CodecError::NotAMember { kind: "an attribute", .. })
));
assert!(matches!(
codec.encode_parameters(report, [("HLAnoSuchParameter", Value::from(1))]),
Err(CodecError::NotAMember { kind: "a parameter", .. })
));
assert_eq!(
codec.encode_attributes(ObjectClassId(9999), [("x", Value::from(1))]),
Err(CodecError::UnknownHandle { kind: "object class", handle: 9999 })
);
assert_eq!(
codec.decode_attribute(AttributeId(9999), &[]),
Err(CodecError::UnknownHandle { kind: "attribute", handle: 9999 })
);
assert_eq!(
codec.encode_parameter(ParameterId(9999), &Value::from(1)),
Err(CodecError::UnknownHandle { kind: "parameter", handle: 9999 })
);
assert_eq!(
codec.decode("HLAnoSuchType", &[]),
Err(CodecError::UnknownDataType { name: "HLAnoSuchType".to_owned() })
);
assert_eq!(codec.octet_boundary("HLAnoSuchType"), None);
assert_eq!(codec.attribute_data_type(AttributeId(9999)), None);
let error = RtiError::from(codec.encode("HLAnoSuchType", &Value::from(1)).unwrap_err());
assert_eq!(error.kind, ExceptionKind::RTIinternalError);
}
hla_enumerated! {
enum SyncPointStatus: HLAinteger32BE {
NoActivity = 0,
AttemptingToRegisterSyncPoint = 1,
MovingToSyncPoint = 2,
WaitingForRestOfFederation = 3,
}
}
hla_fixed_record! {
struct InteractionSubscription {
interaction_class: HLAinteractionClassHandle,
active: bool as HLAboolean,
}
}
hla_fixed_record! {
struct ObjectClassBasedCount {
object_class: HLAobjectClassHandle,
count: i32 as HLAcount,
}
}
hla_fixed_record! {
struct SyncPointFederate {
federate: HLAfederateHandle,
status: SyncPointStatus,
}
}
hla_fixed_record! {
struct Argument {
argument_type: HLAinteger32BE,
name: String,
value: String,
}
}
fn same<T: Encode + ?Sized>(codec: &FomCodec, name: &str, value: &Value, typed: &T) {
let expected = encode_to_vec(typed);
assert_eq!(codec.encode(name, value).as_deref(), Ok(expected.as_slice()), "{name}: {value}");
assert_eq!(codec.decode(name, &expected).as_ref(), Ok(value), "{name}: {expected:?}");
}
fn octets(rng: &mut XorShift, max: usize) -> Vec<u8> {
let len = rng.below(max + 1);
rng.bytes(len)
}
fn text(rng: &mut XorShift, ascii: bool) -> String {
const ASCII: [char; 5] = ['a', 'B', '7', ' ', '~'];
const UNICODE: [char; 6] = ['a', '\u{e9}', '\u{4e2d}', '\u{1f600}', '\u{263a}', 'z'];
(0..rng.below(7)).map(|_| if ascii { ASCII[rng.below(5)] } else { UNICODE[rng.below(6)] }).collect()
}
#[test]
fn mim_data_types_match_the_typed_layer() {
let codec = FomCodec::new(&Fdd::with_standard_mim()).unwrap();
let mut rng = XorShift(0x1234_5678_9abc_def1);
let statuses = [
(SyncPointStatus::NoActivity, "NoActivity"),
(SyncPointStatus::AttemptingToRegisterSyncPoint, "AttemptingToRegisterSyncPoint"),
(SyncPointStatus::MovingToSyncPoint, "MovingToSyncPoint"),
(SyncPointStatus::WaitingForRestOfFederation, "WaitingForRestOfFederation"),
];
let argument_types =
[(3, "AttributeSetRegionSetPair"), (34, "Null"), (53, "String"), (62, "MessageRetractionReturn")];
for _ in 0..200 {
let handles: Vec<Vec<u8>> = (0..rng.below(5)).map(|_| octets(&mut rng, 9)).collect();
let typed: Vec<HLAfederateHandle> =
handles.iter().map(|handle| HLAfederateHandle::new(handle.clone())).collect();
let value = Value::array(handles.iter().map(|handle| Value::handle(handle.clone())));
same(&codec, "HLAfederateHandleList", &value, &typed);
same(&codec, "HLAfederateReferenceList", &value, &typed);
same(&codec, "HLAattributeHandleList", &value, &typed);
let flags: Vec<bool> = handles.iter().map(|_| rng.below(2) == 1).collect();
let typed: Vec<InteractionSubscription> = handles
.iter()
.zip(&flags)
.map(|(handle, active)| InteractionSubscription {
interaction_class: HLAinteractionClassHandle::new(handle.clone()),
active: *active,
})
.collect();
let value = Value::array(handles.iter().zip(&flags).map(|(handle, active)| {
Value::record([
("HLAinteractionClass", Value::handle(handle.clone())),
("HLAactive", Value::Bool(*active)),
])
}));
same(&codec, "HLAinteractionSubList", &value, &typed);
let counts: Vec<i32> = handles.iter().map(|_| rng.next() as i32).collect();
let typed: Vec<ObjectClassBasedCount> = handles
.iter()
.zip(&counts)
.map(|(handle, count)| ObjectClassBasedCount {
object_class: HLAobjectClassHandle::new(handle.clone()),
count: *count,
})
.collect();
let value = Value::array(handles.iter().zip(&counts).map(|(handle, count)| {
Value::record([
("HLAobjectClass", Value::handle(handle.clone())),
("HLAcount", Value::from(*count)),
])
}));
same(&codec, "HLAobjectClassBasedCounts", &value, &typed);
let picks: Vec<usize> = handles.iter().map(|_| rng.below(4)).collect();
let typed: Vec<SyncPointFederate> = handles
.iter()
.zip(&picks)
.map(|(handle, pick)| SyncPointFederate {
federate: HLAfederateHandle::new(handle.clone()),
status: statuses[*pick].0,
})
.collect();
let value = Value::array(handles.iter().zip(&picks).map(|(handle, pick)| {
Value::record([
("HLAfederate", Value::handle(handle.clone())),
(
"HLAfederateSyncStatus",
Value::enumerator_with(statuses[*pick].1, statuses[*pick].0.value()),
),
])
}));
same(&codec, "HLAsyncPointFederateList", &value, &typed);
let arguments: Vec<(usize, String, String)> =
(0..rng.below(4)).map(|_| (rng.below(4), text(&mut rng, false), text(&mut rng, false))).collect();
let typed: Vec<Argument> = arguments
.iter()
.map(|(pick, name, value)| Argument {
argument_type: HLAinteger32BE(argument_types[*pick].0),
name: name.clone(),
value: value.clone(),
})
.collect();
let value = Value::array(arguments.iter().map(|(pick, name, value)| {
Value::record([
("HLAargumentType", Value::enumerator_with(argument_types[*pick].1, argument_types[*pick].0)),
("HLAargumentName", Value::from(name.as_str())),
("HLAargumentValue", Value::from(value.as_str())),
])
}));
same(&codec, "HLAargumentList", &value, &typed);
let labels: Vec<String> = (0..rng.below(4)).map(|_| text(&mut rng, false)).collect();
same(&codec, "HLAsyncPointList", &Value::array(labels.clone()), &labels);
same(&codec, "HLAmoduleDesignatorList", &Value::array(labels.clone()), &labels);
let unicode = text(&mut rng, false);
same(&codec, "HLAunicodeString", &Value::from(unicode.as_str()), &unicode);
same(
&codec,
"HLAupdateRateName",
&Value::from(unicode.as_str()),
&HLAupdateRateName::new(unicode.as_str()),
);
let ascii = text(&mut rng, true);
same(
&codec,
"HLAASCIIstring",
&Value::from(ascii.as_str()),
&HLAASCIIstring::new(ascii.as_str()).unwrap(),
);
let opaque = octets(&mut rng, 12);
same(&codec, "HLAopaqueData", &Value::bytes(opaque.clone()), &HLAopaqueData::new(opaque.clone()));
same(&codec, "HLAlogicalTime", &Value::bytes(opaque.clone()), &HLAlogicalTime::new(opaque.clone()));
same(&codec, "HLAtimeInterval", &Value::bytes(opaque.clone()), &HLAlogicalTimeInterval::new(opaque));
let number = rng.next();
same(&codec, "HLAcount", &Value::from(number as i32), &HLAcount::new(number as i32));
same(
&codec,
"HLAnormalizedFederateHandle",
&Value::from(number as i64),
&HLAinteger64BE(number as i64),
);
let float = f64::from(number as i32) / 64.0;
same(&codec, "HLAfloat64Time", &Value::from(float), &HLAfloat64BE(float));
same(&codec, "HLAboolean", &Value::Bool(number & 1 == 1), &HLAboolean(number & 1 == 1));
same(&codec, "HLAbyte", &Value::Octet(number as u8), &HLAbyte(number as u8));
}
same(&codec, "HLAtoken", &Value::Bytes(vec![]), &HLAtoken::default());
for name in ["HLAcount", "HLAboolean", "HLAunicodeString", "HLAinteractionSubList", "HLAargumentList"] {
assert_eq!(codec.octet_boundary(name), Some(4), "{name}");
}
assert_eq!(codec.octet_boundary("HLAnormalizedFederateHandle"), Some(8));
assert_eq!(codec.octet_boundary("HLAserviceTypeEnum"), Some(2));
assert_eq!(codec.octet_boundary("HLAtoken"), Some(1));
}
hla_enumerated! {
enum Unit: HLAoctet {
Unknown = 0,
Exact = 1,
Estimated = 2,
}
}
hla_variant_record! {
enum Quantity: Unit {
Unknown = Unit::Unknown,
Exact(f64 as HLAfloat64BE) = Unit::Exact,
Estimated(HLAboolean) = Unit::Estimated,
}
}
hla_enumerated! {
enum GarnishKind: HLAinteger32BE {
Salt = 1,
Olives = 2,
Nothing = 3,
}
}
hla_extendable_variant_record! {
enum Garnish: GarnishKind {
HasSaltRim(HLAboolean) = GarnishKind::Salt,
OliveWeight(f64 as HLAfloat64BE) = GarnishKind::Olives,
Nothing = GarnishKind::Nothing,
}
}
hla_fixed_record! {
struct Wide {
flag: HLAoctet,
value: HLAfloat64BE,
}
}
hla_fixed_record! {
struct Mixed {
tag: HLAoctet,
quantity: Quantity,
little: i64 as HLAinteger64LE,
short: u16 as HLAunsignedInteger16LE,
ratio: f32 as HLAfloat32LE,
label: HLAASCIIstring,
marks: Vec<i16> as VariableArrayOf<HLAinteger16BE>,
position: [f64; 2] as FixedArrayOf<HLAfloat64BE>,
wides: Vec<Wide>,
grid: [[HLAinteger16LE; 3]; 2],
garnish: Garnish,
name: String,
initial: HLAASCIIchar,
letter: HLAunicodeChar,
code: [HLAASCIIchar; 3],
token: [HLAbyte; 0],
blob: HLAopaqueData,
garnishes: Vec<Garnish>,
}
}
fn mixed_tables() -> Tables {
Tables::default()
.enumerated("Unit", "HLAoctet", &[("Unknown", 0), ("Exact", 1), ("Estimated", 2)])
.enumerated("GarnishKind", "HLAinteger32BE", &[("Salt", 1), ("Olives", 2), ("Nothing", 3)])
.array("Marks", "HLAinteger16BE", "Dynamic", "HLAvariableArray")
.array("Position", "HLAfloat64BE", "2", "HLAfixedArray")
.array("Wides", "Wide", "Dynamic", "HLAvariableArray")
.array("Grid", "HLAinteger16LE", "2,3", "HLAfixedArray")
.array("Code", "HLAASCIIchar", "3", "HLAfixedArray")
.array("Garnishes", "Garnish", "Dynamic", "HLAvariableArray")
.record("Wide", "HLAfixedRecord", &[("Flag", "HLAoctet"), ("Value", "HLAfloat64BE")])
.record(
"Mixed",
"HLAfixedRecord",
&[
("Tag", "HLAoctet"),
("Quantity", "Quantity"),
("Little", "HLAinteger64LE"),
("Short", "HLAunsignedInteger16LE"),
("Ratio", "HLAfloat32LE"),
("Label", "HLAASCIIstring"),
("Marks", "Marks"),
("Position", "Position"),
("Wides", "Wides"),
("Grid", "Grid"),
("Garnish", "Garnish"),
("Name", "HLAunicodeString"),
("Initial", "HLAASCIIchar"),
("Letter", "HLAunicodeChar"),
("Code", "Code"),
("Token", "HLAtoken"),
("Blob", "HLAopaqueData"),
("Garnishes", "Garnishes"),
],
)
.variant(
"Quantity",
"HLAvariantRecord",
("Unit", "Unit"),
&[("Unknown", "", ""), ("Exact", "Exact", "HLAfloat64BE"), ("Estimated", "Guess", "HLAboolean")],
)
.variant(
"Garnish",
"HLAextendableVariantRecord",
("Kind", "GarnishKind"),
&[
("Salt", "HasSaltRim", "HLAboolean"),
("Olives", "OliveWeight", "HLAfloat64BE"),
("Nothing", "", ""),
],
)
}
fn sample_quantity(rng: &mut XorShift) -> (Quantity, Value) {
match rng.below(3) {
0 => (Quantity::Unknown, Value::variant(Enumerator::new("Unknown", 0), None)),
1 => {
let exact = f64::from(rng.next() as i32) / 8.0;
(Quantity::Exact(exact), Value::variant_named(Enumerator::new("Exact", 1), "Exact", exact))
}
_ => {
let guess = rng.below(2) == 1;
let value = Value::variant_named(Enumerator::new("Estimated", 2), "Guess", guess);
(Quantity::Estimated(HLAboolean(guess)), value)
}
}
}
fn sample_garnish(rng: &mut XorShift) -> (Garnish, Value) {
match rng.below(3) {
0 => {
let rim = rng.below(2) == 1;
let value = Value::variant_named(Enumerator::new("Salt", 1), "HasSaltRim", rim);
(Garnish::HasSaltRim(HLAboolean(rim)), value)
}
1 => {
let weight = f64::from(rng.next() as i16) / 16.0;
let value = Value::variant_named(Enumerator::new("Olives", 2), "OliveWeight", weight);
(Garnish::OliveWeight(weight), value)
}
_ => (Garnish::Nothing, Value::variant(Enumerator::new("Nothing", 3), None)),
}
}
fn sample_mixed(rng: &mut XorShift) -> (Mixed, Value) {
let tag = rng.next() as u8;
let (quantity, quantity_value) = sample_quantity(rng);
let little = rng.next() as i64;
let short = rng.next() as u16;
let ratio = f32::from(rng.next() as i16) / 4.0;
let label = text(rng, true);
let marks: Vec<i16> = (0..rng.below(4)).map(|_| rng.next() as i16).collect();
let position = [f64::from(rng.next() as i32), -0.5];
let wides: Vec<(u8, f64)> =
(0..rng.below(3)).map(|_| (rng.next() as u8, f64::from(rng.next() as i32))).collect();
let grid: [[i16; 3]; 2] = std::array::from_fn(|_| std::array::from_fn(|_| rng.next() as i16));
let (garnish, garnish_value) = sample_garnish(rng);
let name = text(rng, false);
let blob = octets(rng, 6);
let garnishes: Vec<(Garnish, Value)> = (0..rng.below(3)).map(|_| sample_garnish(rng)).collect();
let typed = Mixed {
tag: HLAoctet(tag),
quantity,
little,
short,
ratio,
label: HLAASCIIstring::new(label.clone()).unwrap(),
marks: marks.clone(),
position,
wides: wides
.iter()
.map(|&(flag, value)| Wide { flag: HLAoctet(flag), value: HLAfloat64BE(value) })
.collect(),
grid: grid.map(|row| row.map(HLAinteger16LE)),
garnish,
name: name.clone(),
initial: HLAASCIIchar(b'x'),
letter: HLAunicodeChar(0x263a),
code: [HLAASCIIchar(b'a'), HLAASCIIchar(b'b'), HLAASCIIchar(b'c')],
token: [],
blob: HLAopaqueData::new(blob.clone()),
garnishes: garnishes.iter().map(|(typed, _)| typed.clone()).collect(),
};
let value = Value::record([
("Tag", Value::Octet(tag)),
("Quantity", quantity_value),
("Little", Value::from(little)),
("Short", Value::from(short)),
("Ratio", Value::from(ratio)),
("Label", Value::from(label)),
("Marks", Value::array(marks)),
("Position", Value::array(position)),
(
"Wides",
Value::array(wides.iter().map(|&(flag, value)| {
Value::record([("Flag", Value::Octet(flag)), ("Value", Value::Float(value))])
})),
),
("Grid", Value::array(grid.map(Value::array))),
("Garnish", garnish_value),
("Name", Value::from(name)),
("Initial", Value::Char('x')),
("Letter", Value::Char('\u{263a}')),
("Code", Value::from("abc")),
("Token", Value::Bytes(vec![])),
("Blob", Value::bytes(blob)),
("Garnishes", Value::array(garnishes.into_iter().map(|(_, value)| value))),
]);
(typed, value)
}
#[test]
fn constructed_data_types_match_the_typed_layer() {
let fdd = mixed_tables().fdd();
let codec = FomCodec::new(&fdd).unwrap();
assert_eq!(codec.octet_boundary("Mixed"), Some(Mixed::OCTET_BOUNDARY));
assert_eq!(codec.octet_boundary("Quantity"), Some(Quantity::OCTET_BOUNDARY));
assert_eq!(codec.octet_boundary("Garnish"), Some(Garnish::OCTET_BOUNDARY));
assert_eq!(codec.octet_boundary("Wides"), Some(<Vec<Wide> as Encode>::OCTET_BOUNDARY));
assert_eq!(codec.octet_boundary("Grid"), Some(2));
assert_eq!(codec.octet_boundary("Code"), Some(1));
let mut rng = XorShift(0x0bad_cafe_1234_5678);
for _ in 0..300 {
let (typed, value) = sample_mixed(&mut rng);
same(&codec, "Mixed", &value, &typed);
let (quantity, quantity_value) = sample_quantity(&mut rng);
same(&codec, "Quantity", &quantity_value, &quantity);
let (garnish, garnish_value) = sample_garnish(&mut rng);
same(&codec, "Garnish", &garnish_value, &garnish);
}
walk(&fdd, 0x5151_5151_5151_5151);
let (typed, value) = sample_mixed(&mut rng);
let Value::Record(mut fields) = value else { panic!("a record") };
fields.reverse();
for (name, field) in &mut fields {
if name == "Quantity" {
*field = Value::variant("Exact", Some(Value::from(3)));
}
}
let expected = Mixed { quantity: Quantity::Exact(3.0), ..typed };
assert_eq!(codec.encode("Mixed", &Value::Record(fields)), Ok(encode_to_vec(&expected)));
assert_eq!(
codec.encode("Garnish", &Value::variant(Enumerator::numbered(3), None)),
Ok(encode_to_vec(&Garnish::Nothing))
);
}
hla_enumerated! {
enum ExperienceLevel: HLAinteger32BE {
Trainee = 0,
Apprentice = 1,
Journeyman = 2,
Senior = 3,
Temporary = 4,
Master = 5,
}
}
hla_variant_record! {
enum ServerValue: ExperienceLevel {
CoursePassed(HLAboolean) = ExperienceLevel::Trainee,
TempAgency(String) = ExperienceLevel::Temporary,
ApprenticeRating(i32 as HLAinteger32BE) = ExperienceLevel::Apprentice,
JourneymanRating(i32 as HLAinteger32BE) = ExperienceLevel::Journeyman,
SeniorRating(i32 as HLAinteger32BE) = ExperienceLevel::Senior,
MasterRating(i32 as HLAinteger32BE) = ExperienceLevel::Master,
}
}
hla_extendable_variant_record! {
enum DrinkGarnish: HLAinteger32BE {
HasSaltRim(HLAboolean) = HLAinteger32BE(1),
OliveCount(i32 as HLAinteger32BE) = HLAinteger32BE(2),
ExtraWhippedCream(HLAboolean) = HLAinteger32BE(3),
}
}
#[test]
fn every_data_type_of_the_restaurant_fom_round_trips() {
let base = base_restaurant_fdd();
let extended = restaurant_fdd();
let base_count = walk(&base, 0x2545_f491_4f6c_dd1d);
let extended_count = walk(&extended, 0x2545_f491_4f6c_dd1d);
assert_eq!(base_count, Fdd::with_standard_mim().data_types().len() + 24);
assert_eq!(extended_count, base_count + 2);
let codec = FomCodec::new(&extended).unwrap();
let mut sampler = Sampler::new(&extended, 99);
for class in extended.object_classes() {
let values: BTreeMap<String, Value> = class
.attribute_by_name
.iter()
.map(|(name, id)| {
let data_type = extended.attribute(*id).and_then(|attribute| attribute.data_type.as_deref());
(name.clone(), sampler.sample(data_type.expect("a data type")))
})
.collect();
let encoded = codec.encode_attributes(class.id, &values).unwrap();
assert_eq!(encoded.len(), class.attributes.len());
assert_eq!(codec.decode_attributes(class.id, &encoded), Ok(values), "{}", class.qualified_name);
}
for class in extended.interaction_classes() {
let values: BTreeMap<String, Value> = class
.parameter_by_name
.iter()
.map(|(name, id)| {
let data_type = extended.parameter(*id).and_then(|parameter| parameter.data_type.as_deref());
(name.clone(), sampler.sample(data_type.expect("a data type")))
})
.collect();
let encoded = codec.encode_parameters(class.id, &values).unwrap();
assert_eq!(codec.decode_parameters(class.id, &encoded), Ok(values), "{}", class.qualified_name);
}
let soda = extended.object_class_by_name("Food.Drink.Soda").expect("the Soda class");
let organic =
codec.encode_attributes(soda, [("Organic", Value::Bool(true)), ("NumberCups", Value::from(513))]);
let organic = organic.unwrap();
assert_eq!(organic.get(&attribute(&extended, "Food.Drink.Soda", "Organic")), Some(&vec![0, 0, 0, 1]));
assert_eq!(organic.get(&attribute(&extended, "Food.Drink", "NumberCups")), Some(&vec![2, 1]));
}
#[test]
fn restaurant_values_have_the_expected_octets() {
let codec = FomCodec::new(&restaurant_fdd()).unwrap();
let check = |name: &str, value: Value, expected: &[u8]| {
assert_eq!(codec.encode(name, &value).as_deref(), Ok(expected), "{name}: {value}");
assert_eq!(codec.decode(name, expected).as_ref(), Ok(&value), "{name}");
};
check("DrinkCount", Value::from(513), &[2, 1]);
check("DrinkCount", Value::from(65_535), &[0xff, 0xff]);
for outside in [-1, 65_536] {
let error = codec.encode("DrinkCount", &Value::from(outside)).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
}
check("DollarRate", Value::from(9.5), &[0x41, 0x18, 0, 0]);
check("Years", Value::from(-2), &[0xff, 0xff, 0xff, 0xfe]);
check("FlavorType", Value::enumerator_with("Cola", 101), &[0, 0, 0, 101]);
check("Preparation", Value::Bool(true), &[0, 0, 0, 1]);
check("EmployeeReference", Value::from("Joe"), &[0, 0, 0, 3, 0, 0x4a, 0, 0x6f, 0, 0x65]);
check(
"ServiceStat",
Value::record([("EntreeOk", true), ("Veggy1Ok", false), ("Veggy2Ok", true)]),
&[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
);
let mut address = vec![0, 0, 0, 2, b'J', b'o', 0, 0];
address.extend([0, 0, 0, 3, b'1', b' ', b'A', 0]);
address.extend([0, 0, 0, 0]);
address.extend([0, 0, 0, 2, b'N', b'Y', 0, 0]);
address.extend([0, 0, 0, 5, b'1', b'2', b'3', b'4', b'5']);
let joe =
Value::record([("Name", "Jo"), ("Street", "1 A"), ("City", ""), ("State", "NY"), ("Zip", "12345")]);
check("AddressType", joe.clone(), &address);
let mut book = vec![0, 0, 0, 2];
book.extend(&address);
book.extend([0, 0, 0]); book.extend(&address);
check("AddressBook", Value::array([joe.clone(), joe]), &book);
let employees: Vec<u8> = (1..=10u8).flat_map(|id| [0, 0, 0, id]).collect();
check("Employees", Value::array(1..=10), &employees);
check("Ingredients", Value::array(["a"]), &[0, 0, 0, 1, 0, 0, 0, 1, 0, 0x61]);
let trainee = Value::variant_named(Enumerator::new("Trainee", 0), "CoursePassed", true);
check("ServerValue", trainee.clone(), &[0, 0, 0, 0, 0, 0, 0, 1]);
same(&codec, "ServerValue", &trainee, &ServerValue::CoursePassed(HLAboolean(true)));
let temporary = Value::variant_named(Enumerator::new("Temporary", 4), "TempAgency", "ab");
check("ServerValue", temporary.clone(), &[0, 0, 0, 4, 0, 0, 0, 2, 0, 0x61, 0, 0x62]);
same(&codec, "ServerValue", &temporary, &ServerValue::TempAgency("ab".to_owned()));
let senior = Value::variant_named(Enumerator::new("Senior", 3), "Rating", 7);
check("ServerValue", senior.clone(), &[0, 0, 0, 3, 0, 0, 0, 7]);
same(&codec, "ServerValue", &senior, &ServerValue::SeniorRating(7));
let ratings = [
("Apprentice", ServerValue::ApprenticeRating(-1)),
("Journeyman", ServerValue::JourneymanRating(-1)),
("Master", ServerValue::MasterRating(-1)),
];
for (number, (name, typed)) in [1, 2, 5].into_iter().zip(ratings) {
same(
&codec,
"ServerValue",
&Value::variant_named(Enumerator::new(name, number), "Rating", -1),
&typed,
);
}
assert_eq!(senior.field("Rating"), Some(&Value::from(7)));
assert_eq!(senior.to_string(), "Senior(3){Rating: 7}");
let olives = Value::variant_named(Enumerator::new("DryMartini", 2), "OliveCount", 3);
check("DrinkGarnish", olives.clone(), &[0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]);
same(&codec, "DrinkGarnish", &olives, &DrinkGarnish::OliveCount(3));
let salt = Value::variant_named(Enumerator::new("Margarita", 1), "HasSaltRim", true);
check("DrinkGarnish", salt.clone(), &[0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 1]);
same(&codec, "DrinkGarnish", &salt, &DrinkGarnish::HasSaltRim(HLAboolean(true)));
check("DrinkType", Value::enumerator_with("IrishCoffee", 3), &[0, 0, 0, 3]);
let cream = Value::variant_named(Enumerator::new("IrishCoffee", 3), "ExtraWhippedCream", true);
check("DrinkGarnish", cream.clone(), &[0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1]);
same(&codec, "DrinkGarnish", &cream, &DrinkGarnish::ExtraWhippedCream(HLAboolean(true)));
assert_eq!(codec.octet_boundary("DrinkGarnish"), Some(8));
assert_eq!(codec.octet_boundary("ServerValue"), Some(4));
let wrong_name = Value::variant_named("Margarita", "OliveCount", true);
let wrong_type = Value::variant_named("Margarita", "HasSaltRim", "yes");
let missing = Value::variant("Margarita", None);
let unknown = Value::variant("Mojito", Some(Value::Bool(true)));
for (value, path) in [
(wrong_name, "DrinkGarnish"),
(wrong_type, "DrinkGarnish.HasSaltRim"),
(missing, "DrinkGarnish"),
(unknown, "DrinkGarnish.DrinkType"),
] {
let error = codec.encode("DrinkGarnish", &value).unwrap_err();
assert_eq!(error.path(), Some(path), "{error}");
}
}
#[test]
fn a_codec_without_the_extension_module_passes_unknown_alternatives_on() {
let base = FomCodec::new(&base_restaurant_fdd()).unwrap();
let extended = FomCodec::new(&restaurant_fdd()).unwrap();
let cream = Value::variant_named(Enumerator::new("IrishCoffee", 3), "ExtraWhippedCream", true);
let bytes = extended.encode("DrinkGarnish", &cream).unwrap();
let passed = base.decode("DrinkGarnish", &bytes).unwrap();
assert_eq!(passed, Value::variant(Enumerator::numbered(3), Some(Value::raw([0u8, 0, 0, 1]))));
assert_eq!(passed.to_string(), "?(3){raw(0x00000001)}");
assert_eq!(base.encode("DrinkGarnish", &passed), Ok(bytes));
let empty = base.decode("DrinkGarnish", &[0, 0, 0, 9, 0, 0, 0, 0]).unwrap();
assert_eq!(empty, Value::variant(Enumerator::numbered(9), None));
assert_eq!(base.encode("DrinkGarnish", &empty), Ok(vec![0, 0, 0, 9, 0, 0, 0, 0]));
let typed = Value::variant(Enumerator::numbered(3), Some(Value::Bool(true)));
assert!(matches!(
base.encode("DrinkGarnish", &typed).unwrap_err().reason(),
Some(Reason::Alternative { .. })
));
assert!(matches!(
base.encode("DrinkGarnish", &cream).unwrap_err().reason(),
Some(Reason::UnknownEnumerator { .. })
));
assert_eq!(base.decode("DrinkType", &[0, 0, 0, 3]), Ok(Value::enumerator_value(3)));
for value in [Value::enumerator_value(3), Value::from(3), Value::enumerator("IrishCoffee")] {
let error = base.encode("DrinkType", &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
}
assert_eq!(extended.encode("DrinkType", &Value::from(3)), Ok(vec![0, 0, 0, 3]));
let rated = base.decode("ServerValue", &[0, 0, 0, 77, 0, 0, 0, 5]).unwrap();
let expected = VariantValue {
discriminant: Enumerator::numbered(77),
alternative: Some("Rating".to_owned()),
value: Some(Value::from(5)),
};
assert_eq!(rated.as_variant(), Some(&expected));
}
#[test]
fn basic_representations_by_name() {
let codec = FomCodec::new(&Fdd::with_standard_mim()).unwrap();
let cases: Vec<(&str, Value, Vec<u8>)> = vec![
("HLAinteger16BE", Value::from(-2), vec![0xff, 0xfe]),
("HLAinteger16LE", Value::from(-2), vec![0xfe, 0xff]),
("HLAinteger32BE", Value::from(0x0102_0304), vec![1, 2, 3, 4]),
("HLAinteger32LE", Value::from(0x0102_0304), vec![4, 3, 2, 1]),
("HLAinteger64BE", Value::from(i64::MIN), vec![0x80, 0, 0, 0, 0, 0, 0, 0]),
("HLAinteger64LE", Value::from(-2i64), vec![0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
("HLAunsignedInteger8", Value::from(200), vec![200]),
("HLAunsignedInteger16BE", Value::from(0xfffe), vec![0xff, 0xfe]),
("HLAunsignedInteger16LE", Value::from(0xfffe), vec![0xfe, 0xff]),
("HLAunsignedInteger32BE", Value::from(0xffff_fffeu32), vec![0xff, 0xff, 0xff, 0xfe]),
("HLAunsignedInteger32LE", Value::from(0xffff_fffeu32), vec![0xfe, 0xff, 0xff, 0xff]),
(
"HLAunsignedInteger64BE",
Value::from(u64::MAX - 1),
vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe],
),
(
"HLAunsignedInteger64LE",
Value::from(u64::MAX - 1),
vec![0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
),
("HLAfloat32BE", Value::from(1.5), vec![0x3f, 0xc0, 0, 0]),
("HLAfloat32LE", Value::from(1.5), vec![0, 0, 0xc0, 0x3f]),
("HLAfloat64BE", Value::from(-2.0), vec![0xc0, 0, 0, 0, 0, 0, 0, 0]),
("HLAfloat64LE", Value::from(-2.0), vec![0, 0, 0, 0, 0, 0, 0, 0xc0]),
("HLAoctet", Value::Octet(0xab), vec![0xab]),
("HLAbyte", Value::Octet(7), vec![7]),
("HLAoctetPairBE", Value::from(0x1234), vec![0x12, 0x34]),
("HLAoctetPairLE", Value::from(0x1234), vec![0x34, 0x12]),
("HLAASCIIchar", Value::Char('a'), vec![0x61]),
("HLAunicodeChar", Value::Char('\u{e9}'), vec![0, 0xe9]),
("HLAindex", Value::from(3), vec![0, 0, 0, 3]),
("HLAinteger64Time", Value::from(9), vec![0, 0, 0, 0, 0, 0, 0, 9]),
];
for (name, value, expected) in cases {
assert_eq!(codec.encode(name, &value).as_deref(), Ok(expected.as_slice()), "{name}");
assert_eq!(codec.decode(name, &expected).as_ref(), Ok(&value), "{name}");
assert_eq!(codec.octet_boundary(name), Some(expected.len()), "{name}");
}
assert_eq!(codec.encode("HLAfloat64BE", &Value::from(-2)), Ok(vec![0xc0, 0, 0, 0, 0, 0, 0, 0]));
assert_eq!(codec.encode("HLAoctet", &Value::from(0xab)), Ok(vec![0xab]));
assert_eq!(codec.encode("HLAinteger16BE", &Value::Octet(7)), Ok(vec![0, 7]));
assert_eq!(codec.encode("HLAASCIIchar", &Value::from("a")), Ok(vec![0x61]));
let nan = codec.encode("HLAfloat32BE", &Value::Float(f64::NAN)).unwrap();
assert!(codec.decode("HLAfloat32BE", &nan).unwrap().as_f64().is_some_and(f64::is_nan));
assert_eq!(codec.encode("HLAfloat32LE", &Value::Float(f64::INFINITY)), Ok(vec![0, 0, 0x80, 0x7f]));
let outside: Vec<(&str, Value)> = vec![
("HLAinteger16BE", Value::from(32_768)),
("HLAinteger16LE", Value::from(-32_769)),
("HLAinteger64BE", Value::from(u64::MAX)),
("HLAunsignedInteger8", Value::from(256)),
("HLAunsignedInteger32BE", Value::from(-1)),
("HLAunsignedInteger64LE", Value::Integer(i128::from(u64::MAX) + 1)),
("HLAoctet", Value::from(256)),
("HLAfloat32BE", Value::from(1e300)),
("HLAASCIIchar", Value::Char('\u{e9}')),
("HLAunicodeChar", Value::Char('\u{1f600}')),
];
for (name, value) in outside {
let error = codec.encode(name, &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
assert!(matches!(error, CodecError::Encode(_)));
assert_eq!(RtiError::from(error).kind, ExceptionKind::CouldNotEncode);
}
let mismatched: Vec<(&str, Value)> = vec![
("HLAinteger32BE", Value::from("1")),
("HLAinteger32BE", Value::from(1.0)),
("HLAfloat64BE", Value::Bool(true)),
("HLAoctet", Value::bytes([1u8])),
("HLAASCIIchar", Value::from("ab")),
("HLAunicodeString", Value::from(1)),
("HLAopaqueData", Value::from("text")),
("HLAfederateHandleList", Value::handle([1u8])),
("HLAargument", Value::Array(vec![])),
("HLAboolean", Value::from(1.0)),
("HLAswitch", Value::Bool(true)),
];
for (name, value) in mismatched {
let error = codec.encode(name, &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::TypeMismatch { .. })), "{error}");
}
let error = codec.encode("HLAcount", &Value::from("1")).unwrap_err();
assert_eq!(
error.to_string(),
"cannot encode HLAcount at offset 0: expected an integer (HLAinteger32BE), found string"
);
for (name, bytes) in [
("HLAASCIIchar", vec![0x80]),
("HLAunicodeChar", vec![0xd8, 0]),
("HLAASCIIstring", vec![0, 0, 0, 2, 0x61, 0xff]),
("HLAunicodeString", vec![0, 0, 0, 1, 0xdc, 0]),
] {
let error = codec.decode(name, &bytes).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::InvalidValue { .. })), "{error}");
assert_eq!(RtiError::from(error).kind, ExceptionKind::CouldNotDecode);
}
let error = codec.decode("HLAASCIIstring", &[0, 0, 0, 2, 0x61, 0xff]).unwrap_err();
assert_eq!(error.offset(), Some(5));
let error = codec.encode("HLAASCIIstring", &Value::from("caf\u{e9}")).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
}
#[test]
fn basic_representations_by_size_endian_and_interpretation() {
let tables = Tables::default()
.basic("Fraction16", 16, "Unsigned fraction", "Little")
.basic("Celsius", 64, "Double-precision floating point number", "Little")
.basic("Delta8", 8, "Integer in the range [-128, 127]", "Big")
.basic("Flags8", 8, "8-bit value", "Big")
.basic("Level32", 32, "Signed level", "Little")
.basic("Pair16", 16, "16-bit value", "")
.basic("Wide128", 128, "Integer in the range [0, 2^128 - 1]", "Big")
.simple("Percent", "Fraction16")
.enumerated("Mood", "Delta8", &[("Bad", -1), ("Fine", 0), ("Good", 1)])
.array("Flags", "Flags8", "Dynamic", "HLAvariableArray")
.array("Wides", "Wide128", "Dynamic", "HLAvariableArray");
let codec = tables.codec();
let cases: Vec<(&str, Value, Vec<u8>)> = vec![
("Fraction16", Value::from(0x1234), vec![0x34, 0x12]),
("Percent", Value::from(0xffff), vec![0xff, 0xff]),
("Celsius", Value::from(1.5), 1.5f64.to_le_bytes().to_vec()),
("Delta8", Value::from(-1), vec![0xff]),
("Flags8", Value::Octet(0x80), vec![0x80]),
("Level32", Value::from(-2), vec![0xfe, 0xff, 0xff, 0xff]),
("Pair16", Value::from(0x0102), vec![1, 2]),
("Mood", Value::enumerator_with("Bad", -1), vec![0xff]),
("Mood", Value::enumerator_with("Good", 1), vec![1]),
("Flags", Value::bytes([1u8, 2]), vec![0, 0, 0, 2, 1, 2]),
];
for (name, value, expected) in cases {
assert_eq!(codec.encode(name, &value).as_deref(), Ok(expected.as_slice()), "{name}");
assert_eq!(codec.decode(name, &expected).as_ref(), Ok(&value), "{name}");
assert_eq!(codec.raw_reason(name), None);
}
for (name, value) in [("Delta8", 128i64), ("Delta8", -129), ("Fraction16", -1), ("Level32", 1 << 31)] {
let error = codec.encode(name, &Value::from(value)).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
}
assert_eq!(codec.raw_reason("Wide128"), None);
assert_eq!(codec.octet_boundary("Wide128"), Some(16));
let wide: Vec<u8> = (1..=16).collect();
assert_eq!(codec.decode("Wide128", &wide), Ok(Value::bytes(wide.clone())));
assert!(codec.decode("Wide128", &[1, 2, 3]).is_err());
assert_eq!(codec.raw_reason("Wides"), None);
let mut wides = vec![0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
wides.extend(&wide);
assert_eq!(codec.encode("Wides", &Value::array([Value::bytes(wide)])), Ok(wides));
}
#[test]
fn enumerators_by_name_and_by_number() {
let codec = FomCodec::new(&Fdd::with_standard_mim()).unwrap();
let advancing = vec![0, 0, 0, 1];
for value in [
Value::enumerator_with("TimeAdvancing", 1),
Value::enumerator("TimeAdvancing"),
Value::enumerator_value(1),
Value::from("TimeAdvancing"),
Value::from(1),
] {
assert_eq!(codec.encode("HLAtimeState", &value).as_ref(), Ok(&advancing), "{value}");
}
let decoded = codec.decode("HLAtimeState", &advancing).unwrap();
assert_eq!(decoded, Value::enumerator_with("TimeAdvancing", 1));
assert_eq!((decoded.as_str(), decoded.as_i64()), (Some("TimeAdvancing"), Some(1)));
assert_eq!(decoded.to_string(), "TimeAdvancing(1)");
let unknown = codec.decode("HLAfederateState", &[0, 0, 0, 2]).unwrap();
assert_eq!(unknown, Value::enumerator_value(2));
assert_eq!(unknown.to_string(), "?(2)");
for value in [
unknown,
Value::from(2),
Value::enumerator("Sleeping"),
Value::from("Sleeping"),
Value::enumerator_with("ActiveFederate", 3),
Value::Enum(Box::new(Enumerator { name: None, value: None })),
] {
let error = codec.encode("HLAfederateState", &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
}
let error = codec.encode("HLAfederateState", &Value::from("Sleeping")).unwrap_err();
assert_eq!(
error.to_string(),
"cannot encode HLAfederateState at offset 0: 'Sleeping' is not an enumerator of HLAfederateState"
);
for value in [Value::Bool(true), Value::enumerator("HLAtrue"), Value::from("HLAtrue"), Value::from(1)] {
assert_eq!(codec.encode("HLAboolean", &value), Ok(vec![0, 0, 0, 1]), "{value}");
}
assert_eq!(codec.decode("HLAboolean", &[0, 0, 0, 0]), Ok(Value::Bool(false)));
assert_eq!(codec.decode("HLAboolean", &[0, 0, 0, 7]), Ok(Value::enumerator_value(7)));
assert_eq!(codec.decode("HLAboolean", &[0, 0, 0, 7]).unwrap().as_bool(), None);
assert_eq!(codec.decode("HLAserviceTypeEnum", &[0xff, 0xff]), Ok(Value::enumerator_value(-1)));
let levels = FomCodec::new(&fdd_with(
"<dataTypes><basicDataRepresentations><basicData><name>U8</name><size>8</size>\
<interpretation>Integer in the range [0, 255]</interpretation><endian>Big</endian></basicData>\
</basicDataRepresentations><enumeratedDataTypes><enumeratedData><name>Level</name>\
<representation>HLAunsignedInteger8</representation>\
<enumerator><name>Low</name><value>1</value><value>2</value></enumerator>\
<enumerator><name>High</name><value>0x10</value></enumerator>\
</enumeratedData>\
<enumeratedData><name>Small</name><representation>U8</representation>\
<enumerator><name>Fits</name><value>255</value></enumerator>\
<enumerator><name>TooHigh</name><value>256</value></enumerator>\
</enumeratedData></enumeratedDataTypes></dataTypes>",
))
.unwrap();
assert_eq!(levels.encode("Level", &Value::enumerator("Low")), Ok(vec![1]));
assert_eq!(levels.encode("Level", &Value::enumerator_with("Low", 2)), Ok(vec![2]));
assert_eq!(levels.decode("Level", &[2]), Ok(Value::enumerator_with("Low", 2)));
assert_eq!(levels.decode("Level", &[16]), Ok(Value::enumerator_with("High", 16)));
for value in [Value::enumerator_with("Low", 3), Value::enumerator("TooHigh"), Value::from(256)] {
let error = levels.encode("Level", &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
}
assert_eq!(levels.encode("Small", &Value::enumerator("Fits")), Ok(vec![255]));
for value in [Value::enumerator("TooHigh"), Value::from(256)] {
let error = levels.encode("Small", &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
}
}
#[test]
fn arrays_follow_their_cardinality_and_encoding() {
let codec = Tables::default()
.array("Bounded", "HLAinteger16BE", "[1..3]", "HLAvariableArray")
.array("Pair", "HLAinteger32BE", "2", "HLAvariableArray")
.array("Matrix", "HLAinteger16LE", "2,3", "HLAfixedArray")
.array("Lines", "HLAunicodeChar", "2,3", "HLAfixedArray")
.array("Ragged", "HLAinteger16BE", "Dynamic,Dynamic", "HLAvariableArray")
.array("Tag", "HLAASCIIchar", "4", "HLAfixedArray")
.array("Digest", "HLAbyte", "4", "HLAfixedArray")
.array("Floats", "HLAfloat64BE", "Dynamic", "HLAvariableArray")
.array("Open", "HLAfloat64BE", "Dynamic", "HLAfixedArray")
.array("Odd", "HLAinteger32BE", "99999999999999999999999", "HLAvariableArray")
.codec();
let check = |name: &str, value: Value, expected: &[u8]| {
assert_eq!(codec.encode(name, &value).as_deref(), Ok(expected), "{name}: {value}");
assert_eq!(codec.decode(name, expected).as_ref(), Ok(&value), "{name}");
};
let out_of_range = |name: &str, value: Value, path: &str| {
let error = codec.encode(name, &value).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::OutOfRange { .. })), "{error}");
assert_eq!(error.path(), Some(path), "{error}");
};
check("Bounded", Value::array([1, 2]), &[0, 0, 0, 2, 0, 1, 0, 2]);
out_of_range("Bounded", Value::Array(vec![]), "Bounded");
out_of_range("Bounded", Value::array([1, 2, 3, 4]), "Bounded");
assert_eq!(codec.decode("Bounded", &[0, 0, 0, 0]), Ok(Value::Array(vec![])));
check("Pair", Value::array([1, 2]), &[0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2]);
out_of_range("Pair", Value::array([1, 2, 3]), "Pair");
let matrix = Value::array([Value::array([1, 2, 3]), Value::array([4, 5, 6])]);
check("Matrix", matrix, &[1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]);
out_of_range("Matrix", Value::array([Value::array([1, 2, 3]), Value::array([4, 5])]), "Matrix[1]");
out_of_range("Matrix", Value::array([Value::array([1, 2, 3])]), "Matrix");
check(
"Lines",
Value::array(["abc", "d\u{e9}f"]),
&[0, 0x61, 0, 0x62, 0, 0x63, 0, 0x64, 0, 0xe9, 0, 0x66],
);
out_of_range("Lines", Value::array(["abc", "de"]), "Lines[1]");
let ragged = vec![vec![HLAinteger16BE(1)], vec![HLAinteger16BE(2), HLAinteger16BE(3)]];
let expected = encode_to_vec(&ragged);
assert_eq!(expected.len(), 20);
check("Ragged", Value::array([Value::array([1]), Value::array([2, 3])]), &expected);
check("Tag", Value::from("abcd"), b"abcd");
out_of_range("Tag", Value::from("abc"), "Tag");
check("Digest", Value::bytes([1u8, 2, 3, 4]), &[1, 2, 3, 4]);
out_of_range("Digest", Value::bytes([1u8, 2, 3]), "Digest");
assert!(matches!(
codec.decode("Digest", &[1, 2, 3]).unwrap_err().reason(),
Some(Reason::Decoder(DecoderError::Truncated { offset: 0, needed: 4, remaining: 3 }))
));
check("Floats", Value::array([1.0]), &[0, 0, 0, 1, 0, 0, 0, 0, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
check("Floats", Value::Array(vec![]), &[0, 0, 0, 0]);
assert_eq!(codec.octet_boundary("Floats"), Some(8));
assert_eq!(codec.raw_reason("Open"), Some("HLAfixedArray needs a fixed cardinality, not 'Dynamic'"));
assert_eq!(codec.raw_reason("Odd"), Some("the cardinality '99999999999999999999999' is not understood"));
}
#[test]
fn user_defined_encodings_are_raw() {
let attribute = |name: &str, data_type: &str| {
format!(
"<attribute><name>{name}</name><dataType>{data_type}</dataType><updateType>Static</updateType>\
<updateCondition>NA</updateCondition><ownership>NoTransfer</ownership>\
<sharing>PublishSubscribe</sharing><transportation>HLAreliable</transportation>\
<order>Receive</order></attribute>"
)
};
let objects = format!(
"<objects><objectClass><name>HLAobjectRoot</name><objectClass><name>Thing</name>\
<sharing>PublishSubscribe</sharing>{}{}{}</objectClass></objectClass></objects>",
attribute("Untyped", "NA"),
attribute("Payload", "Zipped"),
attribute("Speed", "HLAfloat64BE"),
);
let tables = Tables::default()
.enumerated("WrapKind", "HLAinteger32BE", &[("Zip", 1)])
.array("Zipped", "HLAbyte", "Dynamic", "MyZip")
.array("Envelopes", "Envelope", "Dynamic", "HLAvariableArray")
.record("Envelope", "HLAfixedRecord", &[("Kind", "HLAinteger32BE"), ("Payload", "Zipped")])
.record("Broken", "HLAfixedRecord", &[("Payload", "Zipped"), ("Kind", "HLAinteger32BE")])
.record("Packed", "MyRecord", &[("A", "HLAinteger32BE")])
.record("Sealed", "HLAfixedRecord", &[("Wrapper", "Wrapper"), ("After", "HLAinteger32BE")])
.variant("Choice", "MyVariant", ("Kind", "WrapKind"), &[("Zip", "A", "HLAinteger32BE")])
.variant(
"Wrapper",
"HLAextendableVariantRecord",
("Kind", "WrapKind"),
&[("Zip", "Payload", "Zipped")],
);
let fdd = fdd_with(&format!("{objects}{}", tables.xml()));
let codec = FomCodec::new(&fdd).unwrap();
assert_eq!(codec.raw_reason("Zipped"), Some("the encoding 'MyZip' is user-defined"));
assert_eq!(codec.raw_reason("Packed"), Some("the encoding 'MyRecord' is user-defined"));
assert_eq!(codec.raw_reason("Choice"), Some("the encoding 'MyVariant' is user-defined"));
for name in ["Zipped", "Packed", "Choice", "Broken", "Envelopes"] {
assert!(codec.raw_reason(name).is_some(), "{name}");
assert_eq!(codec.decode(name, &[1, 2, 3]), Ok(Value::raw([1u8, 2, 3])), "{name}");
assert_eq!(codec.encode(name, &Value::raw([1u8, 2, 3])), Ok(vec![1, 2, 3]), "{name}");
assert_eq!(codec.decode(name, &[]), Ok(Value::Raw(vec![])), "{name}");
let error = codec.encode(name, &Value::from(1)).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::TypeMismatch { .. })), "{error}");
}
assert!(codec.raw_reason("Broken").is_some_and(|reason| reason.contains("'Kind'")));
assert!(codec.raw_reason("Envelopes").is_some_and(|reason| reason.contains("'Envelope'")));
assert_eq!(codec.raw_reason("Envelope"), None);
let envelope = Value::record([("Kind", Value::from(1)), ("Payload", Value::raw([9u8, 9, 9]))]);
assert_eq!(codec.encode("Envelope", &envelope), Ok(vec![0, 0, 0, 1, 9, 9, 9]));
assert_eq!(codec.decode("Envelope", &[0, 0, 0, 1, 9, 9, 9]), Ok(envelope));
let wrapper = Value::variant_named(Enumerator::new("Zip", 1), "Payload", Value::raw([9u8, 9, 9]));
let sealed = Value::record([("Wrapper", wrapper), ("After", Value::from(7))]);
let expected = vec![0, 0, 0, 1, 0, 0, 0, 3, 9, 9, 9, 0, 0, 0, 0, 7];
assert_eq!(codec.encode("Sealed", &sealed).as_ref(), Ok(&expected));
assert_eq!(codec.decode("Sealed", &expected), Ok(sealed));
let untyped = attribute_id(&fdd, "Untyped");
assert_eq!(codec.attribute_data_type(untyped), Some("NA"));
assert_eq!(codec.decode_attribute(untyped, &[5, 6]), Ok(Value::raw([5u8, 6])));
assert_eq!(codec.encode_attribute(untyped, &Value::raw([5u8, 6])), Ok(vec![5, 6]));
assert_eq!(codec.encode_attribute(untyped, &Value::bytes([5u8, 6])), Ok(vec![5, 6]));
let error = codec.encode_attribute(untyped, &Value::from(1)).unwrap_err();
assert_eq!(
error.to_string(),
"cannot encode attribute HLAobjectRoot.Thing.Untyped: NA at offset 0: expected raw bytes (NA), \
found integer"
);
assert_eq!(codec.decode_attribute(attribute_id(&fdd, "Payload"), &[5]), Ok(Value::raw([5u8])));
let speed = attribute_id(&fdd, "Speed");
assert_eq!(codec.decode_attribute(speed, &2.5f64.to_be_bytes()), Ok(Value::from(2.5)));
let thing = fdd.object_class_by_name("Thing").unwrap();
let all = codec.decode_attributes(thing, [(untyped, vec![1u8]), (speed, 2.5f64.to_be_bytes().to_vec())]);
let expected = [("Speed".to_owned(), Value::from(2.5)), ("Untyped".to_owned(), Value::raw([1u8]))];
assert_eq!(all, Ok(BTreeMap::from(expected)));
}
fn attribute_id(fdd: &Fdd, name: &str) -> AttributeId {
attribute(fdd, "Thing", name)
}
#[test]
fn errors_name_the_place_the_offset_and_the_reason() {
let fdd = Fdd::with_standard_mim();
let codec = FomCodec::new(&fdd).unwrap();
let entry = |active: Value| {
Value::record([("HLAinteractionClass", Value::handle([0u8, 0, 0, 9])), ("HLAactive", active)])
};
let list = Value::array((0..4).map(|_| entry(Value::Bool(true))));
let bytes = codec.encode("HLAinteractionSubList", &list).unwrap();
assert_eq!(bytes.len(), 4 + 4 * 12);
let error = codec.decode("HLAinteractionSubList", &bytes[..46]).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList[3].HLAinteractionClass"));
assert_eq!(error.offset(), Some(40));
assert_eq!(
error.reason(),
Some(&Reason::Decoder(DecoderError::CountExceedsInput { count: 4, remaining: 2 }))
);
assert_eq!(
error.to_string(),
"cannot decode HLAinteractionSubList[3].HLAinteractionClass at offset 40: element count 4 exceeds \
the 2 remaining octet(s)"
);
let error = codec.decode("HLAinteractionSubList", &bytes[..50]).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList[3].HLAactive"));
let truncated = DecoderError::Truncated { offset: 48, needed: 4, remaining: 2 };
assert_eq!((error.offset(), error.reason()), (Some(48), Some(&Reason::Decoder(truncated))));
let error = codec.decode("HLAinteractionSubList", &[0xff, 0xff, 0xff, 0xff]).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList"));
assert_eq!(error.reason(), Some(&Reason::Decoder(DecoderError::InvalidCount { count: -1 })));
let error = codec.decode("HLAinteractionSubList", &[0x7f, 0xff, 0xff, 0xff, 0, 0]).unwrap_err();
let exceeds = DecoderError::CountExceedsInput { count: i32::MAX as usize, remaining: 2 };
assert_eq!(error.reason(), Some(&Reason::Decoder(exceeds)));
let error = codec.decode("HLAinteractionSubList", &bytes[..20]).unwrap_err();
assert_eq!(
error.reason(),
Some(&Reason::Decoder(DecoderError::CountExceedsInput { count: 4, remaining: 16 }))
);
let error = codec.decode("HLAcount", &[0, 0, 0, 1, 9]).unwrap_err();
assert_eq!(error.path(), Some("HLAcount"));
assert_eq!(error.offset(), Some(4));
assert_eq!(error.reason(), Some(&Reason::Decoder(DecoderError::TrailingBytes { count: 1 })));
assert_eq!(codec.decode_prefix("HLAcount", &[0, 0, 0, 1, 9]), Ok((Value::from(1), 4)));
assert_eq!(
codec.decode_prefix("HLAinteractionSubList", &[bytes.as_slice(), &[1, 2, 3]].concat()),
Ok((list, 52))
);
let with = |third: Value| Value::array([entry(Value::Bool(true)), entry(Value::Bool(false)), third]);
let error = codec.encode("HLAinteractionSubList", &with(entry(Value::from("maybe")))).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList[2].HLAactive"));
assert!(matches!(error.reason(), Some(Reason::UnknownEnumerator { .. })), "{error}");
assert_eq!(error.offset(), Some(36));
let error = codec.encode("HLAinteractionSubList", &with(entry(Value::from(1.5)))).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList[2].HLAactive"));
assert_eq!(
error.reason(),
Some(&Reason::TypeMismatch {
expected: "an enumerator (HLAboolean)".to_owned(),
found: "float".to_owned()
})
);
let missing = Value::record([("HLAactive", true)]);
let unknown = Value::record([("HLAactive", Value::Bool(true)), ("HLAclass", Value::handle([1u8]))]);
let twice = Value::record([
("HLAactive", Value::Bool(true)),
("HLAinteractionClass", Value::handle([1u8])),
("HLAactive", Value::Bool(true)),
]);
for (third, text) in [
(missing, "the field 'HLAinteractionClass' of HLAinteractionSubscription is missing"),
(unknown, "'HLAclass' is not a field of HLAinteractionSubscription"),
(twice, "a field of HLAinteractionSubscription is given more than once"),
] {
let error = codec.encode("HLAinteractionSubList", &with(third)).unwrap_err();
assert_eq!(error.path(), Some("HLAinteractionSubList[2]"));
assert_eq!(error.reason(), Some(&Reason::Field { detail: text.to_owned() }));
}
let name = attribute(&fdd, "HLAmanager.HLAfederate", "HLAfederateName");
let error = codec.decode_attribute(name, &[0, 0, 0, 2, 0, 0x61]).unwrap_err();
let failure = error.failure().expect("a decoding failure");
assert_eq!(
failure.member.as_deref(),
Some("attribute HLAobjectRoot.HLAmanager.HLAfederate.HLAfederateName")
);
assert_eq!(failure.path, "HLAunicodeString");
assert_eq!(
error.to_string(),
"cannot decode attribute HLAobjectRoot.HLAmanager.HLAfederate.HLAfederateName: HLAunicodeString at \
offset 0: element count 2 exceeds the 2 remaining octet(s)"
);
let period = parameter(&fdd, "HLAmanager.HLAfederate.HLAadjust.HLAsetTiming", "HLAreportPeriod");
let error = codec.encode_parameter(period, &Value::from("soon")).unwrap_err();
assert_eq!(
error.failure().and_then(|failure| failure.member.as_deref()),
Some("parameter HLAinteractionRoot.HLAmanager.HLAfederate.HLAadjust.HLAsetTiming.HLAreportPeriod")
);
assert_eq!(error.path(), Some("HLAseconds"));
let class = fdd.interaction_class_by_name("HLAmanager.HLAfederate.HLAadjust.HLAsetTiming").unwrap();
let error = codec.decode_parameters(class, [(period, [0u8, 0])]).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::Truncated { .. }))), "{error}");
assert!(error.failure().is_some_and(|failure| failure.member.is_some()));
}
#[test]
fn hostile_input_never_panics() {
let fdd = restaurant_fdd();
let codec = FomCodec::new(&fdd).unwrap();
let mut sampler = Sampler::new(&fdd, 7);
let mut rng = XorShift(0xdead_beef_cafe_f00d);
let mut decoded = 0usize;
for data_type in fdd.data_types() {
let name = data_type.name();
for round in 0..150u32 {
let mut input = octets(&mut rng, 48);
if round.is_multiple_of(3) {
input = codec.encode(name, &sampler.sample(name)).unwrap();
for _ in 0..rng.below(3) + 1 {
if !input.is_empty() {
let at = rng.below(input.len());
input[at] = rng.next() as u8;
}
}
if rng.below(4) == 0 {
input.truncate(rng.below(input.len() + 1));
}
}
if round.is_multiple_of(5) && input.len() >= 4 {
input[..4].copy_from_slice(&[0x7f, 0xff, 0xff, 0xff]);
}
match codec.decode_prefix(name, &input) {
Ok((value, used)) => {
decoded += 1;
assert!(used <= input.len(), "{name}");
assert!(!value.to_string().is_empty());
if let Ok(again) = codec.encode(name, &value) {
let reread = codec.decode(name, &again).unwrap_or_else(|error| panic!("{error}"));
assert_eq!(codec.encode(name, &reread), Ok(again), "{name}");
}
}
Err(error) => {
assert!(matches!(error, CodecError::Decode(_)), "{error}");
assert!(error.path().is_some_and(|path| path.starts_with(name)), "{error}");
assert!(error.offset().is_some_and(|offset| offset <= input.len()), "{error}");
}
}
if let Err(error) = codec.decode(name, &input) {
assert!(!error.to_string().is_empty());
}
}
}
assert!(decoded > 1000, "only {decoded} inputs decoded");
let huge_alternative = [0, 0, 0, 1, 0x7f, 0xff, 0xff, 0xff, 0, 0, 0, 1];
let error = codec.decode("DrinkGarnish", &huge_alternative).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::Truncated { .. }))), "{error}");
let negative = [0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 1];
let error = codec.decode("DrinkGarnish", &negative).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::InvalidValue { .. }))), "{error}");
let error = codec.decode("DrinkGarnish", &[0, 0, 0, 1, 0, 0, 0, 6, 0, 0, 0, 1, 0, 0]).unwrap_err();
assert_eq!(error.path(), Some("DrinkGarnish.HasSaltRim"));
assert_eq!(
error.reason(),
Some(&Reason::Decoder(DecoderError::LengthMismatch { declared: 6, consumed: 4 }))
);
let tables = Tables::default().enumerated("Kind", "HLAinteger32BE", &[("A", 1), ("B", 2)]).variant(
"Strict",
"HLAvariantRecord",
("Kind", "Kind"),
&[("A", "Number", "HLAinteger32BE")],
);
let strict = tables.codec();
for discriminant in [2, 3] {
let error = strict.decode("Strict", &[0, 0, 0, discriminant, 0, 0, 0, 1]).unwrap_err();
assert_eq!(
error.reason(),
Some(&Reason::Decoder(DecoderError::TrailingBytes { count: 4 })),
"{error}"
);
}
let bare = Value::variant(Enumerator::new("B", 2), None);
assert_eq!(strict.decode("Strict", &[0, 0, 0, 2]), Ok(bare));
let unknown = Value::variant(Enumerator::numbered(3), None);
assert_eq!(strict.decode("Strict", &[0, 0, 0, 3]), Ok(unknown.clone()));
assert_eq!(strict.encode("Strict", &unknown), Ok(vec![0, 0, 0, 3]));
assert_eq!(strict.encode("Strict", &Value::variant("B", None)), Ok(vec![0, 0, 0, 2]));
let error = strict.encode("Strict", &Value::variant("B", Some(Value::from(1)))).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Alternative { .. })), "{error}");
}
#[test]
fn memory_is_bounded_by_the_input() {
let codec = Tables::default()
.array("Tokens", "HLAtoken", "Dynamic", "HLAvariableArray")
.array("ThreeTokens", "HLAtoken", "3", "HLAfixedArray")
.array("ManyTokens", "HLAtoken", "4000000000", "HLAfixedArray")
.array("ManyFloats", "HLAfloat64BE", "1000000000", "HLAfixedArray")
.array("ManyBytes", "HLAbyte", "4000000000", "HLAfixedArray")
.array("ManyLists", "HLAfederateHandleList", "1000000000", "HLAfixedArray")
.array("Deep", "ManyLists", "1000000,1000000", "HLAfixedArray")
.codec();
let error = codec.decode("Tokens", &[0x3b, 0x9a, 0xca, 0, 0, 0]).unwrap_err();
let exceeds = DecoderError::CountExceedsInput { count: 1_000_000_000, remaining: 2 };
assert_eq!(error.reason(), Some(&Reason::Decoder(exceeds)));
assert_eq!(
codec.decode("ThreeTokens", &[]),
Ok(Value::array([Value::Bytes(vec![]), Value::Bytes(vec![]), Value::Bytes(vec![])]))
);
let error = codec.decode("ManyTokens", &[]).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::InvalidValue { .. })), "{error}");
let error = codec.decode("ManyFloats", &[0; 64]).unwrap_err();
let truncated = DecoderError::Truncated { offset: 0, needed: 8_000_000_000, remaining: 64 };
assert_eq!(error.reason(), Some(&Reason::Decoder(truncated)));
let error = codec.decode("ManyBytes", &[0; 64]).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::Truncated { .. }))), "{error}");
let error = codec.decode("ManyLists", &[0; 64]).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::Truncated { .. }))), "{error}");
let error = codec.decode("Deep", &[0; 64]).unwrap_err();
assert!(matches!(error.reason(), Some(Reason::Decoder(DecoderError::Truncated { .. }))), "{error}");
let mim = FomCodec::new(&Fdd::with_standard_mim()).unwrap();
let mut input = vec![0u8; 4 * 1024];
input[..4].copy_from_slice(&1023u32.to_be_bytes());
let Ok(Value::Array(lists)) = mim.decode("HLAsyncPointList", &input) else { panic!("a list of strings") };
assert_eq!(lists.len(), 1023);
assert!(lists.iter().all(|list| list.as_str() == Some("")));
}
#[test]
fn recursive_data_types_are_rejected() {
let through_array = Tables::default()
.array("NodeList", "Node", "Dynamic", "HLAvariableArray")
.record("Node", "HLAfixedRecord", &[("Value", "HLAinteger32BE"), ("Children", "NodeList")])
.fdd();
let Err(CodecError::RecursiveDataType { cycle }) = FomCodec::new(&through_array) else {
panic!("a recursive definition must be rejected");
};
assert!(cycle == "NodeList -> Node -> NodeList" || cycle == "Node -> NodeList -> Node", "{cycle}");
let itself = Tables::default().array("Loop", "Loop", "2", "HLAfixedArray").fdd();
let error = FomCodec::new(&itself).unwrap_err();
assert_eq!(error, CodecError::RecursiveDataType { cycle: "Loop -> Loop".to_owned() });
assert_eq!(error.to_string(), "recursive data type definition: Loop -> Loop");
assert_eq!(RtiError::from(error).kind, ExceptionKind::InconsistentFOM);
let through_variant = Tables::default()
.enumerated("Kind", "HLAinteger32BE", &[("Leaf", 0), ("Pair", 1)])
.array("Alias", "Tree", "1", "HLAfixedArray")
.record("Branch", "HLAfixedRecord", &[("Left", "Alias"), ("Right", "Alias")])
.variant(
"Tree",
"HLAextendableVariantRecord",
("Kind", "Kind"),
&[("Leaf", "Value", "HLAinteger32BE"), ("Pair", "Branch", "Branch")],
)
.fdd();
let Err(CodecError::RecursiveDataType { cycle }) = FomCodec::new(&through_variant) else {
panic!("a recursive definition must be rejected");
};
for name in ["Alias", "Tree", "Branch"] {
assert!(cycle.contains(name), "{cycle}");
}
let fine = Tables::default()
.array("NodeList", "Node", "Dynamic", "HLAvariableArray")
.record("Node", "HLAfixedRecord", &[("Value", "HLAinteger32BE")])
.record("Tree", "HLAfixedRecord", &[("Root", "Node"), ("Children", "NodeList")])
.codec();
let tree = Value::record([
("Root", Value::record([("Value", 1)])),
("Children", Value::array([Value::record([("Value", 2)])])),
]);
assert_eq!(fine.encode("Tree", &tree), Ok(vec![0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2]));
}
fn chain(levels: usize) -> Tables {
let mut tables = Tables::default();
for level in 0..levels {
let element =
if level + 1 == levels { "HLAinteger32BE".to_owned() } else { format!("Level{}", level + 1) };
tables = tables.array(&format!("Level{level}"), &element, "1", "HLAfixedArray");
}
tables
}
#[test]
fn nesting_is_limited() {
let codec = chain(63).codec();
let mut value = Value::from(5);
for _ in 0..63 {
value = Value::array([value]);
}
assert_eq!(codec.encode("Level0", &value), Ok(vec![0, 0, 0, 5]));
assert_eq!(codec.decode("Level0", &[0, 0, 0, 5]), Ok(value));
let error = FomCodec::new(&chain(64).fdd()).unwrap_err();
assert_eq!(error, CodecError::NestingTooDeep { data_type: "Level0".to_owned(), limit: 64 });
assert_eq!(RtiError::from(error).kind, ExceptionKind::InconsistentFOM);
assert!(matches!(FomCodec::new(&chain(3000).fdd()), Err(CodecError::NestingTooDeep { limit: 64, .. })));
}