rsdiff_core/
error.rs

1/*
2    Appellation: error <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5pub use self::kinds::*;
6
7pub(crate) mod kinds;
8
9pub type Result<T = ()> = core::result::Result<T, Error>;
10
11use core::fmt::{self, Debug, Display};
12
13#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
14#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize,))]
15pub struct Error<K = String> {
16    kind: ErrorKind<K>,
17    message: String,
18}
19
20impl<K> Error<K> {
21    pub fn new(kind: ErrorKind<K>, msg: impl ToString) -> Self {
22        Self {
23            kind,
24            message: msg.to_string(),
25        }
26    }
27    /// Get an owned reference to the error kind
28    pub fn kind(&self) -> &ErrorKind<K> {
29        &self.kind
30    }
31    /// Get an owned reference to the error message
32    pub fn message(&self) -> &str {
33        &self.message
34    }
35    /// Set the error message
36    pub fn set_message(&mut self, msg: impl ToString) {
37        self.message = msg.to_string();
38    }
39    /// Consume the error and return the message
40    pub fn into_message(self) -> String {
41        self.message
42    }
43    /// A functional method for setting the error kind
44    pub fn with_kind(mut self, kind: ErrorKind<K>) -> Self {
45        self.kind = kind;
46        self
47    }
48    /// A functional method for setting the error message
49    pub fn with_message(mut self, msg: impl ToString) -> Self {
50        self.message = msg.to_string();
51        self
52    }
53}
54
55impl<K> Display for Error<K>
56where
57    K: ToString,
58{
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        write!(f, "{}: {}", self.kind, self.message)
61    }
62}
63
64impl<K> std::error::Error for Error<K> where K: Debug + Display {}
65
66impl<K> From<ErrorKind<K>> for Error<K> {
67    fn from(kind: ErrorKind<K>) -> Self {
68        Self::new(kind, "")
69    }
70}
71
72impl<K, T> From<std::sync::TryLockError<T>> for Error<K> {
73    fn from(err: std::sync::TryLockError<T>) -> Self {
74        Self::new(ErrorKind::Sync(SyncError::TryLock), err.to_string())
75    }
76}
77
78macro_rules! err_from {
79    ($kind:expr, $t:ty) => {
80        impl<E> From<$t> for Error<E> {
81            fn from(err: $t) -> Self {
82                Self::new($kind, err.to_string())
83            }
84        }
85    };
86    ($kind:expr => ($($t:ty),*)) => {
87        $(err_from!($kind, $t);)*
88    };
89}
90
91err_from!(ErrorKind::External(ExternalError::Unknown) => (&str, String, Box<dyn std::error::Error>));