o3 0.62.0

shared-nothing primitives
Documentation
use std::{hint::black_box, mem::MaybeUninit, num::NonZero};

use o3::buffer::{
    pool,
    storage::{Owned, inline},
    write::{self, Sink, SpareExt as _, consume},
};

#[test]
fn appends_vector_batches() {
    let mut out = Vec::with_capacity(12);
    out.extend_from_slice(b"prefi");
    out.write_byte(b'x').expect("the final prefix byte fits");
    let pointer = out.as_ptr();

    out.write_slices([])
        .expect("an empty batch keeps the prefix");
    out.write_slices([b"xy".as_slice(), &[], b"xy".as_slice()])
        .expect("the existing allocation admits both source occurrences");
    assert_eq!(out.as_ptr(), pointer);
    assert_eq!(out, b"prefixxyxy");

    out.write_slices([b"1234".as_slice(), b"5678".as_slice()])
        .expect("the vector grows for the complete batch");
    assert_eq!(out, b"prefixxyxy12345678");
}

#[test]
fn rejects_pair_atomically() {
    let mut small = inline::Bytes::<6>::new();
    assert!(
        small
            .write_slices([b"abcd".as_slice(), b"efg".as_slice()])
            .is_err()
    );
    assert!(small.as_ref().is_empty());
    small
        .write_slices([b"one", b"two"])
        .expect("the exact batch fits after rejection");
    assert_eq!(small.as_ref(), b"onetwo");

    let pool =
        (pool::Pool::try_new(1, 6)).expect("the single-slot six-byte pooled sink must allocate");
    let mut pooled = (pool.cursor()).expect("the fresh pool has one available buffer");
    assert!(
        pooled
            .write_slices([b"abcd".as_slice(), b"efg".as_slice()])
            .is_err()
    );
    assert!(pooled.as_ref().is_empty());
    pooled
        .write_slices([b"one", b"two"])
        .expect("the exact batch fits after rejection");
    assert_eq!(pooled.as_ref(), b"onetwo");
}

#[test]
fn replaces_inline_suffix() {
    let mut bytes = inline::Bytes::<8>::from_slice(b"original").expect("source bytes");
    assert!(
        matches!(bytes.try_replace(2, 5, [b"ab".as_slice(), b"cd".as_slice()]), Err(error)
        if { let (required, room) = error.into_parts(); (required.get(), room) == (2, 1) })
    );
    assert_eq!(bytes.as_ref(), b"original");
    bytes
        .try_replace(2, 5, [b"x".as_slice(), b"yz".as_slice()])
        .expect("exact replacement");
    assert_eq!(bytes.as_ref(), b"orxyz");
    bytes
        .try_replace(usize::MAX, usize::MAX, [b"end".as_slice()])
        .expect("clamped append");
    assert_eq!(bytes.as_ref(), b"orxyzend");
}

#[test]
fn inline_preserves_suffix() {
    let mut wide = inline::Bytes::<260, u16>::new();
    wide.backing_mut().fill(0xa5);
    wide.write_slice(&[b'a'; 255])
        .expect("the initialized prefix fits");

    assert!(matches!(
        wide.write_slices([&b"abc"[..], &b"def"[..]]),
        Err(error) if {
            let (required, available) = error.into_parts();
            (required.get(), available) == (3, 2)
        }
    ));
    assert_eq!(wide.len(), 255);
    assert_eq!(&wide.backing_mut()[255..], &[0xa5; 5]);

    wide.write_slices([]).expect("an empty batch fits");
    assert_eq!(wide.len(), 255);
    wide.write_slices([&b"ab"[..], &[], &b"cde"[..]])
        .expect("the exact suffix fits across the u8 length boundary");
    assert_eq!(wide.len(), 260);
    assert_eq!(&wide.as_ref()[..255], &[b'a'; 255]);
    assert_eq!(&wide.as_ref()[255..], b"abcde");

    wide.truncate(255);
    wide.as_mut().fill(b'z');
    assert_eq!(wide.as_ref(), &[b'z'; 255]);
    assert_eq!(&wide.backing_mut()[255..], b"abcde");
}

#[test]
fn keeps_rejected_sources() {
    let mut bytes = [0xa5; 8];
    let mut writer = write::raw::Slice::new(&mut bytes);
    writer
        .write_byte(b'a')
        .as_ref()
        .expect("required fixture outcome");
    writer
        .write_slice(b"bc")
        .as_ref()
        .expect("required fixture outcome");
    writer
        .write_slices([])
        .expect("an empty batch keeps the prefix");
    assert!(
        matches!(writer.write_slices([&b"defg"[..], &b"hi"[..]]), Err(error)
        if error.into_parts() == (NonZero::<usize>::MIN.saturating_add(1), 1))
    );
    let written = writer.into_mut();
    assert_eq!(written, b"abc");
    written[0] = b'A';
    assert_eq!(&bytes, b"Abc\xa5\xa5\xa5\xa5\xa5");
    let mut writer = write::raw::Slice::new(&mut bytes[3..]);
    writer
        .write_slices([&b"de"[..], &b"fgh"[..]])
        .as_ref()
        .expect("required fixture outcome");
    assert!(matches!(writer.write_byte(b'c'), Err(error)
        if error.into_parts() == (NonZero::<usize>::MIN, 0)));
    writer
        .write_slices([&[]])
        .as_ref()
        .expect("required fixture outcome");
    assert_eq!(writer.len(), 5);
    assert_eq!(&bytes, b"Abcdefgh");
}

#[test]
fn checks_slice_completion() {
    let mut bytes = [0; 4];
    let mut writer = write::raw::Slice::new(&mut bytes);
    write::Sink::write_slice(&mut writer, b"ab").expect("prefix must fit");
    assert!(matches!(writer.try_complete(), Err(error)
        if { let (expected, actual) = error.into_parts(); (expected.get(), actual) == (4, 2) }));
    let mut writer = write::raw::Slice::new(&mut bytes);
    write::Sink::write_slice(&mut writer, b"abcd").expect("exact output must fit");
    writer.try_complete().expect("complete slice must succeed");
    write::raw::Slice::new(&mut [])
        .try_complete()
        .expect("empty slice is complete");
}

#[test]
fn lent_progress() {
    let mut first = [MaybeUninit::uninit(); 8];
    first[0].write(b'p');
    let mut written = 1usize;
    let mut second = [MaybeUninit::uninit(); 8];
    {
        // SAFETY: this owner retains its initialized one-byte prefix.
        let mut first = unsafe { write::raw::Slice::from_parts(&mut first, &mut written) };
        let mut second = write::raw::Slice::uninit(&mut second);
        {
            let mut stage = first.stage();
            let mut loan = stage.body();
            loan.write_slice(b"a").expect("prefix");
            assert!(
                matches!(loan.write_slices([b"1234".as_slice(), b"567"]), Err(error)
                if { let (required, room) = error.into_parts(); (required.get(), room) == (3, 2) })
            );
            assert_eq!(loan.len(), 1);
            loan = second.reborrow();
            loan.write_slice(b"bc").expect("other parent");
            stage.commit();
        }
        assert_eq!(first.into_mut(), b"pa");
        assert_eq!(second.into_mut(), b"bc");
    }
    assert_eq!(written, 2);
}

#[test]
fn repeats_initialized_tail() {
    let mut bytes = [b'?'; 10];
    let mut writer = write::raw::Slice::new(&mut bytes);
    writer.write_slice(b"xab").expect("prefix");
    let (width, len) = black_box((NonZero::new(2).expect("width"), 4));
    // SAFETY: the last two bytes are initialized and four bytes fit the suffix.
    unsafe { writer.reborrow().repeat(width, len) };
    assert_eq!(writer.into_mut(), b"xababab");
    assert_eq!(&bytes[7..], b"???");
}

#[test]
fn completes_head() {
    let mut bytes = [MaybeUninit::uninit(); 10];
    let mut parent = write::raw::Slice::uninit(&mut bytes);
    parent.write_byte(b'p').expect("existing prefix");
    assert!(matches!(parent.try_split(3, usize::MAX), Err(error)
        if { let (required, room) = error.into_parts(); (required.get(), room) == (usize::MAX, 6) }));
    let mut split = parent.try_split(3, 4).expect("partition");
    split.body().write_slice(b"bc").expect("body first");
    assert_eq!(split.body().into_mut(), b"bc");
    split.head().write_slice(b"ab").expect("partial head");
    assert!(matches!(split.try_commit(), Err(error)
        if { let (expected, actual) = error.into_parts(); (expected.get(), actual) == (3, 2) }));
    assert_eq!(parent.len(), 1);

    let mut split = parent.try_split(3, 4).expect("retry partition");
    split.body().write_slice(b"de").expect("body first");
    split.head().write_slice(b"abc").expect("complete head");
    split.try_commit().expect("contiguous prefix");
    assert_eq!(parent.into_mut(), b"pabcde");
}

#[test]
fn reframes_stage() {
    let mut bytes = [MaybeUninit::uninit(); 16];
    let mut parent = write::raw::Slice::uninit(&mut bytes);
    parent.write_byte(b'p').expect("common fields");
    {
        let mut stage = parent.stage();
        {
            let mut framing = stage.body();
            framing.write_slice(b"old").expect("plain framing");
            let mut body = framing.stage();
            body.body().write_slice(b"body").expect("body bytes");
            assert_eq!(body.body().into_mut(), b"body");
            body.commit();
        }
    }
    assert_eq!(parent.len(), 1);
    parent
        .write_slice(b"much-longer")
        .expect("larger gzip head");
    assert_eq!(parent.into_mut(), b"pmuch-longer");
}

#[test]
fn keeps_usize_length() {
    assert!(
        matches!(consume::Error::check(usize::MAX, usize::MAX - 1), Err(error)
        if { let (expected, actual) = error.into_parts(); (expected.get(), actual) == (usize::MAX, usize::MAX - 1) })
    );
}

#[test]
fn writes_fitting_prefix() {
    let mut owner = (Owned::try_with(3)).expect("the three-byte spare owner must allocate");
    let mut writer = owner.spare();
    assert_eq!(writer.write(b"abcdef"), 3);
    assert_eq!(writer.write(b"x"), 0);
    assert_eq!(writer.write(b""), 0);
    assert_eq!(writer.as_mut_slice(), b"abc");
    write::Commit::commit(writer);
    assert_eq!(owner.as_ref(), b"abc");
}

#[test]
fn drains_original_tail() {
    let mut owner = (Owned::try_with(5)).expect("the staged destination must allocate");
    let bytes = b"abcdef";
    let mut source = bytes.as_slice();
    let mut writer = owner.spare();
    assert_eq!(writer.write(b"p"), 1);
    writer.drain(&mut source);
    assert_eq!(owner.as_ref(), b"pabcd");
    assert_eq!(source, b"ef");
    assert_eq!(source.as_ptr(), bytes[4..].as_ptr());
    owner.spare().drain(&mut source);
    assert_eq!(source, b"ef");
    assert_eq!(owner.as_ref(), b"pabcd");
    let mut empty = Owned::<()>::default();
    empty.spare().drain(&mut source);
    assert_eq!(source, b"ef");
    assert!(empty.is_empty());
}