use crate::error::{Error, OomOrDynError};
use core::{fmt, mem, ptr::NonNull};
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct OutOfMemory {
inner: NonNull<u8>,
}
unsafe impl Send for OutOfMemory {}
unsafe impl Sync for OutOfMemory {}
impl fmt::Debug for OutOfMemory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OutOfMemory")
.field(
"requested_allocation_size",
&self.requested_allocation_size(),
)
.finish()
}
}
impl fmt::Display for OutOfMemory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"out of memory (failed to allocate {} bytes)",
self.requested_allocation_size()
)
}
}
impl core::error::Error for OutOfMemory {
#[inline]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
None
}
}
impl OutOfMemory {
const _SAME_SIZE_AS_OOM_OR_DYN_ERROR: () =
assert!(mem::size_of::<OutOfMemory>() == mem::size_of::<OomOrDynError>());
const _SAME_ALIGN_AS_OOM_OR_DYN_ERROR: () =
assert!(mem::align_of::<OutOfMemory>() == mem::align_of::<OomOrDynError>());
const _SAME_SIZE_AS_ERROR: () =
assert!(mem::size_of::<OutOfMemory>() == mem::size_of::<Error>());
const _SAME_ALIGN_AS_ERROR: () =
assert!(mem::align_of::<OutOfMemory>() == mem::align_of::<Error>());
#[inline]
pub const fn new(requested_allocation_size: usize) -> Self {
Self {
inner: OomOrDynError::new_oom_ptr(requested_allocation_size),
}
}
#[inline]
pub fn requested_allocation_size(&self) -> usize {
OomOrDynError::oom_size(self.inner)
}
}
impl From<OutOfMemory> for OomOrDynError {
fn from(oom: OutOfMemory) -> Self {
OomOrDynError::new_oom(oom.inner)
}
}