o3 0.60.0

shared-nothing primitives
Documentation
use std::{iter, mem, num::NonZero};

pub use prefix::Prefix;
pub(crate) use retain::Retain;
use crate::buffer::storage;

pub mod bounded;
mod prefix;
mod retain;
pub mod scope;
pub mod window;
/// Read-only bytes with an explicit fallible transition beyond their callback.
pub trait TryRetain: Retain + AsRef<[u8]> + Sized {
    fn try_retain(self) -> Result<storage::Shared, storage::AllocError>;
}
/// An explicit choice between borrowed bytes and an independently retained result.
pub enum Source<'a, R> {
    Borrowed(&'a [u8]),
    Owned(R),
}
impl<R: AsRef<[u8]>> AsRef<[u8]> for Source<'_, R> {
    fn as_ref(&self) -> &[u8] {
        match self {
            Self::Borrowed(bytes) => bytes,
            Self::Owned(bytes) => bytes.as_ref(),
        }
    }
}
impl TryRetain for &[u8] {
    fn try_retain(self) -> Result<storage::Shared, storage::AllocError> {
        storage::Shared::try_copy(self)
    }
}
impl<R: TryRetain> TryRetain for Source<'_, R> {
    fn try_retain(self) -> Result<storage::Shared, storage::AllocError> {
        match self {
            Self::Borrowed(bytes) => bytes.try_retain(),
            Self::Owned(bytes) => bytes.try_retain(),
        }
    }
}

/// Disjoint mutable chunks retaining their admitted nonzero width.
#[derive(Debug)]
pub struct ChunksMut<'a> {
    remaining: &'a mut [u8],
    size: NonZero<usize>,
}

impl<'a> ChunksMut<'a> {
    pub fn new(bytes: &'a mut [u8], size: NonZero<usize>) -> Self {
        Self {
            remaining: bytes,
            size,
        }
    }
}

impl<'a> Iterator for ChunksMut<'a> {
    type Item = &'a mut [u8];

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining.is_empty() {
            return None;
        }
        let end = self.size.get().min(self.remaining.len());
        let (chunk, tail) = mem::take(&mut self.remaining).split_at_mut(end);
        self.remaining = tail;
        Some(chunk)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl ExactSizeIterator for ChunksMut<'_> {
    fn len(&self) -> usize {
        self.remaining.len().div_ceil(self.size.get())
    }
}

impl iter::FusedIterator for ChunksMut<'_> {}

const _: () = assert!(size_of::<ChunksMut<'static>>() == 3 * size_of::<usize>());