use std::num::NonZero;
mod transfer;
pub(in crate::buffer) use transfer::Transfer;
use crate::mem::credit;
use storage::alloc;
use crate::buffer::{self, bytes::bounded, resident, storage, write::consume};
#[must_use]
pub struct Slices<'a, const N: usize> {
capacity: NonZero<u32>,
values: [&'a [u8]; N],
}
impl<'a, const N: usize> Slices<'a, N> {
pub const unsafe fn new(capacity: NonZero<u32>, values: [&'a [u8]; N]) -> Self {
Self { capacity, values }
}
pub const fn len(&self) -> NonZero<u32> {
self.capacity
}
pub(in crate::buffer) fn slices(&self) -> &[&'a [u8]; N] {
&self.values
}
}
const _: () = {
assert!(size_of::<Slices<'static, 1>>() == 3 * size_of::<usize>());
assert!(size_of::<Option<Slices<'static, 1>>>() == size_of::<Slices<'static, 1>>());
assert!(size_of::<Slices<'static, 3>>() == 7 * size_of::<usize>());
assert!(size_of::<Option<Slices<'static, 3>>>() == size_of::<Slices<'static, 3>>());
};
impl<'a, const N: usize> Slices<'a, N> {
pub fn try_new(values: [&'a [u8]; N]) -> Result<Option<Self>, consume::Error> {
let capacity = consume::Error::checked_end(0, u32::MAX as usize, &values)?;
Ok(NonZero::<u32>::new(capacity as u32).map(|capacity| {
unsafe { Self::new(capacity, values) }
}))
}
}
impl<const N: usize> Slices<'_, N> {
pub(in crate::buffer) fn try_init<P: buffer::raw::Policy>(
self,
seed: P,
) -> Result<storage::raw::Init<P>, alloc::Error<P::Failure>> {
unsafe { storage::raw::Init::try_copy(self.len(), self.slices(), seed) }
}
pub fn try_owned(self) -> Result<storage::Exact, crate::alloc::Exhausted> {
let inner = self.try_init(()).map_err(alloc::Error::into_alloc)?;
Ok(storage::Exact { inner: Some(inner) })
}
}
impl<'a> Slices<'a, 1> {
pub(in crate::buffer) fn from_source(source: &'a impl bounded::Source) -> Option<Self> {
let bytes = source.as_ref();
NonZero::new(bytes.len() as u32).map(|capacity| {
unsafe { Self::new(capacity, [bytes]) }
})
}
}
impl<const N: usize> Slices<'_, N> {
pub fn try_copy<'d>(
self,
budget: &resident::Budget<'d>,
) -> Result<resident::Exact<'d>, alloc::Error<credit::Error>> {
let init = self.try_init::<resident::Budget<'d>>(*budget)?;
Ok(resident::Exact::from_init(init))
}
}