use alloc::{
borrow::Cow,
string::{
String,
ToString,
},
sync::Arc,
};
use core::{
error::Error,
fmt,
};
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ParseError {
pub what: Cow<'static, str>,
pub at: Option<String>,
pub input: Option<String>,
pub reason: Option<String>,
pub source: Option<Arc<dyn Error + Send + Sync + 'static>>,
}
impl ParseError {
pub fn new(what: impl Into<Cow<'static, str>>) -> Self {
Self {
what: what.into(),
at: None,
input: None,
reason: None,
source: None,
}
}
pub fn at(
mut self,
at: impl fmt::Display,
) -> Self {
self.at = Some(at.to_string());
self
}
pub fn input(
mut self,
input: impl fmt::Display,
) -> Self {
self.input = Some(input.to_string());
self
}
pub fn because(
mut self,
reason: impl fmt::Display,
) -> Self {
self.reason = Some(reason.to_string());
self
}
pub fn with_source<E>(
mut self,
source: E,
) -> Self
where
E: Error + Send + Sync + 'static,
{
self.source = Some(Arc::new(source));
self
}
}
impl fmt::Display for ParseError {
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
if let Some(at) = &self.at {
write!(f, "{at}: ")?;
}
write!(f, "cannot parse {}", self.what)?;
if let Some(input) = &self.input {
write!(f, " {input:?}")?;
}
if let Some(reason) = &self.reason {
write!(f, ": {reason}")?;
} else if let Some(source) = &self.source {
write!(f, ": {source}")?;
}
Ok(())
}
}
impl Error for ParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().and_then(|s| s.source())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_display() {
assert_eq!(
ParseError::new("dtype").input("f99").to_string(),
"cannot parse dtype \"f99\""
);
let int_err = "x".parse::<u32>().unwrap_err();
let e = ParseError::new("grid shape")
.at("--grid")
.with_source(int_err);
assert_eq!(
e.to_string(),
"--grid: cannot parse grid shape: invalid digit found in string"
);
}
}