use std::{
convert, marker,
mem::MaybeUninit,
num::NonZero,
ops, ptr,
slice::{from_raw_parts, from_raw_parts_mut},
};
use crate::{
base::num::bounded,
buffer::{
self,
pool::owners,
segments::{self, scatter::Take},
storage::{self, provided, range::Error},
write::consume::{self, scope},
},
mem::{self, Rejected, rc},
};
mod chunks;
mod input;
mod length;
mod limit;
mod output;
mod seal;
mod slices;
mod store;
pub use chunks::Chunks;
pub use input::Input;
pub use length::Length;
pub use limit::Limit;
pub use output::Output;
pub(in crate::buffer) use output::{Exclusive, Prefix};
pub(in crate::buffer) use seal::Seal;
pub use slices::Slices;
pub(in crate::buffer) use slices::Transfer;
pub(in crate::buffer) use store::{Header, Heap};
pub unsafe trait Consume: AsRef<[u8]> {
fn consume<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>);
}
pub unsafe trait Retain: Sized {
fn try_retain(&self) -> Result<Self, rc::Error>;
}
unsafe impl<T: mem::raw::Target> Retain for mem::raw::Owner<T> {
fn try_retain(&self) -> Result<Self, rc::Error> {
self.try_clone()
}
}
unsafe impl<T: Retain> Retain for Option<T> {
fn try_retain(&self) -> Result<Self, rc::Error> {
self.as_ref().map(T::try_retain).transpose()
}
}
pub unsafe trait Source: AsRef<[u8]> {
unsafe fn view(&self, bounds: ops::Range<usize>) -> buffer::View<'_, Self> {
buffer::View {
source: self,
proof: unsafe { self.as_ref().get_unchecked(bounds) },
}
}
unsafe fn into_str(self) -> storage::Str<Self>
where
Self: Sized,
{
unsafe { storage::Str::new(self) }
}
unsafe fn nonempty(self) -> storage::NonEmpty<Self>
where
Self: Sized,
{
unsafe { storage::raw::present(self) }
}
}
pub unsafe trait Mutable: Source + AsMut<[u8]> {}
pub unsafe trait Split: Mutable {}
pub unsafe trait Freeze: Source + Sized {
type Output: Source;
fn freeze(self) -> Self::Output;
}
pub(in crate::buffer) unsafe fn range<'a>(
pointer: *const u8,
start: usize,
len: usize,
) -> &'a [u8] {
unsafe { from_raw_parts(pointer.add(start), len) }
}
pub(in crate::buffer) unsafe fn range_mut<'a>(
pointer: *mut u8,
start: usize,
len: usize,
) -> &'a mut [u8] {
unsafe { from_raw_parts_mut(pointer.add(start), len) }
}
pub unsafe trait Store: AsRef<[u8]> + Sized {
fn advance<const MAX: u32>(prefix: Input<&mut Self, scope::Prefix<MAX>>) {
let (source, consumed) = prefix.into_parts();
let end = source.as_ref().len();
Self::project(unsafe { Input::from_parts(source, consumed.count().get() as usize..end) });
}
fn empty() -> Option<Self> {
None
}
fn project(slice: Input<&mut Self, ops::Range<usize>>) {
if slice.proof.is_empty()
&& let Some(empty) = Self::empty()
{
*slice.source = empty;
return;
}
Self::restrict(slice);
}
fn try_project(mut self, bounds: ops::Range<usize>) -> Result<Self, Rejected<Self, Error>> {
match Input::try_select(&mut self, bounds) {
Ok(slice) => {
Self::project(slice);
Ok(self)
}
Err(error) => Err(Rejected::new(self, error)),
}
}
fn restrict(slice: Input<&mut Self, ops::Range<usize>>);
}
pub(in crate::buffer) fn select_max<const SUFFIX: bool, S: Store>(
source: &mut S,
max: usize,
) -> usize {
let end = source.as_ref().len();
let start = max.min(end);
Input {
source,
proof: (start, end - start),
}
.project::<SUFFIX>()
}
pub unsafe trait Backing {
const COUNTED: bool = false;
const SLOTS: Option<u32> = None;
const CAPACITY: Option<NonZero<u32>> = None;
unsafe fn release<S>(core: owners::raw::Ptr<Self, S>)
where
Self: Sized,
{
unsafe { core.deallocate() };
}
}
pub trait Policy: Copy {
type Failure;
type Debit: Into<Self>;
fn available(self) -> usize;
fn try_acquire(self, amount: NonZero<u32>) -> Result<Self::Debit, Self::Failure>;
unsafe fn deallocate(self, pointer: ptr::NonNull<u8>, capacity: NonZero<u32>);
}
impl Policy for () {
type Failure = convert::Infallible;
type Debit = ();
fn available(self) -> usize {
usize::MAX
}
fn try_acquire(self, _: NonZero<u32>) -> Result<Self::Debit, Self::Failure> {
Ok(())
}
unsafe fn deallocate(self, pointer: ptr::NonNull<u8>, capacity: NonZero<u32>) {
unsafe { Header::<Self>::free(pointer.cast(), capacity) };
}
}
pub unsafe trait Segment:
Seal + Source + Store + consume::Consume + buffer::Residency
{
unsafe fn extent(&mut self) -> &mut storage::raw::Extent;
fn try_share(view: &storage::NonEmpty<buffer::View<'_, Self>>) -> Result<Self, rc::Error>;
fn try_clone(&self) -> Result<Self, rc::Error> {
buffer::View::new(self).try_retain()
}
fn try_get(&self, range: ops::Range<usize>) -> Result<Option<Self>, rc::Error> {
buffer::View::new(self)
.get(range)
.map(buffer::View::<Self>::try_retain)
.transpose()
}
unsafe fn try_project(&self, range: ops::Range<usize>) -> Result<Self, rc::Error> {
unsafe { Source::view(self, range) }.try_retain()
}
fn prefix(mut self, limit: usize) -> Self {
select_max::<false, _>(&mut self, limit);
self
}
fn try_split(mut self, limit: usize) -> Result<(Self, Option<Self>), (rc::Error, Self)> {
let Some(tail) = segments::Tail::new(&mut self, limit) else {
return Ok((self, None));
};
let prefix = match tail.try_commit() {
Ok(result) => result,
Err(error) => return Err((error, self)),
};
Ok((prefix, Some(self)))
}
fn suffix(mut self, amount: usize) -> Option<Self> {
segments::Tail::new(&mut self, amount)?.commit();
Some(self)
}
}
pub trait Fixed<T> {
fn resident(&self) -> NonZero<u32>;
unsafe fn project<'a, 'id>(&'a self, item: &'a mut T, limit: Limit<'id>)
-> Projection<'a, 'id>;
unsafe fn insert<'d>(
vacant: provided::raw::Vacant<'d, T, (), &'d Self>,
item: T,
) -> provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, ()>>
where
Self: Sized,
{
unsafe { vacant.insert_fixed(item) }
}
}
#[repr(transparent)]
pub struct Projection<'a, 'id> {
bytes: &'a mut [u8],
operation: marker::PhantomData<fn(&'id mut ()) -> &'id mut ()>,
}
impl<'a> Projection<'a, '_> {
pub(in crate::buffer) const fn into_inner(self) -> &'a mut [u8] {
self.bytes
}
}
pub trait IteratorExt<'a>: IntoIterator<Item = &'a [u8]> + Sized {
unsafe fn copy_to(self, target: *mut u8) {
let mut offset = 0;
for source in self {
unsafe { Transfer::copy_to(source, target.add(offset)) };
offset += source.len();
}
}
}
impl<'a, I: IntoIterator<Item = &'a [u8]>> IteratorExt<'a> for I {}
pub unsafe trait Initializer {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]);
}
unsafe impl<const N: usize> Initializer for &[u8; N] {
fn len(&self) -> usize {
N
}
unsafe fn initialize(self, target: &mut [MaybeUninit<u8>]) {
unsafe { Transfer::copy_to(self.as_slice(), target.as_mut_ptr().cast()) };
}
}
#[repr(transparent)]
pub struct Chunk<'data, const MAX: usize = { usize::MAX }> {
bytes: &'data [u8],
}
impl<'data, const MAX: usize> Chunk<'data, MAX> {
pub unsafe fn new(bytes: &'data [u8]) -> Self {
Self { bytes }
}
pub const fn bytes(&self) -> &'data [u8] {
self.bytes
}
pub const fn len(&self) -> bounded::NonZeroUsize<1, MAX> {
unsafe { bounded::raw::nonzero_usize(self.bytes.len()) }
}
}
impl<'a, T: AsRef<[u8]>> From<&'a storage::NonEmpty<T>> for Chunk<'a> {
fn from(owner: &'a storage::NonEmpty<T>) -> Self {
Self {
bytes: owner.as_ref(),
}
}
}
const _: () = {
assert!(size_of::<Chunk<'static>>() == size_of::<&[u8]>());
assert!(size_of::<Option<Chunk<'static>>>() == size_of::<&[u8]>());
};
pub unsafe trait Scatter<'data> {
fn remaining(&self) -> usize;
fn seek(mut self, offset: usize) -> Option<Self>
where
Self: Sized,
{
if offset > self.remaining() {
return None;
}
Take::<_>::new(&mut self, offset).finish();
Some(self)
}
fn take_bytes(&mut self, limit: usize) -> Take<'_, 'data, Self>
where
Self: Sized,
{
Take::<_>::new(self, limit)
}
unsafe fn advance<const MAX: usize>(&mut self, cap: NonZero<usize>) -> Chunk<'data, MAX>;
}
pub unsafe trait Target: AsRef<[u8]> {
fn capacity(&self) -> usize;
fn truncate(&mut self, len: usize);
unsafe fn spare(&mut self) -> &mut [MaybeUninit<u8>];
unsafe fn complete(&mut self, amount: usize);
unsafe fn set_len(&mut self, len: usize);
}