o3 0.62.0

shared-nothing primitives
Documentation
use crate::{alloc, alloc::VecExt as _, buffer::write};
use std::mem;

/// Appends to one vector without exposing or removing its existing prefix.
#[derive(Debug)]
pub struct Append<'a> {
    pub(in crate::buffer::write) out: &'a mut Vec<u8>,
    pub(in crate::buffer::write) start: usize,
}

impl<'a> Append<'a> {
    pub fn new(out: &'a mut Vec<u8>) -> Self {
        let start = out.len();
        Self { out, start }
    }

    pub fn append(&mut self) -> Append<'_> {
        Append::new(self.out)
    }

    /// Retains the owner and starts a new append at its current end.
    pub fn into_append(self) -> Self {
        Self::new(self.out)
    }

    pub fn try_fill(&mut self, len: usize, byte: u8) -> Result<(), alloc::Error> {
        write::raw::fill(self.out, len, byte)
    }

    pub fn try_grow(&mut self, added: usize) -> Result<(), alloc::Error> {
        self.out.try_grow(added)
    }

    pub fn len(&self) -> usize {
        self.out.len() - self.start
    }

    pub fn is_empty(&self) -> bool {
        self.out.len() == self.start
    }

    pub fn start(&self) -> usize {
        self.start
    }

    pub fn into_mut(self) -> &'a mut [u8] {
        write::raw::suffix_mut(self)
    }

    pub fn rollback(self) {
        self.out.truncate(self.start);
    }
}

impl write::Sink for Append<'_> {
    type Error = alloc::Error;

    fn write_slice(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
        self.out.write_slice(bytes)
    }

    fn write_slices<const N: usize>(&mut self, slices: [&[u8]; N]) -> Result<(), Self::Error> {
        self.out.write_slices(slices)
    }
}

impl AsRef<[u8]> for Append<'_> {
    fn as_ref(&self) -> &[u8] {
        write::raw::suffix(self)
    }
}

impl AsMut<[u8]> for Append<'_> {
    fn as_mut(&mut self) -> &mut [u8] {
        write::raw::suffix_mut(Append {
            out: self.out,
            start: self.start,
        })
    }
}

const _: () = {
    assert!(mem::size_of::<Append<'static>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Option<Append<'static>>>() == mem::size_of::<Append<'static>>());
    assert!(!mem::needs_drop::<Append<'static>>());
};