use std::borrow::Cow;
use std::fmt;
use std::io;
pub type RttiResult<T> = Result<T, RttiError>;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RttiErrorKind {
Malformed,
OrdinalRange,
Utf8,
UnknownTag,
Truncated,
ShapeLenMismatch,
Collision,
Budget,
NoVariant,
Interpret,
UntypedPointer,
UnregisteredTag,
Set,
Clone,
ForeignFile,
Swap,
Unsupported,
Class,
VecLen,
SchemaMismatch,
Mutator,
DiscWidth,
TooLarge,
Depth,
SharedMove,
OffsetOverflow,
Io(io::ErrorKind),
}
impl RttiErrorKind {
pub fn code(self) -> u16 {
match self {
Self::Malformed => 0x0800,
Self::OrdinalRange => 0x0801,
Self::Utf8 => 0x0802,
Self::UnknownTag => 0x0803,
Self::Truncated => 0x0804,
Self::ShapeLenMismatch => 0x0805,
Self::Collision => 0x0806,
Self::Budget => 0x0807,
Self::NoVariant => 0x0808,
Self::Interpret => 0x0809,
Self::UntypedPointer => 0x080A,
Self::UnregisteredTag => 0x080B,
Self::Set => 0x080D,
Self::Clone => 0x080E,
Self::ForeignFile => 0x080F,
Self::Swap => 0x0810,
Self::Unsupported => 0x0811,
Self::Class => 0x0812,
Self::VecLen => 0x0813,
Self::SchemaMismatch => 0x0814,
Self::Mutator => 0x0815,
Self::DiscWidth => 0x0816,
Self::TooLarge => 0x0817,
Self::Depth => 0x0818,
Self::SharedMove => 0x0819,
Self::OffsetOverflow => 0x081A,
Self::Io(_) => 0x081B,
}
}
pub fn io_kind(self) -> io::ErrorKind {
match self {
Self::OrdinalRange | Self::ForeignFile => io::ErrorKind::NotFound,
Self::Set | Self::Swap | Self::Class | Self::Mutator => io::ErrorKind::InvalidInput,
Self::Unsupported => io::ErrorKind::Unsupported,
Self::Io(k) => k,
_ => io::ErrorKind::InvalidData,
}
}
}
#[derive(Clone, Debug)]
pub struct RttiError {
kind: RttiErrorKind,
msg: Cow<'static, str>,
}
impl RttiError {
pub fn new(kind: RttiErrorKind, msg: Cow<'static, str>) -> Self {
Self { kind, msg }
}
pub fn kind(&self) -> RttiErrorKind {
self.kind
}
pub fn code(&self) -> u16 {
self.kind.code()
}
pub fn message(&self) -> &str {
&self.msg
}
}
impl fmt::Display for RttiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[BSTACK{:04X}] {}", self.kind.code(), self.msg)
}
}
impl std::error::Error for RttiError {}
impl From<io::Error> for RttiError {
fn from(e: io::Error) -> Self {
Self {
kind: RttiErrorKind::Io(e.kind()),
msg: Cow::Owned(e.to_string()),
}
}
}
impl From<RttiError> for io::Error {
fn from(e: RttiError) -> Self {
io::Error::new(e.kind.io_kind(), e)
}
}
macro_rules! rtti_err {
($kind:ident, $lit:literal $(,)?) => {
$crate::rtti::RttiError::new(
$crate::rtti::RttiErrorKind::$kind,
::std::borrow::Cow::Borrowed($lit),
)
};
($kind:ident, $fmt:literal, $($arg:tt)+) => {
$crate::rtti::RttiError::new(
$crate::rtti::RttiErrorKind::$kind,
::std::borrow::Cow::Owned(::std::format!($fmt, $($arg)+)),
)
};
}
pub(crate) use rtti_err;