1use std::borrow::Cow;
3use std::fmt;
4
5#[derive(Debug, Eq, PartialEq, Copy, Clone)]
7pub enum ErrorKind {
8 UnsupportedType,
9 Unexpected,
10 MissingField,
11 OutOfRange,
12 WrongLength,
13 EndOfFile,
14}
15
16#[derive(Debug)]
18pub struct Error {
19 kind: ErrorKind,
20 msg: Cow<'static, str>,
21 source: Option<Box<dyn std::error::Error + Send + Sync>>,
22}
23
24impl Error {
25 pub fn new<M: Into<Cow<'static, str>>>(kind: ErrorKind, msg: M) -> Error {
27 Error {
28 kind,
29 msg: msg.into(),
30 source: None,
31 }
32 }
33
34 pub fn with_source<E: std::error::Error + Send + Sync + 'static>(mut self, source: E) -> Self {
36 self.source = Some(Box::new(source));
37 self
38 }
39
40 pub fn kind(&self) -> ErrorKind {
42 self.kind
43 }
44}
45
46impl fmt::Display for Error {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 write!(f, "{:?}: {}", self.kind, self.msg)
49 }
50}
51
52impl std::error::Error for Error {
53 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
54 self.source.as_ref().map(|err| err.as_ref() as _)
55 }
56}