use std; use std::fmt::{self, Display}; use serde::{de, ser}; use crate::{dec, enc}; pub type Result = std::result::Result; #[derive(Debug)] pub enum Error { Message(String), Encode(enc::Error), Decode(String), Type(dec::TypeError), ParseInt(std::num::ParseIntError), ParseFloat(std::num::ParseFloatError), Utf8(std::string::FromUtf8Error), } impl From for Error { fn from(e: enc::Error) -> Self { Error::Encode(e) } } impl<'a> From> for Error { fn from(e: dec::DecodeError) -> Self { Error::Decode(e.to_string()) } } impl From for Error { fn from(e: dec::TypeError) -> Self { Error::Type(e) } } impl ser::Error for Error { fn custom(msg: T) -> Self { Error::Message(msg.to_string()) } } impl From for Error { fn from(x: std::num::ParseIntError) -> Error { Error::ParseInt(x) } } impl From for Error { fn from(x: std::num::ParseFloatError) -> Error { Error::ParseFloat(x) } } impl From for Error { fn from(x: std::string::FromUtf8Error) -> Error { Error::Utf8(x) } } impl de::Error for Error { fn custom(msg: T) -> Self { Error::Message(msg.to_string()) } } impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { Error::Message(msg) => formatter.write_str(msg), Error::Encode(err) => write!(formatter, "Encode: {}", err), Error::Decode(err) => write!(formatter, "Decode: {}", err), Error::Type(err) => write!(formatter, "Type: {}", err), Error::ParseInt(err) => write!(formatter, "Parse (int): {}", err), Error::ParseFloat(err) => write!(formatter, "Parse (float): {}", err), Error::Utf8(err) => write!(formatter, "Invalid UTF-8 byte sequnence: {}", err), } } } impl std::error::Error for Error {}