1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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 {}