nettext/src/serde/error.rs

93 lines
2.4 KiB
Rust

use std;
use std::fmt::{self, Display};
use serde::{de, ser};
use crate::{dec, enc};
/// Result of a serialization/deserialization operation
pub type Result<T> = std::result::Result<T, Error>;
/// Error representing a serialization/deserialization error
#[derive(Debug)]
pub enum Error {
/// Custom error message
Message(String),
/// Nettext encoding error
Encode(enc::Error),
/// Nettext decoding error
Decode(String),
/// Nettext interpretation error
Type(dec::TypeError),
/// Cannot parse term as integer
ParseInt(std::num::ParseIntError),
/// Cannot parse term as float
ParseFloat(std::num::ParseFloatError),
/// Invalid utf8 byte string
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 {}