torrust_serde_bencode/
error.rs

1//! Structures used to handle errors when serializing or deserializing goes wrong.
2
3use serde::de::Error as DeError;
4use serde::de::{Expected, Unexpected};
5use serde::ser::Error as SerError;
6use std::error::Error as StdError;
7use std::fmt;
8use std::fmt::Display;
9use std::io::Error as IoError;
10use std::result::Result as StdResult;
11
12/// Alias for `Result<T, serde_bencode::Error>`.
13pub type Result<T> = StdResult<T, Error>;
14
15/// Represents all possible errors which can occur when serializing or deserializing bencode.
16#[derive(Debug)]
17pub enum Error {
18    /// Raised when an IO error occurred.
19    IoError(IoError),
20
21    /// Raised when the value being deserialized is of the incorrect type.
22    InvalidType(String),
23
24    /// Raised when the value being deserialized is of the right type, but is wrong for some other
25    /// reason. For example, this error may occur when deserializing to a String but the input data
26    /// is not valid UTF-8.
27    InvalidValue(String),
28
29    /// Raised when deserializing a sequence or map, but the input data is the wrong length.
30    InvalidLength(String),
31
32    /// Raised when deserializing an enum, but the variant has an unrecognized name.
33    UnknownVariant(String),
34
35    /// Raised when deserializing a struct, but there was a field which does not match any of the
36    /// expected fields.
37    UnknownField(String),
38
39    /// Raised when deserializing a struct, but there was a field which was expected but not
40    /// present.
41    MissingField(String),
42
43    /// Raised when deserializing a struct, but there is more than one field with the same name.
44    DuplicateField(String),
45
46    /// Catchall for any other kind of error.
47    Custom(String),
48
49    /// Unexpected end of input stream.
50    EndOfStream,
51}
52
53impl SerError for Error {
54    fn custom<T: Display>(msg: T) -> Self {
55        Error::Custom(msg.to_string())
56    }
57}
58
59impl DeError for Error {
60    fn custom<T: Display>(msg: T) -> Self {
61        Error::Custom(msg.to_string())
62    }
63
64    fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self {
65        Error::InvalidType(format!("Invalid Type: {} (expected: `{}`)", unexp, exp))
66    }
67
68    fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self {
69        Error::InvalidValue(format!("Invalid Value: {} (expected: `{}`)", unexp, exp))
70    }
71
72    fn invalid_length(len: usize, exp: &dyn Expected) -> Self {
73        Error::InvalidLength(format!("Invalid Length: {} (expected: {})", len, exp))
74    }
75
76    fn unknown_variant(field: &str, expected: &'static [&'static str]) -> Self {
77        Error::UnknownVariant(format!(
78            "Unknown Variant: `{}` (expected one of: {:?})",
79            field, expected
80        ))
81    }
82
83    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
84        Error::UnknownField(format!(
85            "Unknown Field: `{}` (expected one of: {:?})",
86            field, expected
87        ))
88    }
89
90    fn missing_field(field: &'static str) -> Self {
91        Error::MissingField(format!("Missing Field: `{}`", field))
92    }
93
94    fn duplicate_field(field: &'static str) -> Self {
95        Error::DuplicateField(format!("Duplicat Field: `{}`", field))
96    }
97}
98
99impl StdError for Error {
100    fn source(&self) -> Option<&(dyn StdError + 'static)> {
101        match *self {
102            Error::IoError(ref error) => Some(error),
103            _ => None,
104        }
105    }
106}
107
108impl fmt::Display for Error {
109    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110        let message = match *self {
111            Error::IoError(ref error) => return error.fmt(f),
112            Error::InvalidType(ref s) => s,
113            Error::InvalidValue(ref s) => s,
114            Error::InvalidLength(ref s) => s,
115            Error::UnknownVariant(ref s) => s,
116            Error::UnknownField(ref s) => s,
117            Error::MissingField(ref s) => s,
118            Error::DuplicateField(ref s) => s,
119            Error::Custom(ref s) => s,
120            Error::EndOfStream => "End of stream",
121        };
122        f.write_str(message)
123    }
124}