1use core::fmt;
12use core::num::NonZeroU32;
13
14#[cfg(feature = "std")] use std::boxed::Box;
15
16pub struct Error {
22    #[cfg(feature = "std")]
23    inner: Box<dyn std::error::Error + Send + Sync + 'static>,
24    #[cfg(not(feature = "std"))]
25    code: NonZeroU32,
26}
27
28impl Error {
29    pub const CUSTOM_START: u32 = (1 << 31) + (1 << 30);
37    pub const INTERNAL_START: u32 = 1 << 31;
43
44    #[cfg(feature = "std")]
50    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
51    #[inline]
52    pub fn new<E>(err: E) -> Self
53    where
54        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
55    {
56        Error { inner: err.into() }
57    }
58
59    #[cfg(feature = "std")]
64    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
65    #[inline]
66    pub fn inner(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
67        &*self.inner
68    }
69
70    #[cfg(feature = "std")]
75    #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
76    #[inline]
77    pub fn take_inner(self) -> Box<dyn std::error::Error + Send + Sync + 'static> {
78        self.inner
79    }
80
81    #[inline]
87    pub fn raw_os_error(&self) -> Option<i32> {
88        #[cfg(feature = "std")]
89        {
90            if let Some(e) = self.inner.downcast_ref::<std::io::Error>() {
91                return e.raw_os_error();
92            }
93        }
94        match self.code() {
95            Some(code) if u32::from(code) < Self::INTERNAL_START => Some(u32::from(code) as i32),
96            _ => None,
97        }
98    }
99
100    #[inline]
106    pub fn code(&self) -> Option<NonZeroU32> {
107        #[cfg(feature = "std")]
108        {
109            self.inner.downcast_ref::<ErrorCode>().map(|c| c.0)
110        }
111        #[cfg(not(feature = "std"))]
112        {
113            Some(self.code)
114        }
115    }
116}
117
118impl fmt::Debug for Error {
119    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120        #[cfg(feature = "std")]
121        {
122            write!(f, "Error {{ inner: {:?} }}", self.inner)
123        }
124        #[cfg(all(feature = "getrandom", not(feature = "std")))]
125        {
126            getrandom::Error::from(self.code).fmt(f)
127        }
128        #[cfg(not(feature = "getrandom"))]
129        {
130            write!(f, "Error {{ code: {} }}", self.code)
131        }
132    }
133}
134
135impl fmt::Display for Error {
136    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137        #[cfg(feature = "std")]
138        {
139            write!(f, "{}", self.inner)
140        }
141        #[cfg(all(feature = "getrandom", not(feature = "std")))]
142        {
143            getrandom::Error::from(self.code).fmt(f)
144        }
145        #[cfg(not(feature = "getrandom"))]
146        {
147            write!(f, "error code {}", self.code)
148        }
149    }
150}
151
152impl From<NonZeroU32> for Error {
153    #[inline]
154    fn from(code: NonZeroU32) -> Self {
155        #[cfg(feature = "std")]
156        {
157            Error {
158                inner: Box::new(ErrorCode(code)),
159            }
160        }
161        #[cfg(not(feature = "std"))]
162        {
163            Error { code }
164        }
165    }
166}
167
168#[cfg(feature = "getrandom")]
169impl From<getrandom::Error> for Error {
170    #[inline]
171    fn from(error: getrandom::Error) -> Self {
172        #[cfg(feature = "std")]
173        {
174            Error {
175                inner: Box::new(error),
176            }
177        }
178        #[cfg(not(feature = "std"))]
179        {
180            Error { code: error.code() }
181        }
182    }
183}
184
185#[cfg(feature = "std")]
186impl std::error::Error for Error {
187    #[inline]
188    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
189        self.inner.source()
190    }
191}
192
193#[cfg(feature = "std")]
194impl From<Error> for std::io::Error {
195    #[inline]
196    fn from(error: Error) -> Self {
197        if let Some(code) = error.raw_os_error() {
198            std::io::Error::from_raw_os_error(code)
199        } else {
200            std::io::Error::new(std::io::ErrorKind::Other, error)
201        }
202    }
203}
204
205#[cfg(feature = "std")]
206#[derive(Debug, Copy, Clone)]
207struct ErrorCode(NonZeroU32);
208
209#[cfg(feature = "std")]
210impl fmt::Display for ErrorCode {
211    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212        write!(f, "error code {}", self.0)
213    }
214}
215
216#[cfg(feature = "std")]
217impl std::error::Error for ErrorCode {}
218
219#[cfg(test)]
220mod test {
221    #[cfg(feature = "getrandom")]
222    #[test]
223    fn test_error_codes() {
224        assert_eq!(super::Error::CUSTOM_START, getrandom::Error::CUSTOM_START);
226        assert_eq!(super::Error::INTERNAL_START, getrandom::Error::INTERNAL_START);
227    }
228}