use std::{num::NonZero, ops};
use crate::{
alloc,
buffer::{
self, hold, resident, segments, storage,
write::{Append, Sink as _, consume},
},
mem::{Rejected, rc},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Zero;
#[derive(Debug)]
#[repr(transparent)]
pub struct NonEmpty<T>(T);
impl<T: buffer::raw::Source> NonEmpty<T> {
pub(in crate::buffer) unsafe fn assume(value: T) -> Self {
Self(value)
}
pub fn try_new(value: T) -> Result<Self, Rejected<T, Zero>> {
if value.as_ref().is_empty() {
return Err(Rejected::new(value, Zero));
}
Ok(Self(value))
}
}
impl<T> NonEmpty<T> {
pub const fn get_ref(&self) -> &T {
&self.0
}
pub fn into_storage(self) -> T {
self.0
}
}
impl NonEmpty<Vec<u8>> {
pub fn try_push(mut value: Vec<u8>, byte: u8) -> Result<Self, Rejected<Vec<u8>, alloc::Error>> {
if let Err(error) = value.write_byte(byte) {
return Err(Rejected::new(value, error));
}
Ok(Self(value))
}
pub fn try_resize(
mut value: Vec<u8>,
len: NonZero<usize>,
byte: u8,
) -> Result<Self, Rejected<Vec<u8>, alloc::Error>> {
let added = len.get().saturating_sub(value.len());
if let Err(error) = Append::new(&mut value).try_fill(added, byte) {
return Err(Rejected::new(value, error));
}
value.truncate(len.get());
Ok(Self(value))
}
pub fn append(&mut self) -> Append<'_> {
Append::new(&mut self.0)
}
pub fn truncate(&mut self, len: NonZero<usize>) {
self.0.truncate(len.get());
}
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for NonEmpty<T> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<T: buffer::Residency> buffer::Residency for NonEmpty<T> {
fn resident(&self) -> usize {
self.0.resident()
}
}
impl<T: AsRef<[u8]>> ops::Deref for NonEmpty<T> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl ops::DerefMut for NonEmpty<Vec<u8>> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut_slice()
}
}
impl<T: AsRef<[u8]>> NonEmpty<T> {
pub(in crate::buffer) fn chunk(&self) -> buffer::raw::Chunk<'_> {
unsafe { buffer::raw::Chunk::new(self.as_ref()) }
}
pub fn len(&self) -> NonZero<usize> {
unsafe { NonZero::new_unchecked(self.0.as_ref().len()) }
}
}
unsafe impl<T: buffer::raw::Source> buffer::raw::Source for NonEmpty<T> {}
unsafe impl<T> buffer::raw::Convert<T> for NonEmpty<T> {
fn into(self) -> T {
self.0
}
}
impl<'d, const N: usize> From<&'d [u8; N]> for NonEmpty<resident::Shared<'d>> {
fn from(bytes: &'d [u8; N]) -> Self {
const { assert!(N != 0) };
Self(resident::Shared::from(bytes.as_slice()))
}
}
impl<T: buffer::raw::Segment> NonEmpty<T> {
pub fn try_clone(&self) -> Result<Self, rc::Error> {
NonEmpty(buffer::View::new(&self.0)).try_retain()
}
pub(in crate::buffer) fn tail(&mut self, amount: usize) -> Option<segments::Tail<'_, T>> {
segments::Tail::new(&mut self.0, amount)
}
pub(in crate::buffer) unsafe fn consume_prefix(&mut self, amount: NonZero<usize>) {
let extent = unsafe { self.0.extent() };
*extent = unsafe { extent.restrict(amount.get()..extent.len()) };
}
pub(in crate::buffer) unsafe fn split_retained(
&mut self,
amount: NonZero<usize>,
edge: T::Backing,
) -> Self {
let extent = unsafe { self.0.extent() };
let prefix = unsafe { extent.restrict(0..amount.get()) };
*extent = unsafe { extent.restrict(amount.get()..extent.len()) };
Self(unsafe { storage::Shared::from_extent(edge, prefix) }.into())
}
}
impl<'d> From<NonEmpty<storage::Shared>> for NonEmpty<resident::Shared<'d>> {
fn from(owner: NonEmpty<storage::Shared>) -> Self {
Self(resident::Shared::from(owner.0))
}
}
impl<'d> NonEmpty<resident::Shared<'d>> {
pub fn try_owned(self) -> Result<NonEmpty<storage::Shared>, Self> {
self.0.try_owned().map(NonEmpty).map_err(Self)
}
pub fn prepare_owned(&mut self) -> Option<&resident::Shared<'d>> {
self.0.prepare_owned()
}
pub(in crate::buffer) fn try_detach(self) -> Result<NonEmpty<storage::Shared>, Self> {
self.0.try_detach().map(NonEmpty).map_err(Self)
}
}
impl<'a, T: buffer::raw::Segment> NonEmpty<buffer::View<'a, T>> {
pub(in crate::buffer) fn clamp(source: &'a T, start: usize, end: usize) -> Option<Self> {
let bytes = source.as_ref();
let end = end.min(bytes.len());
if start >= end {
return None;
}
Some(Self(buffer::View {
source,
proof: &bytes[start..end],
}))
}
pub(in crate::buffer) fn try_retain(&self) -> Result<NonEmpty<T>, rc::Error> {
T::try_share(self).map(NonEmpty)
}
}
impl<S: buffer::raw::Segment> buffer::View<'_, S> {
pub fn try_retain(self) -> Result<S, rc::Error> {
if self.is_empty() {
return Ok(S::EMPTY);
}
S::try_share(&NonEmpty(self))
}
}
impl buffer::raw::Seal for storage::Shared {
type Backing = Option<storage::regions::Tag>;
type Retention = ();
const EMPTY: Self = Self::new();
fn try_copy(
source: Result<buffer::raw::Slices<'_, 1>, consume::Error>,
(): &Self::Retention,
) -> Result<NonEmpty<Self>, hold::CopyError> {
let source = source
.map_err(storage::AllocError::Capacity)
.map_err(hold::CopyError::Storage)?;
let value = source
.try_owned()
.map_err(storage::AllocError::Exhausted)
.map_err(hold::CopyError::Storage)?
.into_shared();
Ok(NonEmpty(value))
}
}
impl<'d> buffer::raw::Seal for resident::Shared<'d> {
type Backing = resident::State<'d>;
type Retention = Option<resident::Budget<'d>>;
const EMPTY: Self = Self::new();
fn try_copy(
source: Result<buffer::raw::Slices<'_, 1>, consume::Error>,
domain: &Self::Retention,
) -> Result<NonEmpty<Self>, hold::CopyError> {
let source = source
.map_err(resident::AllocError::Capacity)
.map_err(hold::CopyError::Resident)?;
let budget = domain
.as_ref()
.ok_or(hold::CopyError::Authority(resident::BindError::Unbound))?;
let value = source
.try_copy(budget)
.map_err(resident::AllocError::from)
.map_err(hold::CopyError::Resident)?
.into_shared();
Ok(NonEmpty(value))
}
}
const _: () = {
assert!(size_of::<NonEmpty<Vec<u8>>>() == size_of::<Vec<u8>>());
assert!(size_of::<Option<NonEmpty<Vec<u8>>>>() == size_of::<Option<Vec<u8>>>());
assert!(
size_of::<NonEmpty<resident::Shared<'static>>>() == size_of::<resident::Shared<'static>>()
);
assert!(
align_of::<NonEmpty<resident::Shared<'static>>>()
== align_of::<resident::Shared<'static>>()
);
assert!(
size_of::<Option<NonEmpty<resident::Shared<'static>>>>()
== size_of::<Option<resident::Shared<'static>>>()
);
assert!(size_of::<NonEmpty<storage::Shared>>() == size_of::<storage::Shared>());
assert!(align_of::<NonEmpty<storage::Shared>>() == align_of::<storage::Shared>());
assert!(size_of::<Option<NonEmpty<storage::Shared>>>() == size_of::<Option<storage::Shared>>());
assert!(
size_of::<NonEmpty<buffer::View<'static, storage::Shared>>>()
== size_of::<buffer::View<'static, storage::Shared>>()
);
};