use std::error;
use std::fmt::{self, Debug, Display, Formatter};
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ErrorKind {
OutOfMemory,
AllocationTooLarge,
UnsupportedAlignment,
IllegalState,
UseAfterFree,
Other,
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ErrorKind::OutOfMemory => write!(f, "Not enough memory remaining to complete request"),
ErrorKind::AllocationTooLarge => {
write!(f, "Allocation exceeds the maximum allowed size for this GC")
}
ErrorKind::UnsupportedAlignment => {
write!(f, "The requested allocation alignment is not supported")
}
ErrorKind::IllegalState => write!(
f,
"Attempted to enter an invalid state to complete this request"
),
ErrorKind::UseAfterFree => {
write!(f, "Attempted to access an object which has been freed")
}
ErrorKind::Other => write!(
f,
"An unknown error occurred while attempting to complete the request"
),
}
}
}
pub struct Error {
kind: ErrorKind,
error: Box<dyn error::Error + Send + Sync>,
}
impl Error {
pub fn new<E>(kind: ErrorKind, error: E) -> Self
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Error {
kind,
error: error.into(),
}
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Error::new(kind, format!("{}", kind))
}
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {:?}", &self.kind, &self.error)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.kind {
ErrorKind::Other => Display::fmt(&self.error, f),
x => write!(f, "{:?}: {}", x, &self.error),
}
}
}