ssh_format_error/
lib.rs

1use std::{
2    error,
3    fmt::{self, Display},
4    io,
5    str::Utf8Error,
6    string::FromUtf8Error,
7};
8
9use serde::{de, ser};
10
11pub type Result<T> = std::result::Result<T, Error>;
12
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16    Message(Box<str>),
17    Eof,
18    InvalidBoolEncoding,
19    InvalidChar,
20    InvalidStr(Utf8Error),
21
22    /// Unsupported error.
23    ///
24    /// &str is a fat pointer, but &&str is a thin pointer.
25    Unsupported(&'static &'static str),
26    TooLong,
27
28    IoError(io::Error),
29}
30
31impl ser::Error for Error {
32    fn custom<T: Display>(msg: T) -> Self {
33        Error::Message(msg.to_string().into_boxed_str())
34    }
35}
36
37impl de::Error for Error {
38    fn custom<T: Display>(msg: T) -> Self {
39        Error::Message(msg.to_string().into_boxed_str())
40    }
41}
42
43impl Display for Error {
44    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45        match self {
46            Error::Message(msg) => f.write_str(msg),
47            Error::Eof => f.write_str("EOF"),
48            Error::InvalidBoolEncoding => f.write_str("InvalidBoolEncoding"),
49            Error::InvalidChar => f.write_str("Invalid char"),
50            Error::InvalidStr(err) => write!(f, "Invalid str: {:#?}", err),
51            Error::Unsupported(s) => write!(f, "Unsupported {}", s),
52            Error::TooLong => f.write_str("Bytes must not be larger than u32::MAX"),
53            Error::IoError(io_error) => write!(f, "Io error: {}", io_error),
54        }
55    }
56}
57
58impl error::Error for Error {
59    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
60        use Error::*;
61
62        match self {
63            InvalidStr(utf8_err) => Some(utf8_err),
64            IoError(io_error) => Some(io_error),
65            _ => None,
66        }
67    }
68}
69
70impl From<io::Error> for Error {
71    fn from(io_error: io::Error) -> Self {
72        match io_error.kind() {
73            io::ErrorKind::UnexpectedEof => Error::Eof,
74            _ => Error::IoError(io_error),
75        }
76    }
77}
78
79impl From<Utf8Error> for Error {
80    fn from(utf8_err: Utf8Error) -> Self {
81        Error::InvalidStr(utf8_err)
82    }
83}
84
85impl From<FromUtf8Error> for Error {
86    fn from(from_utf8_err: FromUtf8Error) -> Self {
87        from_utf8_err.utf8_error().into()
88    }
89}