-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherr.rs
114 lines (91 loc) · 2.5 KB
/
err.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
107
108
109
110
111
112
113
114
/*
Appellation: err <module>
Contrib: FL03 <[email protected]>
*/
use super::MusicalError;
pub trait ErrorKind: core::fmt::Debug + core::fmt::Display {}
impl<T> ErrorKind for T where T: core::fmt::Debug + core::fmt::Display {}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[repr(transparent)]
pub struct UnknownError;
impl core::fmt::Display for UnknownError {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "Unknown error")
}
}
unsafe impl Send for UnknownError {}
unsafe impl Sync for UnknownError {}
#[cfg(feature = "std")]
impl std::error::Error for UnknownError {}
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Error<K = MusicalError> {
pub kind: K,
pub msg: String,
}
impl Error<UnknownError> {
pub fn unknown(msg: impl ToString) -> Self {
Self::new(UnknownError, msg)
}
}
impl<K> Error<K>
where
K: ErrorKind,
{
pub fn new(kind: K, msg: impl ToString) -> Self {
Self {
kind,
msg: msg.to_string(),
}
}
pub fn kind(&self) -> &K {
&self.kind
}
pub fn msg(&self) -> &str {
&self.msg
}
}
impl Error<MusicalError> {
pub fn invalid_interval(msg: impl ToString) -> Self {
Self::new(MusicalError::InvalidInterval, msg)
}
pub fn invalid_pitch(msg: impl ToString) -> Self {
Self::new(MusicalError::InvalidPitch, msg)
}
}
impl<K> core::fmt::Display for Error<K>
where
K: ErrorKind,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{}: {}", self.kind, self.msg)
}
}
impl From<Box<dyn std::error::Error>> for Error<UnknownError> {
fn from(err: Box<dyn std::error::Error>) -> Self {
Self::unknown(err.to_string())
}
}
impl From<&str> for Error<UnknownError> {
fn from(msg: &str) -> Self {
Self::unknown(msg)
}
}
impl From<String> for Error<UnknownError> {
fn from(msg: String) -> Self {
Self::unknown(msg)
}
}
impl<K> From<K> for Error<K>
where
K: ErrorKind,
{
fn from(kind: K) -> Self {
Self::new(kind, "")
}
}
unsafe impl<K> Send for Error<K> where K: ErrorKind {}
unsafe impl<K> Sync for Error<K> where K: ErrorKind {}
#[cfg(feature = "std")]
impl<K> std::error::Error for Error<K> where K: ErrorKind {}