microrti-encoding 0.4.0

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! What decoding hostile octets costs in memory. An element count or a length comes from the sender and
//! may announce up to 2^31 - 1 elements (IEEE 1516.2 4.14.10.5); a decoder must not reserve what the
//! input cannot hold. The allocations of this test binary are counted (`stats_alloc`, a wrapper of the
//! system allocator: no `unsafe` here), and every decoder (typed, dynamic and FOM-driven) is run on
//! hostile counts and on random and mutated octets: the octets allocated while one input is decoded stay
//! within a constant plus a multiple of its length.
//!
//! One test only in this file, so that nothing else allocates while a decoder is measured. The random
//! part uses the harness of `tests/fuzz/mod.rs` (`MICRORTI_FUZZ_ITERATIONS`, `MICRORTI_FUZZ_SEED`,
//! `MICRORTI_FUZZ_CASE`).

mod fuzz;

use std::alloc::System;

use fuzz::{Campaign, Rng, mutate};
use microrti_encoding::*;
use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc};

#[global_allocator]
static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;

/// Octets allocated while `run` executes.
fn allocated(run: impl FnOnce()) -> usize {
    let region = Region::new(GLOBAL);
    run();
    region.change().bytes_allocated
}

/// A function that decodes octets and drops the result.
type Decode = Box<dyn Fn(&[u8])>;

/// A decoder under test: its name and its function.
type Decoder = (&'static str, Decode);

macro_rules! typed {
    ($($t:ty),+ $(,)?) => {
        vec![$((stringify!($t), Box::new(|bytes: &[u8]| {
            let _ = decode_prefix::<$t>(bytes);
            let _ = decode_from_slice_strict::<$t>(bytes);
        }) as Decode)),+]
    };
}

fn typed_decoders() -> Vec<Decoder> {
    typed![
        HLAoctet,
        HLAbyte,
        HLAboolean,
        HLAASCIIchar,
        HLAunicodeChar,
        HLAoctetPairBE,
        HLAoctetPairLE,
        HLAinteger16BE,
        HLAinteger16LE,
        HLAinteger32BE,
        HLAinteger32LE,
        HLAinteger64BE,
        HLAinteger64LE,
        HLAunsignedInteger8,
        HLAunsignedInteger16BE,
        HLAunsignedInteger16LE,
        HLAunsignedInteger32BE,
        HLAunsignedInteger32LE,
        HLAunsignedInteger64BE,
        HLAunsignedInteger64LE,
        HLAfloat32BE,
        HLAfloat32LE,
        HLAfloat64BE,
        HLAfloat64LE,
        HLAASCIIstring,
        HLAunicodeString,
        String,
        HLAopaqueData,
        HLAfederateHandle,
        HLAobjectClassHandle,
        HLAattributeHandle,
        HLAinteractionClassHandle,
        HLAparameterHandle,
        HLAobjectInstanceHandle,
        HLAdimensionHandle,
        HLAregionHandle,
        HLAtransportationTypeHandle,
        HLAmessageRetractionHandle,
        HLAlogicalTime,
        HLAlogicalTimeInterval,
        HLAtoken,
        Vec<HLAtoken>,
        Vec<HLAoctet>,
        Vec<HLAinteger64BE>,
        Vec<HLAfloat32LE>,
        Vec<String>,
        Vec<Vec<HLAinteger32BE>>,
        Vec<Vec<Vec<HLAunicodeString>>>,
        Vec<HLAopaqueData>,
        [HLAinteger16BE; 3],
        [Vec<HLAoctet>; 2],
        [[HLAfloat64BE; 2]; 2],
        Box<Vec<HLAASCIIstring>>,
    ]
}

fn dynamic_decoders() -> Vec<Decoder> {
    let mut variant = HLAvariantRecord::new(HLAoctet(0));
    variant.set_variant(HLAoctet(1), HLAvariableArray::new(HLAinteger64BE(0))).expect("a variant");
    variant.set_variant(HLAoctet(2), HLAunicodeString::new("")).expect("a variant");
    let mut extendable = HLAextendableVariantRecord::new(HLAinteger32BE(0));
    extendable
        .set_variant(HLAinteger32BE(1), HLAvariableArray::new(HLAopaqueData::default()))
        .expect("a variant");
    let record = HLAfixedRecord::new()
        .with(HLAoctet(0))
        .with(HLAvariableArray::new(HLAvariableArray::new(HLAinteger16BE(0))))
        .with(variant.clone())
        .with(extendable.clone());
    let decoders: Vec<(&'static str, Box<dyn DataElement>)> = vec![
        ("HLAvariableArray of HLAinteger64BE", Box::new(HLAvariableArray::new(HLAinteger64BE(0)))),
        ("HLAvariableArray of HLAunicodeString", Box::new(HLAvariableArray::new(HLAunicodeString::new("")))),
        (
            "HLAfixedArray of HLAvariableArray",
            Box::new(HLAfixedArray::new(HLAvariableArray::new(HLAbyte(0)), 3)),
        ),
        ("HLAvariantRecord", Box::new(variant)),
        ("HLAextendableVariantRecord", Box::new(extendable)),
        ("HLAfixedRecord", Box::new(record)),
    ];
    decoders
        .into_iter()
        .map(|(name, prototype)| {
            let decode: Decode = Box::new(move |bytes: &[u8]| {
                let mut element = prototype.clone();
                let _ = element.decode_slice(bytes);
            });
            (name, decode)
        })
        .collect()
}

#[cfg(feature = "fom")]
fn fom_decoders() -> Vec<Decoder> {
    use microrti_encoding::fom::FomCodec;
    use microrti_fom::{Fdd, parse_module};
    let restaurant =
        std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../fom/RestaurantFOMmodule-2025.xml"))
            .expect("the Restaurant FOM");
    let mut fdd = Fdd::with_standard_mim();
    fdd.merge(&[parse_module("Restaurant.xml", &restaurant).expect("parses")]).expect("merges");
    let codec = std::sync::Arc::new(FomCodec::new(&fdd).expect("a codec"));
    let names: Vec<String> = codec.data_type_names().map(str::to_owned).collect();
    names
        .into_iter()
        .map(|name| {
            let codec = codec.clone();
            let label: &'static str = Box::leak(name.clone().into_boxed_str());
            let decode: Decode = Box::new(move |bytes: &[u8]| {
                let _ = codec.decode_prefix(&name, bytes);
                let _ = codec.decode(&name, bytes);
            });
            (label, decode)
        })
        .collect()
}

#[cfg(not(feature = "fom"))]
fn fom_decoders() -> Vec<Decoder> {
    Vec::new()
}

/// Hostile counts: the largest count, counts just above what follows, a negative count, at the start
/// and after a few octets, followed by little.
fn hostile_counts() -> Vec<Vec<u8>> {
    let mut inputs = Vec::new();
    for count in [0x7fff_ffffu32, 0x7fff_fff0, 0x0100_0000, 0x0000_ffff, 0x8000_0000, 0xffff_ffff, 17] {
        for prefix in [0usize, 1, 4, 8] {
            for tail in [0usize, 3, 16, 64] {
                let mut input = vec![0u8; prefix];
                input.extend_from_slice(&count.to_be_bytes());
                input.extend(std::iter::repeat_n(0x7f, tail));
                inputs.push(input);
            }
        }
    }
    // Counts nested in counts.
    let mut nested = Vec::new();
    for _ in 0..16 {
        nested.extend_from_slice(&0x7fff_ffffu32.to_be_bytes());
    }
    inputs.push(nested);
    inputs
}

/// Most a decoder may allocate for an input of `len` octets: a fixed allowance (one bounded reservation
/// made before the elements are seen is 64 KiB at most in this crate) and a share per octet for what the
/// octets really hold (an element takes at least one octet of input, and some dozens of octets of memory:
/// `Value`, `String`, the boxes of the dynamic elements).
fn allowance(len: usize) -> usize {
    64 * 1024 + 128 * len
}

/// Random octets whose 32-bit words are small numbers half of the time.
fn random_input(rng: &mut Rng) -> Vec<u8> {
    let len = rng.size(512);
    let mut input = rng.bytes(len);
    for at in (0..input.len()).step_by(4) {
        if rng.one_in(2) {
            input[at] = 0;
            if at + 3 < input.len() {
                input[at + 1] = 0;
                input[at + 2] = 0;
                input[at + 3] = rng.below(5) as u8;
            }
        }
    }
    input
}

#[test]
fn decoding_allocates_in_proportion_to_the_input_not_to_its_counts() {
    let mut decoders = typed_decoders();
    decoders.extend(dynamic_decoders());
    decoders.extend(fom_decoders());
    // A reservation of 2^31 elements of any size is far above the allowance: the witness works.
    let witness = allocated(|| drop(Vec::<u8>::with_capacity(1 << 31)));
    assert!(witness > allowance(64), "the allocations are not counted: {witness}");

    let mut most = 0;
    for input in hostile_counts() {
        for (name, decode) in &decoders {
            let used = allocated(|| decode(&input));
            assert!(
                used <= allowance(input.len()),
                "{name}: {used} octets for {} octets of input",
                input.len()
            );
            most = most.max(used);
        }
    }
    eprintln!("encoding-allocation: hostile counts cost at most {most} octets");

    // Random and mutated octets: counts are small often enough for decoding to get far. The inputs to
    // mutate are drawn before the campaign, so that every case depends on its number alone.
    let mut drawer = Rng::new(0x0a11_0ca7_e5ee_d500);
    let seeds: Vec<Vec<u8>> = (0..256).map(|_| random_input(&mut drawer)).collect();
    let mut worst = (0usize, 0usize, "");
    let report = Campaign::new("encoding-allocation", 20000).run(|rng: &mut Rng, _| {
        let mut input = if rng.one_in(2) {
            let mut input = rng.pick(&seeds).clone();
            mutate(rng, &mut input);
            input
        } else {
            random_input(rng)
        };
        if rng.one_in(8) && input.len() >= 4 {
            let at = rng.below(input.len() - 3);
            input[at..at + 4].copy_from_slice(&0x7fff_ffffu32.to_be_bytes());
        }
        let (name, decode) = &decoders[rng.below(decoders.len())];
        let used = allocated(|| decode(&input));
        assert!(used <= allowance(input.len()), "{name}: {used} octets for {} octets of input", input.len());
        if used > worst.0 {
            worst = (used, input.len(), name);
        }
    });
    eprintln!(
        "encoding-allocation: {} inputs over {} decoders; most allocated: {} octets for {} octets ({})",
        report.cases,
        decoders.len(),
        worst.0,
        worst.1,
        worst.2
    );
}