use std::fmt::{self, Display};
use std::io;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Syntax {
msg: String,
offset: usize,
},
Eof,
TrailingData {
offset: usize,
},
Message(String),
Io(io::Error),
}
impl Error {
pub(crate) fn syntax(msg: impl Into<String>, offset: usize) -> Self {
Error::Syntax {
msg: msg.into(),
offset,
}
}
pub(crate) fn message(msg: impl Into<String>) -> Self {
Error::Message(msg.into())
}
pub fn offset(&self) -> Option<usize> {
match self {
Error::Syntax { offset, .. } | Error::TrailingData { offset } => Some(*offset),
_ => None,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Syntax { msg, offset } => write!(f, "{msg} (at byte offset {offset})"),
Error::Eof => f.write_str("unexpected end of input"),
Error::TrailingData { offset } => {
write!(f, "trailing data after top-level value (at byte offset {offset})")
}
Error::Message(msg) => f.write_str(msg),
Error::Io(err) => Display::fmt(err, f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(err) => Some(err),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
impl serde::ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl serde::de::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}