nettext/serde/
error.rs

1use std;
2use std::fmt::{self, Display};
3
4use serde::{de, ser};
5
6use crate::{dec, enc};
7
8/// Result of a serialization/deserialization operation
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Error representing a serialization/deserialization error
12#[derive(Debug)]
13pub enum Error {
14    /// Custom error message
15    Message(String),
16    /// Nettext encoding error
17    Encode(enc::Error),
18    /// Nettext decoding error
19    Decode(String),
20    /// Nettext interpretation error
21    Type(dec::TypeError),
22    /// Cannot parse term as integer
23    ParseInt(std::num::ParseIntError),
24    /// Cannot parse term as float
25    ParseFloat(std::num::ParseFloatError),
26    /// Invalid utf8 byte string
27    Utf8(std::string::FromUtf8Error),
28}
29
30impl From<enc::Error> for Error {
31    fn from(e: enc::Error) -> Self {
32        Error::Encode(e)
33    }
34}
35
36impl<'a> From<dec::DecodeError<'a>> for Error {
37    fn from(e: dec::DecodeError) -> Self {
38        Error::Decode(e.to_string())
39    }
40}
41
42impl From<dec::TypeError> for Error {
43    fn from(e: dec::TypeError) -> Self {
44        Error::Type(e)
45    }
46}
47
48impl ser::Error for Error {
49    fn custom<T: Display>(msg: T) -> Self {
50        Error::Message(msg.to_string())
51    }
52}
53
54impl From<std::num::ParseIntError> for Error {
55    fn from(x: std::num::ParseIntError) -> Error {
56        Error::ParseInt(x)
57    }
58}
59
60impl From<std::num::ParseFloatError> for Error {
61    fn from(x: std::num::ParseFloatError) -> Error {
62        Error::ParseFloat(x)
63    }
64}
65
66impl From<std::string::FromUtf8Error> for Error {
67    fn from(x: std::string::FromUtf8Error) -> Error {
68        Error::Utf8(x)
69    }
70}
71
72impl de::Error for Error {
73    fn custom<T: Display>(msg: T) -> Self {
74        Error::Message(msg.to_string())
75    }
76}
77
78impl Display for Error {
79    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
80        match self {
81            Error::Message(msg) => formatter.write_str(msg),
82            Error::Encode(err) => write!(formatter, "Encode: {}", err),
83            Error::Decode(err) => write!(formatter, "Decode: {}", err),
84            Error::Type(err) => write!(formatter, "Type: {}", err),
85            Error::ParseInt(err) => write!(formatter, "Parse (int): {}", err),
86            Error::ParseFloat(err) => write!(formatter, "Parse (float): {}", err),
87            Error::Utf8(err) => write!(formatter, "Invalid UTF-8 byte sequnence: {}", err),
88        }
89    }
90}
91
92impl std::error::Error for Error {}