nativeview-codec 0.1.0-rc.1

Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives and #[derive(NvCodec)]
Documentation
//! Global-allocator verification proving `0` steady-state heap allocations for reused
//! `ByteWriter` + `ByteReader` + `#[derive(NvCodec)]` encode/decode round-trips, thread-local
//! allocator isolation under background allocation noise, and bounded zero-byte DoS budgets.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use nativeview_codec::{
    call_sync_decode, encode_f32_stack, for_each_padded_le_word, read_flat_op_str_bytes, read_flat_op_str_words_into,
    try_with_stack_writer, validate_flat_op_str_words, with_stack_writer, write_flat_op_str_bytes,
    write_flat_op_str_words, ByteReader, ByteTransport, ByteWriter, CodecError, NvCodec,
    NvDecode, NvEncode, TransportError, DEFAULT_MAX_ITEMS,
};

use nativeview_test_support::count_allocs;
nativeview_test_support::install_counting_allocator!();

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, NvCodec)]
enum Kind {
    Ping = 1,
    Pong = 2,
}

#[derive(Debug, Clone, Copy, PartialEq, NvCodec)]
struct Header {
    kind: Kind,
    seq: u64,
    active: bool,
    scale: f32,
}

#[test]
fn steady_state_reused_codec_allocates_zero_bytes_under_background_alloc_noise() {
    // Spawn a noisy background thread that continuously allocates heap memory to prove our
    // thread-local CountingAlloc never races with parallel test threads.
    let stop = Arc::new(AtomicBool::new(false));
    let stop_bg = Arc::clone(&stop);
    let bg = std::thread::spawn(move || {
        let mut total = 0usize;
        while !stop_bg.load(Ordering::Relaxed) {
            let v: Vec<u8> = Vec::with_capacity(64);
            total = total.wrapping_add(v.capacity());
            std::hint::black_box(v);
        }
        total
    });

    let mut writer = ByteWriter::with_capacity(256);
    let hdr = Header {
        kind: Kind::Pong,
        seq: 42,
        active: true,
        scale: 2.0,
    };

    // Warm buffer once.
    writer.clear();
    hdr.encode(&mut writer).unwrap();
    writer.write_str("nv-steady-state").unwrap();

    let (decoded, allocs) = count_allocs(|| {
        let mut last = hdr;
        for i in 0..128u64 {
            writer.clear();
            let cur = Header { seq: i, ..hdr };
            cur.encode(&mut writer).unwrap();
            writer.write_str("nv-steady-state").unwrap();

            let mut r = ByteReader::new(writer.as_slice());
            last = Header::decode(&mut r).unwrap();
            let label = r.read_str(64).unwrap();
            assert_eq!(label, "nv-steady-state");
            r.finish().unwrap();
        }
        last
    });

    stop.store(true, Ordering::Relaxed);
    let _ = bg.join().unwrap();

    assert_eq!(decoded.seq, 127);
    assert_eq!(
        allocs, 0,
        "steady-state ByteWriter/ByteReader roundtrip must allocate 0 bytes"
    );
}

#[test]
fn adversarial_lying_lengths_allocate_zero_bytes_and_bound_zst_amplification() {
    // 1. Lying length with MIN_ENCODED_BYTES > 0 (Vec<u32>): 0 heap allocations on rejection.
    let lying_u32 = 65_536u32.to_le_bytes();
    let (res_u32, allocs_u32) = count_allocs(|| Vec::<u32>::decode_exact(&lying_u32));
    assert!(matches!(res_u32, Err(CodecError::Truncated { .. })));
    assert_eq!(allocs_u32, 0, "lying Vec<u32> length must allocate 0 bytes");

    // 2. Lying length when caller passes min_elem_bytes == 0: 0 heap allocations on rejection.
    let (res_zero_min, allocs_zero_min) = count_allocs(|| {
        let mut r = ByteReader::new(&lying_u32);
        r.read_vec(DEFAULT_MAX_ITEMS, 0, ByteReader::read_u32)
    });
    assert!(matches!(res_zero_min, Err(CodecError::Truncated { .. })));
    assert_eq!(allocs_zero_min, 0, "lying read_vec(min=0) must allocate 0 bytes");

    // 3. Lying Vec<()> claiming 65_536 ZST elements in 4 bytes: rejected in O(1) with 0 allocs.
    let (res_zst, allocs_zst) = count_allocs(|| Vec::<()>::decode_exact(&lying_u32));
    assert!(matches!(res_zst, Err(CodecError::LenOverflow { .. })));
    assert_eq!(allocs_zst, 0, "lying Vec<()> must allocate 0 bytes");

    // 4. Running-total zero_byte_budget test: 1024 inner Vec<()> each claiming 4000 items.
    // Input is 4100 bytes (budget = 4164), so inner #0 (4000 <= 4164) drains budget to 164 and
    // inner #1 (4000 > 164) MUST trigger `LenOverflow`, exercising `self.zero_byte_budget -= 1`.
    let mut amp = ByteWriter::with_capacity(4 + 1024 * 4);
    amp.write_u32(1024);
    for _ in 0..1024 {
        amp.write_u32(4_000);
    }
    let res_amp = Vec::<Vec<()>>::decode_exact(amp.as_slice());
    assert!(matches!(res_amp, Err(CodecError::LenOverflow { .. })));

    // 5. Direct read_vec(..., 0, ...) counting invocations across multiple inner vectors:
    // total zero-byte invocations must never exceed input_len + 64.
    let input = amp.as_slice();
    let mut r = ByteReader::new(input);
    let outer = r.read_u32().unwrap();
    let mut invocations = 0usize;
    let mut hit_overflow = false;
    for _ in 0..outer {
        match r.read_vec(DEFAULT_MAX_ITEMS, 0, |_| {
            invocations += 1;
            Ok(())
        }) {
            Ok(_) => {}
            Err(CodecError::LenOverflow { .. }) => {
                hit_overflow = true;
                break;
            }
            Err(other) => panic!("unexpected error: {other:?}"),
        }
    }
    assert!(hit_overflow, "running zero_byte_budget must stop multi-vec ZST amplification");
    assert!(
        invocations <= input.len() + 64 + 1,
        "zero-byte callback invocations ({invocations}) exceeded input_len + 64 ({})",
        input.len() + 64
    );
}

#[test]
fn counting_alloc_positive_probe_and_stack_writer_byte_transport_zero_alloc() {
    // Positive control probe: prove CountingAlloc catches real heap allocations.
    let (_, probe_allocs) = count_allocs(|| {
        let v = std::hint::black_box(vec![1u8; 64]);
        v.len()
    });
    assert!(
        probe_allocs >= 1,
        "positive control probe must observe >= 1 heap allocation"
    );

    struct InlineEcho;
    impl ByteTransport for InlineEcho {
        fn call_sync(
            &self,
            _service_id: u32,
            _method_id: u32,
            req: &[u8],
            on_reply: &mut dyn FnMut(&[u8]),
        ) -> Result<(), TransportError> {
            on_reply(req);
            Ok(())
        }

        fn call_async(
            &self,
            _service_id: u32,
            _method_id: u32,
            req: &[u8],
            on_done: nativeview_codec::TransportDoneFn,
        ) {
            on_done(Ok(req));
        }
    }

    let transport = InlineEcho;

    let (sum, fast_allocs) = count_allocs(|| {
        let mut acc = 0u64;
        for i in 0..128u32 {
            let decoded: u64 = try_with_stack_writer::<512, _, TransportError>(
                |w| {
                    w.write_u32(i)?;
                    w.write_str("clipboard.read")?;
                    w.write_bytes(b"zero-alloc-payload")?;
                    w.write_bool(true)
                },
                |req| {
                    call_sync_decode(&transport, 1, 1, req, |reply| {
                        let mut r = ByteReader::new(reply);
                        let seq = r.read_u32()?;
                        let name = r.read_str(64)?;
                        let body = r.read_bytes(64)?;
                        let flag = r.read_bool()?;
                        r.finish()?;
                        assert_eq!(name, "clipboard.read");
                        assert_eq!(body, b"zero-alloc-payload");
                        assert!(flag);
                        Ok(u64::from(seq))
                    })
                },
            )
            .unwrap();
            acc += decoded;

            // Single primitive + canonical float stack round-trip.
            let pod_req = encode_f32_stack(i as f32);
            let pod_out = call_sync_decode(&transport, 1, 1, &pod_req, |reply| {
                let mut r = ByteReader::new(reply);
                let v = r.read_f32()?;
                r.finish()?;
                Ok(v)
            })
            .unwrap();
            assert_eq!(pod_out, i as f32);
        }
        acc
    });
    assert_eq!(sum, (0..128u64).sum::<u64>());
    assert_eq!(
        fast_allocs, 0,
        "with_stack_writer::<512> + ByteTransport::call_sync fast path must allocate 0 bytes"
    );

    // Overflow spills cleanly to Vec<u8> (verified by observing >= 1 allocation).
    let (spilled_len, spill_allocs) = count_allocs(|| {
        with_stack_writer::<16, _>(
            |w| {
                w.write_str("this-payload-exceeds-sixteen-bytes-and-spills-to-heap")
            },
            |bytes| bytes.len(),
        )
        .unwrap()
    });
    assert!(spilled_len > 16);
    assert!(
        spill_allocs >= 1,
        "overflowing StackWriter must spill to heap Vec<u8>"
    );
}

#[test]
fn flat_op_str_helpers_allocate_zero_bytes_in_steady_state() {
    let sample = format!("{}日本語🚀", "a".repeat(254));
    let mut words = Vec::with_capacity(128);
    let mut bytes = Vec::with_capacity(512);
    let mut scratch = String::with_capacity(512);

    assert!(write_flat_op_str_words(&mut words, &sample, 1024));
    assert!(write_flat_op_str_bytes(&mut bytes, &sample, 1024));

    let ((), allocs) = count_allocs(|| {
        for _ in 0..64 {
            words.clear();
            bytes.clear();
            assert!(write_flat_op_str_words(&mut words, &sample, 1024));
            assert!(write_flat_op_str_bytes(&mut bytes, &sample, 1024));

            let mut wp = 0;
            validate_flat_op_str_words(&words, &mut wp, 1024).unwrap();
            assert_eq!(wp, words.len());

            let mut wp2 = 0;
            read_flat_op_str_words_into(&words, &mut wp2, 1024, &mut scratch).unwrap();
            assert_eq!(scratch, sample);
            assert_eq!(wp2, words.len());

            let mut bp = 0;
            let borrowed = read_flat_op_str_bytes(&bytes, &mut bp, 1024).unwrap();
            assert_eq!(borrowed, sample);
            assert_eq!(bp, bytes.len());
        }
    });
    assert_eq!(
        allocs, 0,
        "steady-state flat_op_str encode/validate/decode must allocate 0 bytes"
    );
}

#[test]
fn word_helpers_allocate_zero_bytes_when_warm_and_on_lying_counts() {
    let bytes: Vec<u8> = (0..=255u8).cycle().take(1027).collect();
    let mut words = Vec::with_capacity(256);
    let ((), allocs) = count_allocs(|| {
        for _ in 0..64 {
            words.clear();
            let mut r = ByteReader::new(&bytes);
            r.skip(3).unwrap();
            r.read_u32_words_into(256, &mut words).unwrap();
            r.finish().unwrap();
            let mut hash = 0u32;
            for_each_padded_le_word(&bytes, |w| hash = hash.rotate_left(5) ^ w);
            std::hint::black_box(hash);
        }
    });
    assert_eq!(words.len(), 256);
    assert_eq!(allocs, 0, "warm skip/read_u32_words_into/for_each_padded_le_word must not allocate");

    // A lying word count fails its bounds check before reserving anything.
    let mut cold = Vec::new();
    let (res, lying_allocs) =
        count_allocs(|| ByteReader::new(&bytes).read_u32_words_into(1 << 28, &mut cold));
    assert!(matches!(res, Err(CodecError::Truncated { .. })));
    assert_eq!(lying_allocs, 0);
}