torrust_serde_bencode/
error.rs1use 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
12pub type Result<T> = StdResult<T, Error>;
14
15#[derive(Debug)]
17pub enum Error {
18 IoError(IoError),
20
21 InvalidType(String),
23
24 InvalidValue(String),
28
29 InvalidLength(String),
31
32 UnknownVariant(String),
34
35 UnknownField(String),
38
39 MissingField(String),
42
43 DuplicateField(String),
45
46 Custom(String),
48
49 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}