use serde::de::Error as DeError;
use serde::de::{Expected, Unexpected};
use serde::ser::Error as SerError;
use std::error::Error as StdError;
use std::fmt;
use std::fmt::Display;
use std::io::Error as IoError;
use std::result::Result as StdResult;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum Error {
IoError(IoError),
InvalidType(String),
InvalidValue(String),
InvalidLength(String),
UnknownVariant(String),
UnknownField(String),
MissingField(String),
DuplicateField(String),
Custom(String),
EndOfStream,
}
impl SerError for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Custom(msg.to_string())
}
}
impl DeError for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Custom(msg.to_string())
}
fn invalid_type(unexpected: Unexpected<'_>, exp: &dyn Expected) -> Self {
Error::InvalidType(format!("Invalid Type: {unexpected} (expected: `{exp}`)"))
}
fn invalid_value(unexpected: Unexpected<'_>, exp: &dyn Expected) -> Self {
Error::InvalidValue(format!("Invalid Value: {unexpected} (expected: `{exp}`)"))
}
fn invalid_length(len: usize, exp: &dyn Expected) -> Self {
Error::InvalidLength(format!("Invalid Length: {len} (expected: {exp})"))
}
fn unknown_variant(field: &str, expected: &'static [&'static str]) -> Self {
Error::UnknownVariant(format!(
"Unknown Variant: `{field}` (expected one of: {expected:?})"
))
}
fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
Error::UnknownField(format!(
"Unknown Field: `{field}` (expected one of: {expected:?})"
))
}
fn missing_field(field: &'static str) -> Self {
Error::MissingField(format!("Missing Field: `{field}`"))
}
fn duplicate_field(field: &'static str) -> Self {
Error::DuplicateField(format!("Duplicate Field: `{field}`"))
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match *self {
Error::IoError(ref error) => Some(error),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match *self {
Error::IoError(ref error) => return error.fmt(f),
Error::InvalidType(ref s)
| Error::InvalidValue(ref s)
| Error::InvalidLength(ref s)
| Error::UnknownVariant(ref s)
| Error::UnknownField(ref s)
| Error::MissingField(ref s)
| Error::DuplicateField(ref s)
| Error::Custom(ref s) => s,
Error::EndOfStream => "End of stream",
};
f.write_str(message)
}
}