quacky/
errors.rs

1//! A module to handle errors
2
3/// An error enum
4#[derive(Debug)]
5pub enum Error {
6    /// Io error
7    Io(std::io::Error),
8    /// Utf8 Error
9    Utf8(::std::str::Utf8Error),
10    /// Deprecated feature (in protocol buffer specification)
11    Deprecated(&'static str),
12    /// Unknown wire type
13    UnknownWireType(u8),
14    /// Varint decoding error
15    Varint,
16    /// Error while parsing protocol buffer message
17    Message(String),
18    /// Unexpected map tag
19    Map(u8),
20    /// Out of data when reading from or writing to a byte buffer
21    UnexpectedEndOfBuffer,
22    /// The supplied output buffer is not large enough to serialize the message
23    OutputBufferTooSmall,
24}
25
26/// A wrapper for `Result<T, Error>`
27pub type Result<T> = ::std::result::Result<T, Error>;
28
29impl From<Error> for std::io::Error {
30    fn from(val: Error) -> Self {
31        match val {
32            Error::Io(e) => e,
33            Error::Utf8(e) => std::io::Error::new(std::io::ErrorKind::InvalidData, e),
34            x => std::io::Error::other(x),
35        }
36    }
37}
38
39impl From<std::io::Error> for Error {
40    fn from(e: std::io::Error) -> Error {
41        Error::Io(e)
42    }
43}
44
45impl From<::std::str::Utf8Error> for Error {
46    fn from(e: ::std::str::Utf8Error) -> Error {
47        Error::Utf8(e)
48    }
49}
50
51impl std::error::Error for Error {
52    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
53        match self {
54            Error::Io(e) => Some(e),
55            Error::Utf8(e) => Some(e),
56            _ => None,
57        }
58    }
59}
60
61impl core::fmt::Display for Error {
62    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
63        match self {
64            Error::Io(e) => write!(f, "{e}"),
65            Error::Utf8(e) => write!(f, "{e}"),
66            Error::Deprecated(feature) => write!(f, "Feature '{feature}' has been deprecated"),
67            Error::UnknownWireType(e) => {
68                write!(f, "Unknown wire type '{e}', must be less than 6",)
69            }
70            Error::Varint => write!(f, "Cannot decode varint"),
71            Error::Message(msg) => write!(f, "Error while parsing message: {msg}",),
72            Error::Map(tag) => write!(f, "Unexpected map tag: '{tag}', expecting 1 or 2",),
73            Error::UnexpectedEndOfBuffer => write!(f, "Unexpected end of buffer"),
74            Error::OutputBufferTooSmall => write!(f, "Output buffer too small"),
75        }
76    }
77}