microrti-encoding 0.2.1

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! Byte-exact vectors for the basic representations, the simple datatypes, strings, opaque data, handle
//! elements and logical time elements.

mod common;

use common::check;
use microrti_core::{ExceptionKind, LogicalTime, LogicalTimeInterval, RtiError, TimeKind};
use microrti_encoding::*;

#[test]
fn octets_and_octet_pairs() {
    check(HLAoctet(0xab), &[0xab]);
    check(HLAoctetPairBE(0x1234), &[0x12, 0x34]);
    check(HLAoctetPairLE(0x1234), &[0x34, 0x12]);
    check(HLAunsignedInteger8(200), &[0xc8]);
    assert_eq!(HLAoctet::OCTET_BOUNDARY, 1);
    assert_eq!(HLAoctetPairBE::OCTET_BOUNDARY, 2);
    assert_eq!(HLAoctetPairLE::OCTET_BOUNDARY, 2);
}

#[test]
fn signed_integers_both_endiannesses() {
    check(HLAinteger16BE(-2), &[0xff, 0xfe]);
    check(HLAinteger16LE(-2), &[0xfe, 0xff]);
    check(HLAinteger16BE(0x0102), &[1, 2]);
    check(HLAinteger16LE(0x0102), &[2, 1]);

    check(HLAinteger32BE(0x0102_0304), &[1, 2, 3, 4]);
    check(HLAinteger32LE(0x0102_0304), &[4, 3, 2, 1]);
    check(HLAinteger32BE(-1), &[0xff; 4]);
    check(HLAinteger32BE(i32::MIN), &[0x80, 0, 0, 0]);
    check(HLAinteger32LE(i32::MIN), &[0, 0, 0, 0x80]);

    check(HLAinteger64BE(0x0102_0304_0506_0708), &[1, 2, 3, 4, 5, 6, 7, 8]);
    check(HLAinteger64LE(0x0102_0304_0506_0708), &[8, 7, 6, 5, 4, 3, 2, 1]);
    check(HLAinteger64BE(-2), &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]);
    check(HLAinteger64LE(-2), &[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);

    assert_eq!(HLAinteger16BE::OCTET_BOUNDARY, 2);
    assert_eq!(HLAinteger16LE::OCTET_BOUNDARY, 2);
    assert_eq!(HLAinteger32BE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAinteger32LE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAinteger64BE::OCTET_BOUNDARY, 8);
    assert_eq!(HLAinteger64LE::OCTET_BOUNDARY, 8);
}

#[test]
fn unsigned_integers_both_endiannesses() {
    check(HLAunsignedInteger16BE(0xfffe), &[0xff, 0xfe]);
    check(HLAunsignedInteger16LE(0xfffe), &[0xfe, 0xff]);
    check(HLAunsignedInteger32BE(0xdead_beef), &[0xde, 0xad, 0xbe, 0xef]);
    check(HLAunsignedInteger32LE(0xdead_beef), &[0xef, 0xbe, 0xad, 0xde]);
    check(HLAunsignedInteger64BE(0xfedc_ba98_7654_3210), &[0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10]);
    check(HLAunsignedInteger64LE(0xfedc_ba98_7654_3210), &[0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]);
    check(HLAunsignedInteger64BE(u64::MAX), &[0xff; 8]);

    assert_eq!(HLAunsignedInteger16LE::OCTET_BOUNDARY, 2);
    assert_eq!(HLAunsignedInteger32LE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAunsignedInteger64LE::OCTET_BOUNDARY, 8);
}

#[test]
fn floats_both_endiannesses() {
    check(HLAfloat32BE(1.0), &[0x3f, 0x80, 0, 0]);
    check(HLAfloat32LE(1.0), &[0, 0, 0x80, 0x3f]);
    check(HLAfloat32BE(-2.5), &[0xc0, 0x20, 0, 0]);
    check(HLAfloat32LE(-2.5), &[0, 0, 0x20, 0xc0]);

    check(HLAfloat64BE(1.0), &[0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
    check(HLAfloat64LE(1.0), &[0, 0, 0, 0, 0, 0, 0xf0, 0x3f]);
    check(HLAfloat64BE(-2.5), &[0xc0, 0x04, 0, 0, 0, 0, 0, 0]);
    check(HLAfloat64LE(-2.5), &[0, 0, 0, 0, 0, 0, 0x04, 0xc0]);
    check(HLAfloat64BE(f64::INFINITY), &[0x7f, 0xf0, 0, 0, 0, 0, 0, 0]);

    // NaN keeps its bit pattern.
    let nan = [0x7f, 0xf8, 0, 0, 0, 0, 0, 0x2a];
    let decoded = decode_from_slice_strict::<HLAfloat64BE>(&nan).unwrap();
    assert!(decoded.0.is_nan());
    assert_eq!(encode_to_vec(&decoded), nan);

    assert_eq!(HLAfloat32BE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAfloat32LE::OCTET_BOUNDARY, 4);
    assert_eq!(HLAfloat64BE::OCTET_BOUNDARY, 8);
    assert_eq!(HLAfloat64LE::OCTET_BOUNDARY, 8);
}

#[test]
fn simple_datatypes() {
    check(HLAASCIIchar(b'A'), &[0x41]);
    check(HLAunicodeChar(0x20ac), &[0x20, 0xac]);
    check(HLAbyte(7), &[7]);
    check(HLAboolean(false), &[0, 0, 0, 0]);
    check(HLAboolean(true), &[0, 0, 0, 1]);
    assert_eq!(HLAboolean::OCTET_BOUNDARY, 4);
    assert_eq!(HLAunicodeChar::OCTET_BOUNDARY, 2);

    // MIM simple datatypes are aliases of their representation.
    check(HLAcount::new(3), &[0, 0, 0, 3]);
    check(HLAmsec::new(1500), &[0, 0, 0x05, 0xdc]);
    check(HLAnormalizedFederateHandle::new(5), &[0, 0, 0, 0, 0, 0, 0, 5]);
    check(HLAfloat64Time::new(1.0), &[0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
    check(HLAinteger64Time::new(-1), &[0xff; 8]);
}

#[test]
fn native_conversions() {
    assert_eq!(HLAinteger32BE::from(5).get(), 5);
    assert_eq!(i32::from(HLAinteger32BE(5)), 5);
    assert_eq!(HLAinteger32BE::from_native(5).to_native(), 5);
    assert!(bool::from(HLAboolean::from(true)));
    assert_eq!(HLAfloat64BE(1.5).to_string(), "1.5");
    assert_eq!(HLAboolean(true).to_string(), "HLAtrue");
    assert!(HLAinteger16BE(1) < HLAinteger16BE(2));
}

#[test]
fn ascii_strings() {
    check(HLAASCIIstring::new("").unwrap(), &[0, 0, 0, 0]);
    check(HLAASCIIstring::new("HLA").unwrap(), &[0, 0, 0, 3, b'H', b'L', b'A']);
    assert_eq!(HLAASCIIstring::OCTET_BOUNDARY, 4);

    let text: HLAASCIIstring = "plain".parse().unwrap();
    assert_eq!(text.as_str(), "plain");
    assert_eq!(String::from(text), "plain");
    assert!(matches!(
        HLAASCIIstring::new("caf\u{e9}"),
        Err(EncoderError::InvalidValue { type_name: "HLAASCIIstring", .. })
    ));
    assert!(HLAASCIIstring::try_from("\u{1f600}").is_err());
}

#[test]
fn unicode_strings() {
    check(HLAunicodeString::new(""), &[0, 0, 0, 0]);
    check(HLAunicodeString::new("H\u{e9}"), &[0, 0, 0, 2, 0, 0x48, 0, 0xe9]);
    check(HLAunicodeString::new("\u{20ac}"), &[0, 0, 0, 1, 0x20, 0xac]);
    // Characters outside the BMP are a surrogate pair, and the count is in code units.
    check(HLAunicodeString::new("a\u{1f600}"), &[0, 0, 0, 3, 0, 0x61, 0xd8, 0x3d, 0xde, 0x00]);
    check(
        HLAunicodeString::new("\u{10000}\u{10ffff}"),
        &[0, 0, 0, 4, 0xd8, 0x00, 0xdc, 0x00, 0xdb, 0xff, 0xdf, 0xff],
    );
    assert_eq!(HLAunicodeString::OCTET_BOUNDARY, 4);

    // String and str share the encoding.
    check(String::from("a\u{1f600}"), &[0, 0, 0, 3, 0, 0x61, 0xd8, 0x3d, 0xde, 0x00]);
    check(String::new(), &[0, 0, 0, 0]);
    assert_eq!(encode_to_vec("H\u{e9}"), [0, 0, 0, 2, 0, 0x48, 0, 0xe9]);
    assert_eq!("H\u{e9}".encoded_len(), 8);
}

#[test]
fn opaque_data() {
    check(HLAopaqueData::new(Vec::<u8>::new()), &[0, 0, 0, 0]);
    check(HLAopaqueData::new([1u8, 2, 3]), &[0, 0, 0, 3, 1, 2, 3]);
    check(HLAopaqueData::new(vec![0xffu8; 5]), &[0, 0, 0, 5, 0xff, 0xff, 0xff, 0xff, 0xff]);
    assert_eq!(HLAopaqueData::OCTET_BOUNDARY, 4);
    assert_eq!(HLAopaqueData::from(&[9u8, 8][..]).as_bytes(), [9, 8]);
}

macro_rules! handle_vectors {
    ($($name:ident),+) => {$(
        // A handle is a variable array of bytes: count, then the opaque octets of the handle.
        check($name::new([0u8, 0, 0, 7]), &[0, 0, 0, 4, 0, 0, 0, 7]);
        check($name::new([1u8, 2, 3, 4, 5, 6, 7, 8]), &[0, 0, 0, 8, 1, 2, 3, 4, 5, 6, 7, 8]);
        check($name::new([0xaau8, 0xbb, 0xcc]), &[0, 0, 0, 3, 0xaa, 0xbb, 0xcc]);
        check($name::default(), &[0, 0, 0, 0]);
        assert_eq!($name::OCTET_BOUNDARY, 4);
        assert_eq!($name::from(vec![1u8, 2]).into_bytes(), [1, 2]);
    )+};
}

#[test]
fn handle_elements() {
    handle_vectors!(
        HLAfederateHandle,
        HLAobjectClassHandle,
        HLAattributeHandle,
        HLAinteractionClassHandle,
        HLAparameterHandle,
        HLAobjectInstanceHandle,
        HLAdimensionHandle,
        HLAregionHandle,
        HLAtransportationTypeHandle,
        HLAmessageRetractionHandle
    );
}

#[test]
fn handle_decoding_does_not_validate() {
    // 12.11.4.2: handle decoders do not check the semantic validity of the handle.
    let odd = decode_from_slice_strict::<HLAobjectInstanceHandle>(&[0, 0, 0, 1, 0xff]).unwrap();
    assert_eq!(odd.as_bytes(), [0xff]);
}

#[test]
fn logical_time_elements() {
    let float_time = HLAlogicalTime::from_time(LogicalTime::Float64(1.0));
    check(float_time.clone(), &[0, 0, 0, 8, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0]);
    assert_eq!(float_time.time(TimeKind::Float64), Ok(LogicalTime::Float64(1.0)));

    let integer_time = HLAlogicalTime::from(LogicalTime::Integer64(5));
    check(integer_time.clone(), &[0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 5]);
    assert_eq!(integer_time.time(TimeKind::Integer64), Ok(LogicalTime::Integer64(5)));

    let interval = HLAlogicalTimeInterval::from_interval(LogicalTimeInterval::Float64(0.5));
    check(interval.clone(), &[0, 0, 0, 8, 0x3f, 0xe0, 0, 0, 0, 0, 0, 0]);
    assert_eq!(interval.interval(TimeKind::Float64), Ok(LogicalTimeInterval::Float64(0.5)));

    let integer_interval = HLAlogicalTimeInterval::from(LogicalTimeInterval::Integer64(-3));
    check(integer_interval.clone(), &[0, 0, 0, 8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd]);
    assert_eq!(integer_interval.interval(TimeKind::Integer64), Ok(LogicalTimeInterval::Integer64(-3)));

    assert_eq!(HLAlogicalTime::OCTET_BOUNDARY, 4);
    assert_eq!(HLAlogicalTimeInterval::OCTET_BOUNDARY, 4);
}

#[test]
fn logical_time_elements_reject_bad_content() {
    let short = decode_from_slice_strict::<HLAlogicalTime>(&[0, 0, 0, 3, 1, 2, 3]).unwrap();
    assert_eq!(
        short.time(TimeKind::Integer64),
        Err(DecoderError::CountMismatch { type_name: "HLAlogicalTime", expected: 8, found: 3 })
    );
    let nan = HLAlogicalTime::new(f64::NAN.to_be_bytes());
    assert!(matches!(nan.time(TimeKind::Float64), Err(DecoderError::InvalidValue { .. })));
    // The same octets are a legal integer time.
    assert!(nan.time(TimeKind::Integer64).is_ok());

    let short = HLAlogicalTimeInterval::new([0u8; 9]);
    assert_eq!(
        short.interval(TimeKind::Float64),
        Err(DecoderError::CountMismatch { type_name: "HLAlogicalTimeInterval", expected: 8, found: 9 })
    );
}

#[test]
fn errors_map_to_rti_exceptions() {
    let decode: RtiError = DecoderError::TrailingBytes { count: 2 }.into();
    assert_eq!(decode.kind, ExceptionKind::CouldNotDecode);
    assert!(decode.message.contains("2 trailing"));
    let encode: RtiError = EncoderError::NoVariantForDiscriminant.into();
    assert_eq!(encode.kind, ExceptionKind::CouldNotEncode);
}

#[test]
fn convenience_functions() {
    let bytes = [0, 0, 0, 5, 0xee];
    assert_eq!(decode_from_slice::<HLAinteger32BE>(&bytes), Ok(HLAinteger32BE(5)));
    assert_eq!(decode_prefix::<HLAinteger32BE>(&bytes), Ok((HLAinteger32BE(5), 4)));
    assert_eq!(
        decode_from_slice_strict::<HLAinteger32BE>(&bytes),
        Err(DecoderError::TrailingBytes { count: 1 })
    );
    assert_eq!(try_encode_to_vec(&HLAinteger32BE(5)), Ok(vec![0, 0, 0, 5]));

    // encode_into starts a new outermost value: padding is counted from the first appended octet.
    let mut buffer = vec![0xee];
    encode_into(&vec![HLAinteger64BE(1)], &mut buffer).unwrap();
    assert_eq!(buffer, [0xee, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
}

#[test]
fn writer_and_reader_primitives() {
    assert_eq!(max_boundary(&[]), 1);
    assert_eq!(max_boundary(&[2, 8, 4]), 8);
    assert_eq!(padding_for(0, 8), 0);
    assert_eq!(padding_for(5, 4), 3);
    assert_eq!(padding_for(5, 1), 0);

    let mut buffer = Vec::new();
    let mut writer = ByteWriter::new(&mut buffer);
    writer.put_u8(1);
    writer.align(4);
    writer.put_count(2);
    assert_eq!(writer.position(), 8);
    assert_eq!(writer.status(), Ok(()));
    writer.put_count(usize::MAX);
    assert_eq!(writer.status(), Err(EncoderError::TooManyElements { count: usize::MAX }));
    assert_eq!(buffer[..8], [1, 0, 0, 0, 0, 0, 0, 2]);

    let mut counter = ByteWriter::counter();
    counter.put_slice(&[1, 2, 3]);
    counter.align(8);
    assert_eq!(counter.position(), 8);

    let mut reader = ByteReader::new(&buffer[..8]);
    assert_eq!(reader.read_u8(), Ok(1));
    reader.align(4).unwrap();
    assert_eq!(reader.position(), 4);
    let mut window = reader.window(4).unwrap();
    assert!(reader.is_empty());
    assert_eq!(window.position(), 4);
    assert_eq!(window.take(4), Ok(&[0u8, 0, 0, 2][..]));
    assert_eq!(reader.expect_end(), Ok(()));
    assert_eq!(reader.take(1), Err(DecoderError::Truncated { offset: 8, needed: 1, remaining: 0 }));
}