1use std::fmt::Display;
7
8#[cfg(feature = "alloc")]
9use alloc::string::String;
10
11#[cfg(feature = "alloc")]
12use alloc::string::ToString;
13
14use std::str::Utf8Error;
15
16use std::fmt;
17
18#[derive(Debug)]
20pub enum Error {
21 TooBig,
23
24 EndOfStream,
26
27 BadType,
29
30 BadLength,
32
33 Utf8Error(Utf8Error),
35
36 Other(String),
38}
39
40impl Display for Error {
41 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
42 fmt.write_str(self.description())
43 }
44}
45
46impl Error {
47 fn description(&self) -> &str {
48 match self {
49 &Error::TooBig => "Overflowing value",
50 &Error::EndOfStream => "End of stream",
51 &Error::BadType => "Invalid type",
52 &Error::BadLength => "Invalid length",
53 &Error::Utf8Error(_) => "UTF8 Error",
54 &Error::Other(ref message) => &message,
55 }
56 }
57}
58
59impl From<Utf8Error> for Error {
60 fn from(cause: Utf8Error) -> Error {
61 Error::Utf8Error(cause)
62 }
63}
64
65#[cfg(feature = "std")]
66impl ::std::error::Error for Error {
67 fn description(&self) -> &str {
68 Error::description(self)
69 }
70
71 fn cause(&self) -> Option<&::std::error::Error> {
72 match self {
73 &Error::Utf8Error(ref cause) => Some(cause),
74 _ => None,
75 }
76 }
77}
78
79impl ::serde::ser::Error for Error {
80 fn custom<T: Display>(msg: T) -> Error {
81 Error::Other(msg.to_string())
82 }
83}
84
85impl ::serde::de::Error for Error {
86 fn custom<T: Display>(msg: T) -> Error {
87 ::serde::ser::Error::custom(msg)
88 }
89}