use crate::buffer::{self, storage, write::consume};
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct Exact {
pub(in crate::buffer) inner: Option<storage::raw::Init>,
}
impl Exact {
#[must_use]
pub const fn new() -> Self {
Self { inner: None }
}
pub fn try_copy(bytes: &[u8]) -> Result<Self, storage::AllocError> {
use storage::AllocError;
let Some(slices) = buffer::raw::Slices::try_new([bytes]).map_err(AllocError::Capacity)?
else {
return Ok(Self::new());
};
slices.try_owned().map_err(AllocError::Exhausted)
}
#[must_use]
pub fn into_shared(self) -> storage::Shared {
match self.inner {
Some(inner) => inner.into_buf().into(),
None => storage::Shared::new(),
}
}
}
impl TryFrom<storage::Owned> for Exact {
type Error = consume::Error;
fn try_from(owned: storage::Owned) -> Result<Self, Self::Error> {
Ok(Self {
inner: storage::raw::Init::try_full(owned)?,
})
}
}
impl AsRef<[u8]> for Exact {
fn as_ref(&self) -> &[u8] {
self.inner
.as_ref()
.map_or(&[], storage::raw::Init::as_slice)
}
}
impl buffer::Residency for Exact {
fn resident(&self) -> usize {
self.inner
.as_ref()
.map_or(0, |inner| inner.capacity().get() as usize)
}
}
const _: () = assert!(size_of::<Exact>() == size_of::<usize>());