use std::{
error::Error as StdError,
fmt::{Debug, Display, Formatter, Result as FmtResult},
};
use crate::world::{Entity, Generation};
pub struct BoxedErr(pub Box<dyn StdError + Send + Sync + 'static>);
impl BoxedErr {
pub fn new<T>(err: T) -> Self
where
T: StdError + Send + Sync + 'static,
{
BoxedErr(Box::new(err))
}
}
impl AsRef<dyn StdError> for BoxedErr {
fn as_ref(&self) -> &(dyn StdError + 'static) {
self.0.as_ref()
}
}
impl Debug for BoxedErr {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{:}", self.0)
}
}
impl Display for BoxedErr {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", self.as_ref())
}
}
impl StdError for BoxedErr {
fn description(&self) -> &str {
self.as_ref().description()
}
}
#[derive(Debug)]
pub enum Error {
Custom(BoxedErr),
WrongGeneration(WrongGeneration),
#[doc(hidden)]
__NonExhaustive,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match *self {
Error::Custom(ref e) => write!(f, "Custom: {}", e),
Error::WrongGeneration(ref e) => write!(f, "Wrong generation: {}", e),
Error::__NonExhaustive => unimplemented!(),
}
}
}
impl From<NoError> for Error {
fn from(e: NoError) -> Self {
match e {}
}
}
impl From<WrongGeneration> for Error {
fn from(e: WrongGeneration) -> Self {
Error::WrongGeneration(e)
}
}
impl StdError for Error {
fn description(&self) -> &str {
"A Specs error"
}
fn cause(&self) -> Option<&dyn StdError> {
let e = match *self {
Error::Custom(ref e) => e.as_ref(),
Error::WrongGeneration(ref e) => e,
Error::__NonExhaustive => unimplemented!(),
};
Some(e)
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct WrongGeneration {
pub action: &'static str,
pub actual_gen: Generation,
pub entity: Entity,
}
impl Display for WrongGeneration {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"Tried to {} entity {:?}, but the generation is wrong; it should be {:?}",
self.action, self.entity, self.actual_gen
)
}
}
impl StdError for WrongGeneration {
fn description(&self) -> &str {
"Used an entity with a generation that is not valid anymore \
(e.g. because the entity has been deleted)"
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum NoError {}
impl Display for NoError {
fn fmt(&self, _: &mut Formatter) -> FmtResult {
match *self {}
}
}
impl StdError for NoError {
fn description(&self) -> &str {
match *self {}
}
}