nettext/src/serde/error.rs

84 lines
2 KiB
Rust

use std;
use std::fmt::{self, Display};
use serde::{de, ser};
use crate::{dec, enc};
pub type Result<T> = std::result::Result<T, Error>;
#[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<enc::Error> for Error {
fn from(e: enc::Error) -> Self {
Error::Encode(e)
}
}
impl<'a> From<dec::DecodeError<'a>> for Error {
fn from(e: dec::DecodeError) -> Self {
Error::Decode(e.to_string())
}
}
impl From<dec::TypeError> for Error {
fn from(e: dec::TypeError) -> Self {
Error::Type(e)
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
impl From<std::num::ParseIntError> for Error {
fn from(x: std::num::ParseIntError) -> Error {
Error::ParseInt(x)
}
}
impl From<std::num::ParseFloatError> for Error {
fn from(x: std::num::ParseFloatError) -> Error {
Error::ParseFloat(x)
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(x: std::string::FromUtf8Error) -> Error {
Error::Utf8(x)
}
}
impl de::Error for Error {
fn custom<T: Display>(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 {}