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<storage::Owned> {
pub fn freeze(self) -> NonEmpty<storage::Shared> {
let owner = std::mem::ManuallyDrop::new(self.0);
let heap = unsafe { std::ptr::read(crate::mem::raw::initialized(&owner.allocation)) };
let shared = unsafe { heap.into_shared().into_range(0, owner.len) }.into();
NonEmpty(shared)
}
}
impl NonEmpty<buffer::pool::Span> {
pub fn try_append<const N: usize>(
mut value: buffer::pool::Span,
source: &[u8; N],
) -> Result<Self, consume::Error> {
const { assert!(N != 0) };
value.try_append(source)?.commit();
Ok(Self(value))
}
pub fn spare(&mut self) -> buffer::write::Spare<'_> {
buffer::write::SpareExt::spare(&mut self.0)
}
pub fn freeze(self) -> NonEmpty<storage::Shared> {
let len = unsafe { NonZero::new_unchecked(self.0.len()) };
NonEmpty(unsafe { buffer::pool::raw::into_nonempty(self.0, 0, len) }.into())
}
}
impl ops::DerefMut for NonEmpty<buffer::pool::Span> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut_slice()
}
}
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> From<NonEmpty<&'d [u8]>> for NonEmpty<resident::Shared<'d>> {
fn from(source: NonEmpty<&'d [u8]>) -> Self {
Self(resident::Shared::from(source.0))
}
}
impl From<storage::regions::Init> for NonEmpty<storage::Shared> {
fn from(source: storage::regions::Init) -> Self {
Self(source.into_buf().into())
}
}
impl NonEmpty<&[u8]> {
pub fn try_copy(self) -> Result<NonEmpty<storage::Shared>, storage::AllocError> {
let len = self.len();
let capacity = NonZero::<u32>::try_from(len).map_err(|_| {
storage::AllocError::Capacity(consume::Error::new(len, u32::MAX as usize))
})?;
let init = unsafe { storage::regions::try_init(capacity, self.0, ()) }?;
Ok(NonEmpty::from(init))
}
}
impl TryFrom<NonEmpty<Vec<u8>>> for NonEmpty<storage::Shared> {
type Error = alloc::Exhausted;
fn try_from(mut source: NonEmpty<Vec<u8>>) -> Result<Self, Self::Error> {
storage::regions::Header::try_allocated(&mut source.0).map(Self)
}
}
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> From<NonEmpty<&mut resident::Shared<'d>>> for NonEmpty<resident::Shared<'d>> {
fn from(source: NonEmpty<&mut resident::Shared<'d>>) -> Self {
Self(std::mem::take(source.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()
}
}
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>>()
);
};