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
//! A fuzzing harness without external tools: a seeded generator, campaigns whose length the environment
//! sets, and a replay hint when a case fails. The same file is in the tests of every crate that has
//! hostile input campaigns (see `docs/ARCHITECTURE.md`, section 9).
//!
//! * `MICRORTI_FUZZ_ITERATIONS=<n>`: number of cases of every campaign (default: the campaign's own,
//!   a few seconds in all).
//! * `MICRORTI_FUZZ_SEED=<n>`: the seed of every campaign (default: a fixed seed per campaign, so that
//!   the normal suite is deterministic). Every case derives its generator from the seed and its number.
//! * `MICRORTI_FUZZ_CASE=<n>`: plays that case alone (with the seed of the failure).
#![allow(dead_code)]

use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::time::{Duration, Instant};

/// The finalizer of splitmix64.
pub fn mix(mut z: u64) -> u64 {
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// A small deterministic generator (splitmix64).
pub struct Rng(u64);

impl Rng {
    pub fn new(seed: u64) -> Rng {
        Rng(seed)
    }

    pub fn next_u64(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        mix(self.0)
    }

    pub fn next_u32(&mut self) -> u32 {
        (self.next_u64() >> 32) as u32
    }

    /// A number in `0..bound` (0 when `bound` is 0).
    pub fn below(&mut self, bound: usize) -> usize {
        if bound == 0 { 0 } else { (self.next_u64() % bound as u64) as usize }
    }

    /// True once in `n` times on average.
    pub fn one_in(&mut self, n: usize) -> bool {
        self.below(n) == 0
    }

    pub fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
        &items[self.below(items.len())]
    }

    pub fn bytes(&mut self, len: usize) -> Vec<u8> {
        (0..len).map(|_| self.next_u64() as u8).collect()
    }

    /// A length up to `max`: tiny or small most of the time, sometimes anywhere in the range.
    pub fn size(&mut self, max: usize) -> usize {
        match self.below(4) {
            0 => self.below(max.min(3) + 1),
            1 | 2 => self.below(max.min(32) + 1),
            _ => self.below(max + 1),
        }
    }
}

fn variable(name: &str) -> Option<u64> {
    let value = std::env::var(name).ok()?;
    let value = value.trim();
    let parsed = match value.strip_prefix("0x") {
        Some(hex) => u64::from_str_radix(hex, 16),
        None => value.parse(),
    };
    Some(parsed.unwrap_or_else(|_| panic!("{name} must be an unsigned 64-bit integer, not {value:?}")))
}

/// A fixed seed per campaign name (FNV-1a), so that two campaigns do not draw the same inputs.
fn default_seed(name: &str) -> u64 {
    name.bytes()
        .fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3))
}

/// What a campaign did.
#[derive(Debug, Clone, Copy)]
pub struct Report {
    pub cases: u64,
    pub slowest: Duration,
    pub slowest_case: u64,
}

/// A series of cases drawn from one seed.
pub struct Campaign {
    name: &'static str,
    seed: u64,
    cases: u64,
    only: Option<u64>,
}

impl Campaign {
    /// A campaign of `default_cases` cases unless the environment says otherwise.
    pub fn new(name: &'static str, default_cases: u64) -> Campaign {
        Campaign {
            name,
            seed: variable("MICRORTI_FUZZ_SEED").unwrap_or_else(|| default_seed(name)),
            cases: variable("MICRORTI_FUZZ_ITERATIONS").unwrap_or(default_cases),
            only: variable("MICRORTI_FUZZ_CASE"),
        }
    }

    pub fn seed(&self) -> u64 {
        self.seed
    }

    /// The generator of case `number`.
    pub fn rng(&self, number: u64) -> Rng {
        Rng::new(mix(self.seed ^ mix(number.wrapping_add(1))))
    }

    /// How to play case `number` again.
    pub fn replay_hint(&self, number: u64) -> String {
        format!(
            "{}: case {number} failed; replay it alone with MICRORTI_FUZZ_SEED={} MICRORTI_FUZZ_CASE={number}",
            self.name, self.seed
        )
    }

    /// The numbers of the cases to play.
    pub fn numbers(&self) -> std::ops::Range<u64> {
        match self.only {
            Some(number) => number..number + 1,
            None => 0..self.cases,
        }
    }

    /// Plays every case; a case that panics is named with its replay hint before the panic goes on.
    pub fn run(&self, mut case: impl FnMut(&mut Rng, u64)) -> Report {
        let mut report = Report { cases: 0, slowest: Duration::ZERO, slowest_case: 0 };
        for number in self.numbers() {
            let mut rng = self.rng(number);
            let start = Instant::now();
            if let Err(panic) = catch_unwind(AssertUnwindSafe(|| case(&mut rng, number))) {
                eprintln!("{}", self.replay_hint(number));
                resume_unwind(panic);
            }
            let elapsed = start.elapsed();
            if elapsed > report.slowest {
                report.slowest = elapsed;
                report.slowest_case = number;
            }
            report.cases += 1;
        }
        eprintln!(
            "{}: {} cases of seed {}, slowest case {} in {:?}",
            self.name, report.cases, self.seed, report.slowest_case, report.slowest
        );
        report
    }
}

/// Mutates `input` in place a few times: octets replaced, inserted, removed, duplicated, cut.
pub fn mutate(rng: &mut Rng, input: &mut Vec<u8>) {
    const INTERESTING: [u8; 10] = [0x00, 0x01, 0x02, 0x08, 0x7f, 0x80, 0x81, 0xfe, 0xff, b'<'];
    for _ in 0..rng.below(4) + 1 {
        let len = input.len();
        match rng.below(8) {
            0 | 1 if len > 0 => input[rng.below(len)] = rng.next_u64() as u8,
            2 if len > 0 => input[rng.below(len)] = *rng.pick(&INTERESTING),
            3 => {
                let at = rng.below(len + 1);
                let count = rng.size(16);
                let inserted = rng.bytes(count);
                input.splice(at..at, inserted);
            }
            4 if len > 0 => {
                let at = rng.below(len);
                let end = (at + rng.size(16) + 1).min(len);
                input.drain(at..end);
            }
            5 if len > 0 => {
                let at = rng.below(len);
                let end = (at + rng.size(64) + 1).min(len);
                let copy = input[at..end].to_vec();
                let to = rng.below(len + 1);
                input.splice(to..to, copy);
            }
            6 => input.truncate(rng.below(len + 1)),
            _ if len >= 4 => {
                // A 32-bit big-endian field set to an edge value.
                let at = rng.below(len - 3);
                let value: u32 = *rng.pick(&[0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff, 0x0100_0000]);
                input[at..at + 4].copy_from_slice(&value.to_be_bytes());
            }
            _ => input.push(rng.next_u64() as u8),
        }
    }
}

static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Counts every panic of the process from now on, on any thread (tokio tasks and blocking threads
/// included, whose panics a test would not see otherwise), then reports it as before.
pub fn watch_panics() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            PANICS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            previous(info);
        }));
    });
}

/// Panics counted since [`watch_panics`].
pub fn panics() -> usize {
    PANICS.load(std::sync::atomic::Ordering::SeqCst)
}