mindustry logic execution, map- and schematic- parsing and rendering
Make content errors implement Error
| -rw-r--r-- | src/content.rs | 32 | ||||
| -rw-r--r-- | src/team.rs | 11 |
2 files changed, 40 insertions, 3 deletions
diff --git a/src/content.rs b/src/content.rs index 947f2f2..b7bfb9e 100644 --- a/src/content.rs +++ b/src/content.rs @@ -1,7 +1,23 @@ +use std::error::Error; + macro_rules!numeric_enum { ($vis:vis enum $tname:ident for $numeric:ty | $error:ident {$($name:ident $(= $val:literal)?),* $(,)?}) => { + crate::content::numeric_enum!($vis enum $tname for $numeric | $error* {$($name $(= $val)?),*}); + + impl std::fmt::Display for $error + { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result + { + write!(f, "No variant of {} for value {}", stringify!($tname), self.0) + } + } + + impl std::error::Error for $error {} + }; + ($vis:vis enum $tname:ident for $numeric:ty | $error:ident* {$($name:ident $(= $val:literal)?),* $(,)?}) => + { #[repr($numeric)] #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] $vis enum $tname @@ -43,7 +59,7 @@ macro_rules!content_enum { ($vis:vis enum $tname:ident / $ctype:ident for u16 | $error:ident {$($name:ident $(= $val:literal)? => $vname:expr),* $(,)?}) => { - $crate::content::numeric_enum!($vis enum $tname for u16 | $error {$($name $(= $val)?),*}); + $crate::content::numeric_enum!($vis enum $tname for u16 | $error* {$($name $(= $val)?),*}); impl $crate::content::Content for $tname { @@ -65,6 +81,16 @@ macro_rules!content_enum } } } + + impl std::fmt::Display for $error + { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result + { + write!(f, "No content of type {} for value {}", stringify!($ctype), self.0) + } + } + + impl std::error::Error for $error {} }; } pub(crate) use content_enum; @@ -99,14 +125,14 @@ macro_rules!gen_by_id match <$target>::try_from($id) { Ok(v) => Ok(Box::new(v)), - Err(..) => Err($id), + Err(e) => Err(Box::new(e)), } }; } impl Type { - pub fn get(&self, id: u16) -> Result<Box<dyn Content>, u16> + pub fn get(&self, id: u16) -> Result<Box<dyn Content>, Box<dyn Error>> { match self { diff --git a/src/team.rs b/src/team.rs index cb79d2a..123d996 100644 --- a/src/team.rs +++ b/src/team.rs @@ -1,3 +1,4 @@ +use std::error::Error; use std::fmt; use crate::content::{Content, Type}; @@ -73,6 +74,16 @@ impl fmt::Display for Team } } +impl fmt::Display for TryFromU16Error +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result + { + write!(f, "No content of type Team for value {}", self.0) + } +} + +impl Error for TryFromU16Error {} + const TEAM_NAMES: &str = include_str!("../res/team_names.txt"); impl Content for Team |