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
use std::{
    error,
    fmt::{self, Display},
    io,
    str::Utf8Error,
    string::FromUtf8Error,
};

use serde::{de, ser};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    Message(Box<str>),
    Eof,
    InvalidBoolEncoding,
    InvalidChar,
    InvalidStr(Utf8Error),

    /// Unsupported error.
    ///
    /// &str is a fat pointer, but &&str is a thin pointer.
    Unsupported(&'static &'static str),
    TooLong,

    IoError(io::Error),
}

impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::Message(msg.to_string().into_boxed_str())
    }
}

impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::Message(msg.to_string().into_boxed_str())
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Message(msg) => f.write_str(msg),
            Error::Eof => f.write_str("EOF"),
            Error::InvalidBoolEncoding => f.write_str("InvalidBoolEncoding"),
            Error::InvalidChar => f.write_str("Invalid char"),
            Error::InvalidStr(err) => write!(f, "Invalid str: {:#?}", err),
            Error::Unsupported(s) => write!(f, "Unsupported {}", s),
            Error::TooLong => f.write_str("Bytes must not be larger than u32::MAX"),
            Error::IoError(io_error) => write!(f, "Io error: {}", io_error),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use Error::*;

        match self {
            InvalidStr(utf8_err) => Some(utf8_err),
            IoError(io_error) => Some(io_error),
            _ => None,
        }
    }
}

impl From<io::Error> for Error {
    fn from(io_error: io::Error) -> Self {
        match io_error.kind() {
            io::ErrorKind::UnexpectedEof => Error::Eof,
            _ => Error::IoError(io_error),
        }
    }
}

impl From<Utf8Error> for Error {
    fn from(utf8_err: Utf8Error) -> Self {
        Error::InvalidStr(utf8_err)
    }
}

impl From<FromUtf8Error> for Error {
    fn from(from_utf8_err: FromUtf8Error) -> Self {
        from_utf8_err.utf8_error().into()
    }
}