use core::{
alloc::{Layout, LayoutError},
fmt::Display,
};
#[cfg(feature = "std")]
use core::mem::transmute;
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TryReserveError {
kind: TryReserveErrorKind,
}
impl TryReserveError {
#[inline]
#[allow(dead_code)]
pub fn kind(&self) -> TryReserveErrorKind {
self.kind.clone()
}
#[cfg(feature = "std")]
pub fn from_std(error: std::collections::TryReserveError) -> Self {
Self::from(error)
}
#[cfg(feature = "std")]
pub fn from_std_result<T>(
result: Result<T, std::collections::TryReserveError>,
) -> Result<T, Self> {
result.map_err(Self::from_std)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TryReserveErrorKind {
CapacityOverflow,
#[allow(dead_code)]
AllocError {
layout: Layout,
non_exhaustive: (),
},
}
impl From<TryReserveErrorKind> for TryReserveError {
#[inline]
fn from(kind: TryReserveErrorKind) -> Self {
Self { kind }
}
}
impl From<LayoutError> for TryReserveErrorKind {
#[inline]
fn from(_: LayoutError) -> Self {
TryReserveErrorKind::CapacityOverflow
}
}
impl From<LayoutError> for TryReserveError {
fn from(_: LayoutError) -> Self {
TryReserveError {
kind: TryReserveErrorKind::CapacityOverflow,
}
}
}
#[cfg(feature = "std")]
impl From<std::collections::TryReserveError> for TryReserveError {
fn from(value: std::collections::TryReserveError) -> Self {
unsafe { transmute::<std::collections::TryReserveError, TryReserveError>(value) }
}
}
#[cfg(feature = "std")]
impl From<TryReserveErrorKind> for std::collections::TryReserveError {
fn from(value: TryReserveErrorKind) -> Self {
TryReserveError { kind: value }.into()
}
}
#[cfg(feature = "std")]
impl From<TryReserveError> for std::collections::TryReserveError {
fn from(val: TryReserveError) -> Self {
unsafe { transmute::<TryReserveError, std::collections::TryReserveError>(val) }
}
}
impl Display for TryReserveError {
fn fmt(
&self,
fmt: &mut core::fmt::Formatter<'_>,
) -> core::result::Result<(), core::fmt::Error> {
fmt.write_str("memory allocation failed")?;
let reason = match self.kind {
TryReserveErrorKind::CapacityOverflow => {
" because the computed capacity exceeded the collection's maximum"
}
TryReserveErrorKind::AllocError { .. } => {
" because the memory allocator returned an error"
}
};
fmt.write_str(reason)
}
}
impl core::error::Error for TryReserveError {}