use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use core::ptr::NonNull;
use super::{Alloc, AllocError, Allocator};
#[cfg(feature = "alloc")]
use super::{Global, GlobalAlloc, GlobalAllocator};
#[cfg(not(feature = "alloc"))]
use super::{Slice, SliceAlloc};
pub const DEFAULT_ARRAY_BUFFER: usize = 4096;
macro_rules! implement {
($id:ident, $ty:ty, $raw_vec:ty, $raw:ty) => {
#[repr(transparent)]
pub struct $id<'buf, const BUF: usize> {
inner: $ty,
_marker: PhantomData<&'buf mut [u8]>,
}
impl<'buf, const BUF: usize> $id<'buf, BUF> {
#[inline]
pub(super) const fn new(inner: $ty) -> Self {
Self {
inner,
_marker: PhantomData,
}
}
}
pub struct DefaultAlloc<'a, T, const BUF: usize> {
inner: $raw,
_marker: PhantomData<&'a ()>,
}
};
}
#[cfg(feature = "alloc")]
implement!(DefaultAllocator, Global, SystemAlloc<T>, GlobalAlloc<T>);
#[cfg(not(feature = "alloc"))]
implement!(
DefaultAllocator,
Slice<'buf>,
SliceAlloc<'a, T>,
SliceAlloc<'a, T>
);
#[cfg(feature = "alloc")]
unsafe impl<const BUF: usize> GlobalAllocator for &DefaultAllocator<'_, BUF> {
#[inline]
fn __do_not_implement() {}
#[inline]
fn new() -> Self {
&const { DefaultAllocator::new(Global::new()) }
}
#[inline]
fn clone_alloc<T>(alloc: &Self::Alloc<T>) -> Self::Alloc<T> {
DefaultAlloc {
inner: <Global as GlobalAllocator>::clone_alloc(&alloc.inner),
_marker: PhantomData,
}
}
#[inline]
fn slice_from_raw_parts<T>(ptr: NonNull<T>, len: usize) -> Self::Alloc<T> {
DefaultAlloc {
inner: Global::slice_from_raw_parts(ptr, len),
_marker: PhantomData,
}
}
}
unsafe impl<'a, const BUF: usize> Allocator for &'a DefaultAllocator<'_, BUF> {
#[inline]
fn __do_not_implement() {}
#[cfg(feature = "alloc")]
const IS_GLOBAL: bool = true;
#[cfg(not(feature = "alloc"))]
const IS_GLOBAL: bool = false;
type Alloc<T> = DefaultAlloc<'a, T, BUF>;
#[inline]
fn alloc<T>(self, value: T) -> Result<Self::Alloc<T>, AllocError> {
Ok(DefaultAlloc {
inner: self.inner.alloc(value)?,
_marker: PhantomData,
})
}
#[inline]
fn alloc_empty<T>(self) -> Self::Alloc<T> {
DefaultAlloc {
inner: self.inner.alloc_empty(),
_marker: PhantomData,
}
}
}
impl<T, const BUF: usize> Alloc<T> for DefaultAlloc<'_, T, BUF> {
#[inline]
fn as_ptr(&self) -> *const T {
Alloc::as_ptr(&self.inner)
}
#[inline]
fn as_mut_ptr(&mut self) -> *mut T {
Alloc::as_mut_ptr(&mut self.inner)
}
#[inline]
fn capacity(&self) -> usize {
self.inner.capacity()
}
#[inline]
fn resize(&mut self, len: usize, additional: usize) -> Result<(), AllocError> {
self.inner.resize(len, additional)
}
#[inline]
fn try_merge<B>(&mut self, this_len: usize, other: B, other_len: usize) -> Result<(), B>
where
B: Alloc<T>,
{
self.inner.try_merge(this_len, other, other_len)
}
}