microrti-encoding 0.3.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! `HLAextendableVariantRecord`: byte-exact vectors of the layout documented in the `extendable`
//! module, skipping of unknown alternatives, and the errors specific to this encoding.

mod common;

use common::check;
use microrti_encoding::*;

hla_enumerated! {
    /// `DrinkType` as the base module of the Restaurant sample FOM declares it.
    enum DrinkType: HLAinteger32BE {
        Margarita = 1,
        DryMartini = 2,
    }
}

hla_enumerated! {
    /// `DrinkType` after merging the extension module, which adds an enumerator.
    enum ExtendedDrinkType: HLAinteger32BE {
        Margarita = 1,
        DryMartini = 2,
        IrishCoffee = 3,
    }
}

hla_extendable_variant_record! {
    /// `DrinkGarnish` of the base module.
    enum DrinkGarnish: DrinkType {
        HasSaltRim(HLAboolean) = DrinkType::Margarita,
        OliveCount(i32 as HLAinteger32BE) = DrinkType::DryMartini,
    }
}

hla_extendable_variant_record! {
    /// `DrinkGarnish` after merging the extension module, which adds an alternative.
    enum ExtendedDrinkGarnish: ExtendedDrinkType {
        HasSaltRim(HLAboolean) = ExtendedDrinkType::Margarita,
        OliveCount(i32 as HLAinteger32BE) = ExtendedDrinkType::DryMartini,
        ExtraWhippedCream(HLAboolean) = ExtendedDrinkType::IrishCoffee,
    }
}

hla_fixed_record! {
    struct Order {
        table: HLAoctet,
        garnish: DrinkGarnish,
        priority: HLAoctet,
    }
}

hla_fixed_record! {
    struct ExtendedOrder {
        table: HLAoctet,
        garnish: ExtendedDrinkGarnish,
        priority: HLAoctet,
    }
}

hla_extendable_variant_record! {
    enum Shapes: HLAoctet {
        Wide(HLAinteger64BE) = HLAoctet(5),
        Plain = HLAoctet(7),
        Note(String) = HLAoctet(4),
    }
}

hla_extendable_variant_record! {
    enum WideDiscriminant: HLAinteger64BE {
        Short(HLAinteger16BE) = HLAinteger64BE(1),
    }
}

#[test]
fn discriminant_length_alternative() {
    assert_eq!(DrinkGarnish::OCTET_BOUNDARY, 8);
    assert_eq!(extendable::OCTET_BOUNDARY, 8);
    check(DrinkGarnish::HasSaltRim(HLAboolean(true)), &[0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 1]);
    check(DrinkGarnish::OliveCount(3), &[0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]);
    check(ExtendedDrinkGarnish::ExtraWhippedCream(HLAboolean(true)), &[0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1]);
}

#[test]
fn padding_inside_the_record() {
    // One-octet discriminant: padding to the length field.
    check(Shapes::Wide(HLAinteger64BE(1)), &[5, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1]);
    // No alternative data: the length is zero and nothing follows.
    check(Shapes::Plain, &[7, 0, 0, 0, 0, 0, 0, 0]);
    // A variable-length alternative.
    check(Shapes::Note("ab".into()), &[4, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0x61, 0, 0x62]);
    // Eight-octet discriminant: the length field is followed by padding to the alternative boundary.
    check(
        WideDiscriminant::Short(HLAinteger16BE(7)),
        &[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7],
    );
}

#[test]
fn boundary_is_independent_of_the_alternatives() {
    let order = Order { table: HLAoctet(4), garnish: DrinkGarnish::OliveCount(3), priority: HLAoctet(9) };
    let mut expected = vec![4, 0, 0, 0, 0, 0, 0, 0]; // table, padding to the boundary 8
    expected.extend([0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]); // garnish
    expected.push(9); // priority directly after the alternative
    check(order, &expected);
    assert_eq!(Order::OCTET_BOUNDARY, 8);

    // In an array the next record starts at the next multiple of 8.
    let mut in_array = vec![0, 0, 0, 2, 0, 0, 0, 0];
    in_array.extend([0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0]);
    in_array.extend([0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 3]);
    check(vec![DrinkGarnish::HasSaltRim(HLAboolean(false)), DrinkGarnish::OliveCount(3)], &in_array);
}

#[test]
fn unknown_alternatives_are_skipped_and_passed_on() {
    let cream = ExtendedDrinkGarnish::ExtraWhippedCream(HLAboolean(true));
    let bytes = encode_to_vec(&cream);

    // The base declaration does not know enumerator 3: it keeps the raw discriminant and the octets.
    let skipped = decode_from_slice_strict::<DrinkGarnish>(&bytes).unwrap();
    assert_eq!(skipped, DrinkGarnish::Unknown { discriminant: HLAinteger32BE(3), data: vec![0, 0, 0, 1] });
    assert_eq!(encode_to_vec(&skipped), bytes);
    assert_eq!(skipped.encoded_len(), bytes.len());

    // The fields after the record are found whatever the alternative is.
    let extended = ExtendedOrder { table: HLAoctet(4), garnish: cream, priority: HLAoctet(9) };
    let bytes = encode_to_vec(&extended);
    let order = decode_from_slice_strict::<Order>(&bytes).unwrap();
    assert_eq!(order.table, HLAoctet(4));
    assert_eq!(order.priority, HLAoctet(9));
    assert!(matches!(order.garnish, DrinkGarnish::Unknown { .. }));
    assert_eq!(encode_to_vec(&order), bytes);

    // Known alternatives are understood by both declarations.
    let olives = encode_to_vec(&ExtendedDrinkGarnish::OliveCount(2));
    assert_eq!(decode_from_slice_strict::<DrinkGarnish>(&olives), Ok(DrinkGarnish::OliveCount(2)));

    // An unknown alternative without data, and one whose discriminant is not even an enumerator.
    assert_eq!(
        decode_from_slice_strict::<DrinkGarnish>(&[0, 0, 0, 9, 0, 0, 0, 0]),
        Ok(DrinkGarnish::Unknown { discriminant: HLAinteger32BE(9), data: Vec::new() })
    );
    assert_eq!(
        decode_from_slice_strict::<Shapes>(&[9, 0, 0, 0, 0, 0, 0, 3, 1, 2, 3]),
        Ok(Shapes::Unknown { discriminant: HLAoctet(9), data: vec![1, 2, 3] })
    );
}

#[test]
fn dynamic_container_matches_the_typed_layer() {
    let mut record = HLAextendableVariantRecord::new(HLAinteger32BE(0));
    assert_eq!(record.octet_boundary(), 8);
    assert_eq!(record.to_bytes(), Err(EncoderError::NoVariantForDiscriminant));
    record.set_variant(HLAinteger32BE(1), HLAboolean(false)).unwrap();
    record.set_variant(HLAinteger32BE(2), HLAinteger32BE(3)).unwrap();
    assert_eq!(record.to_bytes().unwrap(), encode_to_vec(&DrinkGarnish::OliveCount(3)));
    assert_eq!(record.encoded_length(), Ok(12));

    record.decode_slice_strict(&encode_to_vec(&DrinkGarnish::HasSaltRim(HLAboolean(true)))).unwrap();
    assert_eq!(record.discriminant_as::<HLAinteger32BE>(), Some(&HLAinteger32BE(1)));
    assert_eq!(record.value_as::<HLAboolean>(), Some(&HLAboolean(true)));
    assert_eq!(record.unknown_alternative(), None);

    // Unknown discriminant: decoding succeeds, the value is unavailable, the octets are kept.
    let cream = encode_to_vec(&ExtendedDrinkGarnish::ExtraWhippedCream(HLAboolean(true)));
    record.decode_slice_strict(&cream).unwrap();
    assert_eq!(record.discriminant_as::<HLAinteger32BE>(), Some(&HLAinteger32BE(3)));
    assert_eq!(record.value().err(), Some(EncoderError::NoVariantForDiscriminant));
    assert!(record.value_mut().is_err());
    assert_eq!(record.unknown_alternative(), Some(&[0u8, 0, 0, 1][..]));
    assert_eq!(record.to_bytes(), Err(EncoderError::NoVariantForDiscriminant));

    // Selecting a discriminant forgets the skipped octets.
    record.set_discriminant(HLAinteger32BE(2)).unwrap();
    assert_eq!(record.unknown_alternative(), None);
    record.value_mut().unwrap().downcast_mut::<HLAinteger32BE>().unwrap().0 = 8;
    assert_eq!(record.to_bytes().unwrap(), encode_to_vec(&DrinkGarnish::OliveCount(8)));

    // An enumerator without data.
    record.set_empty_variant(HLAinteger32BE(7)).unwrap();
    assert_eq!(record.to_bytes().as_deref(), Ok(&[0u8, 0, 0, 7, 0, 0, 0, 0][..]));
    assert!(record.value().is_err());
    assert!(record.has_variant(&HLAinteger32BE(7)));

    // Inside a fixed record the fields after it stay where they are.
    let order = HLAfixedRecord::new().with(HLAoctet(4)).with(record.clone()).with(HLAoctet(9));
    assert_eq!(order.octet_boundary(), 8);
    let mut decoded = order.clone();
    let typed = ExtendedOrder {
        table: HLAoctet(1),
        garnish: ExtendedDrinkGarnish::ExtraWhippedCream(HLAboolean(true)),
        priority: HLAoctet(2),
    };
    decoded.decode_slice_strict(&encode_to_vec(&typed)).unwrap();
    assert_eq!(decoded.get_as::<HLAoctet>(0), Some(&HLAoctet(1)));
    assert_eq!(decoded.get_as::<HLAoctet>(2), Some(&HLAoctet(2)));
    let garnish = decoded.get_as::<HLAextendableVariantRecord>(1).unwrap();
    assert_eq!(garnish.unknown_alternative(), Some(&[0u8, 0, 0, 1][..]));
}

#[test]
fn malformed_records() {
    // The alternative datatype must use exactly the announced length.
    assert_eq!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 1, 0, 0, 0, 0]),
        Err(DecoderError::LengthMismatch { declared: 8, consumed: 4 })
    );
    // An enumerator declared without data that receives some: another FOM module gave it an
    // alternative (IEEE 1516.2 4.14.8, annex C), which is passed on like an unknown one.
    let extended = [7, 0, 0, 0, 0, 0, 0, 2, 1, 2];
    assert_eq!(
        decode_from_slice_strict::<Shapes>(&extended),
        Ok(Shapes::Unknown { discriminant: HLAoctet(7), data: vec![1, 2] })
    );
    assert_eq!(encode_to_vec(&Shapes::Unknown { discriminant: HLAoctet(7), data: vec![1, 2] }), extended);
    // The alternative cannot read past the announced length, even if octets follow.
    assert_eq!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1]),
        Err(DecoderError::Truncated { offset: 8, needed: 4, remaining: 2 })
    );
    assert!(matches!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0, 0, 0]),
        Err(DecoderError::Truncated { .. })
    ));
    // The announced length exceeds the input, for known and unknown alternatives alike.
    assert_eq!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 9, 0x7f, 0xff, 0xff, 0xff, 1, 2]),
        Err(DecoderError::Truncated { offset: 8, needed: 0x7fff_ffff, remaining: 2 })
    );
    // encoded_length is an HLAinteger32BE (IEEE 1516.2 4.14.10.3): 0xffffffff is -1, not a length.
    assert!(matches!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 9, 0xff, 0xff, 0xff, 0xff, 1, 2]),
        Err(DecoderError::InvalidValue { type_name: "HLAextendableVariantRecord", .. })
    ));
    assert!(decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0, 0, 4, 0, 0]).is_err());
    assert!(decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0]).is_err());
    // A bad value inside the alternative is reported as such.
    assert!(matches!(
        decode_from_slice::<DrinkGarnish>(&[0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2]),
        Err(DecoderError::InvalidValue { type_name: "HLAboolean", .. })
    ));

    let mut record = HLAextendableVariantRecord::new(HLAinteger32BE(0));
    record.set_variant(HLAinteger32BE(1), HLAboolean(false)).unwrap();
    assert_eq!(
        record.decode_slice(&[0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 1, 0, 0, 0, 0]),
        Err(DecoderError::LengthMismatch { declared: 8, consumed: 4 })
    );
    assert!(record.decode_slice(&[0, 0, 0, 2, 0, 0, 0, 9, 1]).is_err());
}

#[test]
fn layout_functions() {
    let mut buffer = Vec::new();
    let mut writer = ByteWriter::new(&mut buffer);
    writer.put_u8(0xee);
    extendable::begin_encode(&mut writer);
    HLAoctet(6).encode(&mut writer);
    extendable::write_length(&mut writer, 2);
    writer.put_slice(&[1, 2]);
    assert_eq!(writer.status(), Ok(()));
    assert_eq!(buffer, [0xee, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 2, 1, 2]);

    let mut reader = ByteReader::new(&buffer);
    assert_eq!(reader.read_u8(), Ok(0xee));
    extendable::begin_decode(&mut reader).unwrap();
    assert_eq!(HLAoctet::decode(&mut reader), Ok(HLAoctet(6)));
    let mut alternative = extendable::read_alternative(&mut reader).unwrap();
    assert_eq!(alternative.len(), 2);
    assert!(!alternative.is_empty());
    assert_eq!(alternative.reader().read_u8(), Ok(1));
    assert_eq!(alternative.clone().finish(), Err(DecoderError::LengthMismatch { declared: 2, consumed: 1 }));
    assert_eq!(alternative.into_bytes(), [2]);
    assert!(reader.is_empty());

    let mut counter = ByteWriter::counter();
    extendable::write_length(&mut counter, usize::MAX);
    assert_eq!(counter.status(), Err(EncoderError::AlternativeTooLong { length: usize::MAX }));
}