| 1 | //! When serializing or deserializing CBOR goes wrong. |
| 2 | use core::fmt; |
| 3 | use core::result; |
| 4 | use serde::de; |
| 5 | use serde::ser; |
| 6 | #[cfg(feature = "std")] |
| 7 | use std::error; |
| 8 | #[cfg(feature = "std")] |
| 9 | use std::io; |
| 10 | |
| 11 | /// This type represents all possible errors that can occur when serializing or deserializing CBOR |
| 12 | /// data. |
| 13 | pub struct Error(ErrorImpl); |
| 14 | |
| 15 | /// Alias for a `Result` with the error type `serde_cbor::Error`. |
| 16 | pub type Result<T> = result::Result<T, Error>; |
| 17 | |
| 18 | /// Categorizes the cause of a `serde_cbor::Error`. |
| 19 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
| 20 | pub enum Category { |
| 21 | /// The error was caused by a failure to read or write bytes on an IO stream. |
| 22 | Io, |
| 23 | /// The error was caused by input that was not syntactically valid CBOR. |
| 24 | Syntax, |
| 25 | /// The error was caused by input data that was semantically incorrect. |
| 26 | Data, |
| 27 | /// The error was caused by prematurely reaching the end of the input data. |
| 28 | Eof, |
| 29 | } |
| 30 | |
| 31 | impl Error { |
| 32 | /// The byte offset at which the error occurred. |
| 33 | pub fn offset(&self) -> u64 { |
| 34 | self.0.offset |
| 35 | } |
| 36 | |
| 37 | pub(crate) fn syntax(code: ErrorCode, offset: u64) -> Error { |
| 38 | Error(ErrorImpl { code, offset }) |
| 39 | } |
| 40 | |
| 41 | #[cfg(feature = "std")] |
| 42 | pub(crate) fn io(error: io::Error) -> Error { |
| 43 | Error(ErrorImpl { |
| 44 | code: ErrorCode::Io(error), |
| 45 | offset: 0, |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | #[cfg(all(not(feature = "std"), feature = "unsealed_read_write"))] |
| 50 | /// Creates an error signalling that the underlying `Read` encountered an I/O error. |
| 51 | pub fn io() -> Error { |
| 52 | Error(ErrorImpl { |
| 53 | code: ErrorCode::Io, |
| 54 | offset: 0, |
| 55 | }) |
| 56 | } |
| 57 | |
| 58 | #[cfg(feature = "unsealed_read_write")] |
| 59 | /// Creates an error signalling that the scratch buffer was too small to fit the data. |
| 60 | pub fn scratch_too_small(offset: u64) -> Error { |
| 61 | Error(ErrorImpl { |
| 62 | code: ErrorCode::ScratchTooSmall, |
| 63 | offset, |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | #[cfg(not(feature = "unsealed_read_write"))] |
| 68 | pub(crate) fn scratch_too_small(offset: u64) -> Error { |
| 69 | Error(ErrorImpl { |
| 70 | code: ErrorCode::ScratchTooSmall, |
| 71 | offset, |
| 72 | }) |
| 73 | } |
| 74 | |
| 75 | #[cfg(feature = "unsealed_read_write")] |
| 76 | /// Creates an error with a custom message. |
| 77 | /// |
| 78 | /// **Note**: When the "std" feature is disabled, the message will be discarded. |
| 79 | pub fn message<T: fmt::Display>(_msg: T) -> Error { |
| 80 | #[cfg(not(feature = "std"))] |
| 81 | { |
| 82 | Error(ErrorImpl { |
| 83 | code: ErrorCode::Message, |
| 84 | offset: 0, |
| 85 | }) |
| 86 | } |
| 87 | #[cfg(feature = "std")] |
| 88 | { |
| 89 | Error(ErrorImpl { |
| 90 | code: ErrorCode::Message(_msg.to_string()), |
| 91 | offset: 0, |
| 92 | }) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | #[cfg(not(feature = "unsealed_read_write"))] |
| 97 | pub(crate) fn message<T: fmt::Display>(_msg: T) -> Error { |
| 98 | #[cfg(not(feature = "std"))] |
| 99 | { |
| 100 | Error(ErrorImpl { |
| 101 | code: ErrorCode::Message, |
| 102 | offset: 0, |
| 103 | }) |
| 104 | } |
| 105 | #[cfg(feature = "std")] |
| 106 | { |
| 107 | Error(ErrorImpl { |
| 108 | code: ErrorCode::Message(_msg.to_string()), |
| 109 | offset: 0, |
| 110 | }) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | #[cfg(feature = "unsealed_read_write")] |
| 115 | /// Creates an error signalling that the underlying read |
| 116 | /// encountered an end of input. |
| 117 | pub fn eof(offset: u64) -> Error { |
| 118 | Error(ErrorImpl { |
| 119 | code: ErrorCode::EofWhileParsingValue, |
| 120 | offset, |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | /// Categorizes the cause of this error. |
| 125 | pub fn classify(&self) -> Category { |
| 126 | match self.0.code { |
| 127 | #[cfg(feature = "std")] |
| 128 | ErrorCode::Message(_) => Category::Data, |
| 129 | #[cfg(not(feature = "std"))] |
| 130 | ErrorCode::Message => Category::Data, |
| 131 | #[cfg(feature = "std")] |
| 132 | ErrorCode::Io(_) => Category::Io, |
| 133 | #[cfg(not(feature = "std"))] |
| 134 | ErrorCode::Io => Category::Io, |
| 135 | ErrorCode::ScratchTooSmall => Category::Io, |
| 136 | ErrorCode::EofWhileParsingValue |
| 137 | | ErrorCode::EofWhileParsingArray |
| 138 | | ErrorCode::EofWhileParsingMap => Category::Eof, |
| 139 | ErrorCode::LengthOutOfRange |
| 140 | | ErrorCode::InvalidUtf8 |
| 141 | | ErrorCode::UnassignedCode |
| 142 | | ErrorCode::UnexpectedCode |
| 143 | | ErrorCode::TrailingData |
| 144 | | ErrorCode::ArrayTooShort |
| 145 | | ErrorCode::ArrayTooLong |
| 146 | | ErrorCode::RecursionLimitExceeded |
| 147 | | ErrorCode::WrongEnumFormat |
| 148 | | ErrorCode::WrongStructFormat => Category::Syntax, |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// Returns true if this error was caused by a failure to read or write bytes on an IO stream. |
| 153 | pub fn is_io(&self) -> bool { |
| 154 | matches!(self.classify(), Category::Io) |
| 155 | } |
| 156 | |
| 157 | /// Returns true if this error was caused by input that was not syntactically valid CBOR. |
| 158 | pub fn is_syntax(&self) -> bool { |
| 159 | matches!(self.classify(), Category::Syntax) |
| 160 | } |
| 161 | |
| 162 | /// Returns true if this error was caused by data that was semantically incorrect. |
| 163 | pub fn is_data(&self) -> bool { |
| 164 | matches!(self.classify(), Category::Data) |
| 165 | } |
| 166 | |
| 167 | /// Returns true if this error was caused by prematurely reaching the end of the input data. |
| 168 | pub fn is_eof(&self) -> bool { |
| 169 | matches!(self.classify(), Category::Eof) |
| 170 | } |
| 171 | |
| 172 | /// Returns true if this error was caused by the scratch buffer being too small. |
| 173 | /// |
| 174 | /// Note this being `true` implies that `is_io()` is also `true`. |
| 175 | pub fn is_scratch_too_small(&self) -> bool { |
| 176 | matches!(self.0.code, ErrorCode::ScratchTooSmall) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | #[cfg(feature = "std")] |
| 181 | impl error::Error for Error { |
| 182 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
| 183 | match self.0.code { |
| 184 | ErrorCode::Io(ref err) => Some(err), |
| 185 | _ => None, |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | impl fmt::Display for Error { |
| 191 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 192 | if self.0.offset == 0 { |
| 193 | fmt::Display::fmt(&self.0.code, f) |
| 194 | } else { |
| 195 | write!(f, "{} at offset {}", self.0.code, self.0.offset) |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl fmt::Debug for Error { |
| 201 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 202 | fmt::Debug::fmt(&self.0, fmt) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | impl de::Error for Error { |
| 207 | fn custom<T: fmt::Display>(msg: T) -> Error { |
| 208 | Error::message(msg) |
| 209 | } |
| 210 | |
| 211 | fn invalid_type(unexp: de::Unexpected<'_>, exp: &dyn de::Expected) -> Error { |
| 212 | if let de::Unexpected::Unit = unexp { |
| 213 | Error::custom(format_args!("invalid type: null, expected {exp}")) |
| 214 | } else { |
| 215 | Error::custom(format_args!("invalid type: {unexp}, expected {exp}")) |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | impl ser::Error for Error { |
| 221 | fn custom<T: fmt::Display>(msg: T) -> Error { |
| 222 | Error::message(msg) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | #[cfg(feature = "std")] |
| 227 | impl From<io::Error> for Error { |
| 228 | fn from(e: io::Error) -> Error { |
| 229 | Error::io(e) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | #[cfg(not(feature = "std"))] |
| 234 | impl From<core::fmt::Error> for Error { |
| 235 | fn from(_: core::fmt::Error) -> Error { |
| 236 | Error(ErrorImpl { |
| 237 | code: ErrorCode::Message, |
| 238 | offset: 0, |
| 239 | }) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | #[derive(Debug)] |
| 244 | struct ErrorImpl { |
| 245 | code: ErrorCode, |
| 246 | offset: u64, |
| 247 | } |
| 248 | |
| 249 | #[derive(Debug)] |
| 250 | pub(crate) enum ErrorCode { |
| 251 | #[cfg(feature = "std")] |
| 252 | Message(String), |
| 253 | #[cfg(not(feature = "std"))] |
| 254 | Message, |
| 255 | #[cfg(feature = "std")] |
| 256 | Io(io::Error), |
| 257 | #[allow(unused)] |
| 258 | #[cfg(not(feature = "std"))] |
| 259 | Io, |
| 260 | ScratchTooSmall, |
| 261 | EofWhileParsingValue, |
| 262 | EofWhileParsingArray, |
| 263 | EofWhileParsingMap, |
| 264 | LengthOutOfRange, |
| 265 | InvalidUtf8, |
| 266 | UnassignedCode, |
| 267 | UnexpectedCode, |
| 268 | TrailingData, |
| 269 | ArrayTooShort, |
| 270 | ArrayTooLong, |
| 271 | RecursionLimitExceeded, |
| 272 | WrongEnumFormat, |
| 273 | WrongStructFormat, |
| 274 | } |
| 275 | |
| 276 | impl fmt::Display for ErrorCode { |
| 277 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 278 | match *self { |
| 279 | #[cfg(feature = "std")] |
| 280 | ErrorCode::Message(ref msg) => f.write_str(msg), |
| 281 | #[cfg(not(feature = "std"))] |
| 282 | ErrorCode::Message => f.write_str("Unknown error"), |
| 283 | #[cfg(feature = "std")] |
| 284 | ErrorCode::Io(ref err) => fmt::Display::fmt(err, f), |
| 285 | #[cfg(not(feature = "std"))] |
| 286 | ErrorCode::Io => f.write_str("Unknown I/O error"), |
| 287 | ErrorCode::ScratchTooSmall => f.write_str("Scratch buffer too small"), |
| 288 | ErrorCode::EofWhileParsingValue => f.write_str("EOF while parsing a value"), |
| 289 | ErrorCode::EofWhileParsingArray => f.write_str("EOF while parsing an array"), |
| 290 | ErrorCode::EofWhileParsingMap => f.write_str("EOF while parsing a map"), |
| 291 | ErrorCode::LengthOutOfRange => f.write_str("length out of range"), |
| 292 | ErrorCode::InvalidUtf8 => f.write_str("invalid UTF-8"), |
| 293 | ErrorCode::UnassignedCode => f.write_str("unassigned type"), |
| 294 | ErrorCode::UnexpectedCode => f.write_str("unexpected code"), |
| 295 | ErrorCode::TrailingData => f.write_str("trailing data"), |
| 296 | ErrorCode::ArrayTooShort => f.write_str("array too short"), |
| 297 | ErrorCode::ArrayTooLong => f.write_str("array too long"), |
| 298 | ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"), |
| 299 | ErrorCode::WrongEnumFormat => f.write_str("wrong enum format"), |
| 300 | ErrorCode::WrongStructFormat => f.write_str("wrong struct format"), |
| 301 | } |
| 302 | } |
| 303 | } |