rbs/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use serde::{ser, Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::num::{ParseFloatError, ParseIntError, TryFromIntError};
use std::str::Utf8Error;

#[derive(Debug, Serialize, Deserialize)]
pub enum Error {
    E(String),
}

impl Error {
    pub fn append(self, arg: &str) -> Error {
        match self {
            Error::E(mut e) => {
                e.push_str(arg);
                Error::E(e)
            }
        }
    }
}

impl Error {
    #[allow(dead_code)]
    #[inline]
    pub fn protocol(err: impl Display) -> Self {
        Error::from(format!("ProtocolError {}", err))
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::E(e) => std::fmt::Display::fmt(&e, f),
        }
    }
}

impl std::error::Error for Error {}

impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::E(format!("{}", msg))
    }
}

impl serde::de::Error for Error {
    #[cold]
    fn custom<T: Display>(msg: T) -> Self {
        Error::E(format!("{}", msg))
    }
}

impl From<std::io::Error> for Error {
    fn from(arg: std::io::Error) -> Self {
        Error::from(arg.to_string())
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(e: Utf8Error) -> Self {
        Error::from(e.to_string())
    }
}

impl From<&str> for Error {
    fn from(arg: &str) -> Self {
        Error::from(arg.to_string())
    }
}

impl From<String> for Error {
    fn from(arg: String) -> Self {
        Error::E(arg)
    }
}

impl From<ParseIntError> for Error {
    fn from(arg: ParseIntError) -> Self {
        Error::from(arg.to_string())
    }
}

impl From<ParseFloatError> for Error {
    fn from(arg: ParseFloatError) -> Self {
        Error::from(arg.to_string())
    }
}

impl From<TryFromIntError> for Error {
    fn from(e: TryFromIntError) -> Self {
        Error::from(e.to_string())
    }
}


// Format an error message as a `Protocol` error
#[macro_export]
macro_rules! err_protocol {
    ($expr:expr) => {
        $crate::Error::E($expr.into())
    };

    ($fmt:expr, $($arg:tt)*) => {
        $crate::Error::E(format!($fmt, $($arg)*))
    };
}