use std::fmt::{Display, Formatter};
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
DeserializeAnyUnsupported,
EndOfBlock,
BadVarint,
BadBool,
BadChar,
BadString,
BadOption,
BadEnum,
BadLen,
BadIdentifier,
UsizeOverflow,
Custom(String),
Io(std::io::Error),
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Self::Io(err)
}
}
impl From<Error> for std::io::Error {
fn from(err: Error) -> Self {
use std::io::ErrorKind;
if let Error::Io(err) = err {
return err;
}
let kind = match &err {
Error::DeserializeAnyUnsupported => ErrorKind::Unsupported,
Error::EndOfBlock => ErrorKind::UnexpectedEof,
_ => ErrorKind::InvalidData,
};
std::io::Error::new(kind, err)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
use Error::*;
match self {
DeserializeAnyUnsupported => write!(f, "deserialize_any is unsupported"),
EndOfBlock => write!(f, "end of block"),
BadVarint => write!(f, "invalid integer"),
BadBool => write!(f, "invalid bool"),
BadChar => write!(f, "invalid char"),
BadString => write!(f, "invalid string"),
BadOption => write!(f, "invalid option"),
BadIdentifier => write!(f, "invalid identifier"),
BadEnum => write!(f, "invalid enum discriminant"),
BadLen => write!(f, "invalid length"),
UsizeOverflow => write!(f, "usize overflow"),
Custom(msg) => write!(f, "serde error: {msg}"),
Io(err) => write!(f, "IO error: {err}"),
}
}
}
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Error::Custom(msg.to_string())
}
}
impl serde::de::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Error::Custom(msg.to_string())
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;