use core::fmt;
use core::ptr;
use core::mem::forget;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ErrorKind {
MarkerLimit,
MarkerLocked,
InsufficientMemory,
NotAtEnd,
OutOfOrder,
NotAdjacent,
Overflow,
}
#[derive(Debug)]
pub struct Error<T> {
args: T,
kind: ErrorKind,
}
impl<T> Error<T> {
#[inline]
pub fn new(kind: ErrorKind, args: T) -> Self {
Error { args, kind }
}
#[inline]
pub fn kind(&self) -> ErrorKind {
self.kind
}
#[inline]
pub fn args(&self) -> &T {
&self.args
}
#[inline]
pub fn unwrap_args(self) -> T {
unsafe {
let args = ptr::read(&self.args);
forget(self);
args
}
}
#[inline]
pub fn map<U, F>(self, op: F) -> Error<U>
where
F: FnOnce(T) -> U,
{
let kind = self.kind;
let args = op(self.unwrap_args());
Error { args, kind }
}
}
impl<T> fmt::Display for Error<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ErrorKind::MarkerLimit => {
write!(f, "scratchpad marker limit reached")
}
ErrorKind::MarkerLocked => {
write!(f, "marker is not the most recent active marker")
}
ErrorKind::InsufficientMemory => {
write!(f, "insufficient allocation buffer space")
}
ErrorKind::NotAtEnd => {
write!(f, "allocation not most recent from its marker")
}
ErrorKind::OutOfOrder => {
write!(f, "allocations specified out-of-order")
}
ErrorKind::NotAdjacent => {
write!(f, "allocations are not adjacent in memory")
}
ErrorKind::Overflow => write!(f, "integer overflow"),
}
}
}
#[cfg(feature = "std")]
impl<T> ::std::error::Error for Error<T>
where
T: fmt::Debug,
{
#[inline]
fn description(&self) -> &str {
match self.kind {
ErrorKind::MarkerLimit => "scratchpad marker limit reached",
ErrorKind::MarkerLocked => {
"marker is not the most recent active marker"
}
ErrorKind::InsufficientMemory => {
"insufficient allocation buffer space"
}
ErrorKind::NotAtEnd => {
"allocation not most recent from its marker"
}
ErrorKind::OutOfOrder => "allocations specified out-of-order",
ErrorKind::NotAdjacent => {
"allocations are not adjacent in memory"
}
ErrorKind::Overflow => "integer overflow",
}
}
}