use core::{
alloc::Layout,
error,
fmt,
ptr::NonNull,
};
pub(crate) type MemAddr = NonNull<[u8]>;
pub unsafe trait TrMalloc {
type Err: error::Error;
fn can_support(&self, layout: Layout) -> bool;
fn allocate(
&self,
layout: Layout,
) -> Result<MemAddr, Self::Err>;
unsafe fn deallocate(
&self,
ptr: MemAddr,
layout: Layout,
) -> Result<usize, Self::Err>;
}
#[derive(Debug, Clone, Default)]
pub struct FakeMalloc;
impl FakeMalloc {
pub fn shared() -> &'static FakeMalloc {
static FAKE_ALLOC: FakeMalloc = FakeMalloc;
&FAKE_ALLOC
}
pub fn can_support(&self, _: Layout) -> bool {
false
}
pub fn allocate(&self, _: Layout) -> Result<MemAddr, FakeMallocError> {
Result::Err(FakeMallocError)
}
pub unsafe fn deallocate(
&self,
_: MemAddr,
_: Layout,
) -> Result<usize, FakeMallocError> {
Result::Ok(0usize)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct FakeMallocError;
unsafe impl TrMalloc for FakeMalloc {
type Err = FakeMallocError;
#[inline(always)]
fn can_support(&self, layout: Layout) -> bool {
FakeMalloc::can_support(self, layout)
}
#[inline(always)]
fn allocate(&self, layout: Layout) -> Result<MemAddr, FakeMallocError> {
FakeMalloc::allocate(self, layout)
}
#[inline(always)]
unsafe fn deallocate(&self, ptr: MemAddr, layout: Layout) -> Result<usize, FakeMallocError> {
unsafe { FakeMalloc::deallocate(self, ptr, layout) }
}
}
impl fmt::Display for FakeMallocError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FakeMallocError")
}
}
impl error::Error for FakeMallocError {}
#[cfg(any(test, feature = "core_alloc"))]
pub use crate::core_alloc_::{CoreAlloc, CoreAllocError};