mod context;
use alloc::{borrow::Cow, boxed::Box, string::String};
use core::fmt::Display;
pub use context::{Context, Location};
#[derive(Debug)]
pub struct Error {
context: Context,
kind: ErrorKind,
}
impl core::error::Error for Error {}
impl Error {
pub fn new(kind: ErrorKind) -> Error {
Error {
context: Context::new(),
kind,
}
}
pub fn custom(error: impl core::error::Error + Send + Sync + 'static) -> Error {
Error::new(ErrorKind::Custom(Box::new(error)))
}
pub fn custom_str(error: &'static str) -> Error {
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct StrError(pub &'static str);
Error::new(ErrorKind::Custom(Box::new(StrError(error))))
}
pub fn custom_string(error: String) -> Error {
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct StringError(String);
Error::new(ErrorKind::Custom(Box::new(StringError(error))))
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
pub fn context(&self) -> &Context {
&self.context
}
pub fn at(mut self, loc: Location) -> Self {
self.context.push(loc);
Error {
context: self.context,
kind: self.kind,
}
}
pub fn at_idx(mut self, idx: usize) -> Self {
self.context.push(Location::idx(idx));
Error {
context: self.context,
kind: self.kind,
}
}
pub fn at_field(mut self, field: impl Into<Cow<'static, str>>) -> Self {
self.context.push(Location::field(field));
Error {
context: self.context,
kind: self.kind,
}
}
pub fn at_variant(mut self, variant: impl Into<Cow<'static, str>>) -> Self {
self.context.push(Location::variant(variant));
Error {
context: self.context,
kind: self.kind,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let path = self.context.path();
let kind = &self.kind;
write!(f, "Error at {path}: {kind}")
}
}
#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
#[error("Failed to resolve type: {0}")]
TypeResolvingError(String),
#[error("Cannot find type with identifier {0}")]
TypeNotFound(String),
#[error("Cannot encode {actual:?} into type with ID {expected_id}")]
WrongShape {
actual: Kind,
expected_id: String,
},
#[error("Cannot encode to type; expected length {expected_len} but got length {actual_len}")]
WrongLength {
actual_len: usize,
expected_len: usize,
},
#[error("Number {value} is out of range for target type with identifier {expected_id}")]
NumberOutOfRange {
value: String,
expected_id: String,
},
#[error("Variant {name} does not exist on type with identifier {expected_id}")]
CannotFindVariant {
name: String,
expected_id: String,
},
#[error("Field {name} does not exist in our source struct")]
CannotFindField {
name: String,
},
#[error("Custom error: {0}")]
Custom(Box<dyn core::error::Error + Send + Sync + 'static>),
}
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Kind {
Struct,
Tuple,
Variant,
Array,
BitSequence,
Bool,
Char,
Str,
Number,
}