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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright (c) 2019 libeither developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Error Handling

use std::fmt;

/// A result that must include an `Error`
pub type Result<T> = std::result::Result<T, Error>;

/// An error from the `libeither` library
#[derive(Debug)]
pub struct Error {
    /// the code
    code: ErrCode,
    /// the reason
    reason: String,
    /// the description
    description: String,
    /// the kind
    source: Option<ErrSource>,
}

impl Error {
    fn new<U>(code: ErrCode, reason: U, source: Option<ErrSource>) -> Self
    where
        U: Into<String>,
    {
        let reason = reason.into();
        let code_str: &str = code.into();
        let description = format!("{}: {}", code_str, reason.clone());

        Self {
            code,
            reason,
            description,
            source,
        }
    }

    pub(crate) fn extract_left() -> Self {
        Self::new(ErrCode::Left, "Unable to extract Left value", None)
    }

    pub(crate) fn extract_right() -> Self {
        Self::new(ErrCode::Right, "Unable to extract Right value", None)
    }

    pub(crate) fn invalid() -> Self {
        Self::new(ErrCode::Invalid, "Invalid Either", None)
    }
}

impl std::error::Error for Error {
    #[must_use]
    fn description(&self) -> &str {
        &self.description
    }

    #[must_use]
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if let Some(ref x) = self.source {
            Some(x)
        } else {
            None
        }
    }
}

impl fmt::Display for Error {
    #[cfg(feature = "unstable")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use std::error::Error;
        let res = std::error::Error::iter_sources(self).fold(
            self.description().to_string(),
            |mut s, e| {
                s.push_str(&format!(" => {}", e));
                s
            },
        );
        write!(f, "{}", res)
    }

    #[cfg(not(feature = "unstable"))]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.description.to_string())
    }
}

impl From<&str> for Error {
    #[must_use]
    fn from(text: &str) -> Self {
        let split = text.split(':');
        let vec = split.collect::<Vec<&str>>();
        let code = vec.get(0).unwrap_or_else(|| &"");
        let reason = vec.get(1).unwrap_or_else(|| &"");
        Self::new((*code).into(), *reason, None)
    }
}

/// Error Codes
#[derive(Copy, Clone, Debug)]
enum ErrCode {
    /// An error working with the Left
    Left,
    /// An error working with the Right
    Right,
    /// An invalid either
    Invalid,
    /// An unknown error code
    Unknown,
}

impl Into<&str> for ErrCode {
    #[must_use]
    fn into(self) -> &'static str {
        match self {
            Self::Left => "left",
            Self::Right => "right",
            Self::Invalid => "invalid",
            Self::Unknown => "unknown",
        }
    }
}

impl Into<String> for ErrCode {
    #[must_use]
    fn into(self) -> String {
        let tmp: &str = self.into();
        tmp.to_string()
    }
}

impl From<&str> for ErrCode {
    #[must_use]
    fn from(text: &str) -> Self {
        match text {
            "left" => Self::Left,
            "right" => Self::Right,
            "invalid" => Self::Invalid,
            _ => Self::Unknown,
        }
    }
}

macro_rules! dep_error {
    ($error:ty, $kind:expr, $code:expr, $reason:expr) => {
        impl From<$error> for Error {
            #[must_use]
            fn from(inner: $error) -> Self {
                Self::new($code, $reason, Some($kind(inner)))
            }
        }
    };
}

dep_error!(
    std::io::Error,
    ErrSource::Io,
    ErrCode::Unknown,
    "There was an I/O error"
);
#[cfg(all(test, feature = "serde"))]
dep_error!(
    serde_json::Error,
    ErrSource::SerdeJson,
    ErrCode::Unknown,
    "There was an error converting JSON"
);
#[cfg(all(test, feature = "serde"))]
dep_error!(
    toml::de::Error,
    ErrSource::TomlDe,
    ErrCode::Unknown,
    "There was an error deserializing TOML"
);
#[cfg(all(test, feature = "serde"))]
dep_error!(
    toml::ser::Error,
    ErrSource::TomlSer,
    ErrCode::Unknown,
    "There was an error serializing TOML"
);

/// Error Source
#[derive(Debug)]
#[allow(clippy::large_enum_variant, variant_size_differences)]
enum ErrSource {
    /// An I/O error
    Io(std::io::Error),
    /// An error with the serde_json library
    #[cfg(all(test, feature = "serde"))]
    SerdeJson(serde_json::Error),
    /// An error with the toml library
    #[cfg(all(test, feature = "serde"))]
    TomlDe(toml::de::Error),
    /// An error with the toml library
    #[cfg(all(test, feature = "serde"))]
    TomlSer(toml::ser::Error),
}

impl std::error::Error for ErrSource {
    fn description(&self) -> &str {
        match self {
            Self::Io(source) => source.description(),
            #[cfg(all(test, feature = "serde"))]
            Self::SerdeJson(source) => source.description(),
            #[cfg(all(test, feature = "serde"))]
            Self::TomlDe(source) => source.description(),
            #[cfg(all(test, feature = "serde"))]
            Self::TomlSer(source) => source.description(),
        }
    }
}

impl fmt::Display for ErrSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(source) => write!(f, "{}", source),
            #[cfg(all(test, feature = "serde"))]
            Self::SerdeJson(source) => write!(f, "{}", source),
            #[cfg(all(test, feature = "serde"))]
            Self::TomlDe(source) => write!(f, "{}", source),
            #[cfg(all(test, feature = "serde"))]
            Self::TomlSer(source) => write!(f, "{}", source),
        }
    }
}