|
5 | 5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
|
6 | 6 | // option. This file may not be copied, modified, or distributed
|
7 | 7 | // except according to those terms.
|
8 |
| -use core::convert::From; |
9 | 8 | use core::fmt;
|
10 | 9 | use core::num::NonZeroU32;
|
11 | 10 |
|
12 |
| -// A randomly-chosen 24-bit prefix for our codes |
13 |
| -pub(crate) const CODE_PREFIX: u32 = 0x57f4c500; |
14 |
| -const CODE_UNKNOWN: u32 = CODE_PREFIX | 0x00; |
15 |
| -const CODE_UNAVAILABLE: u32 = CODE_PREFIX | 0x01; |
16 |
| - |
17 |
| -/// The error type. |
18 |
| -/// |
19 |
| -/// This type is small and no-std compatible. |
| 11 | +/// A small and `no_std` compatible error type. It can indicate failure from |
| 12 | +/// either the underlying OS or a custom error reason. |
| 13 | +/// |
| 14 | +/// The [`Error::raw_os_error()`] will indicate if the error is from the OS, and |
| 15 | +/// if so, which error code the OS gave the application. If such an error is |
| 16 | +/// encountered, please consult with your system documentation. |
20 | 17 | #[derive(Copy, Clone, Eq, PartialEq)]
|
21 |
| -pub struct Error(pub(crate) NonZeroU32); |
| 18 | +pub struct Error(NonZeroU32); |
22 | 19 |
|
| 20 | +// This NonZeroU32 has enough room to store 3 types of values: |
| 21 | +// - OS Errors: in range [1, 1 << 31) (i.e. positive i32 values) |
| 22 | +// - Custom u16 Errors: in range [1 << 31, 1 << 31 + 1 << 16) |
| 23 | +// - Unknown Errors: currently just (1 << 32) - 1 |
| 24 | +// TODO simplify impls with try_from when version >= 1.34 |
23 | 25 | impl Error {
|
24 | 26 | /// An unknown error.
|
25 |
| - pub const UNKNOWN: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNKNOWN) }); |
| 27 | + pub(crate) const UNKNOWN: Error = Self(unsafe { NonZeroU32::new_unchecked(u32::max_value()) }); |
| 28 | + const CUSTOM_START: u32 = 1 << 31; |
26 | 29 |
|
27 |
| - /// No generator is available. |
28 |
| - pub const UNAVAILABLE: Error = Error(unsafe { NonZeroU32::new_unchecked(CODE_UNAVAILABLE) }); |
| 30 | + pub(crate) fn from_os_error(errno: i32) -> Self { |
| 31 | + if errno > 0 { |
| 32 | + Self(NonZeroU32::new(errno as u32).unwrap()) |
| 33 | + } else { |
| 34 | + Self::UNKNOWN |
| 35 | + } |
| 36 | + } |
29 | 37 |
|
30 |
| - /// Extract the error code. |
31 |
| - /// |
32 |
| - /// This may equal one of the codes defined in this library or may be a |
33 |
| - /// system error code. |
34 |
| - /// |
35 |
| - /// One may attempt to format this error via the `Display` implementation. |
36 |
| - pub fn code(&self) -> NonZeroU32 { |
37 |
| - self.0 |
| 38 | + pub(crate) fn from_custom_error(custom: u16) -> Self { |
| 39 | + Self(NonZeroU32::new(custom as u32 + Self::CUSTOM_START).unwrap()) |
38 | 40 | }
|
39 | 41 |
|
40 |
| - pub(crate) fn msg(&self) -> Option<&'static str> { |
41 |
| - if let Some(msg) = crate::imp::error_msg_inner(self.0) { |
42 |
| - Some(msg) |
| 42 | + /// Extract the raw OS error code (if this error came from the OS) |
| 43 | + /// |
| 44 | + /// This method is identical to `std::io::Error::raw_os_error()`, except |
| 45 | + /// that it works in `no_std` contexts. If this method returns `None`, the |
| 46 | + /// error value can still be formatted via the `Diplay` implementation. |
| 47 | + pub fn raw_os_error(&self) -> Option<i32> { |
| 48 | + if self.0.get() < Self::CUSTOM_START { |
| 49 | + Some(self.0.get() as i32) |
43 | 50 | } else {
|
44 |
| - match *self { |
45 |
| - Error::UNKNOWN => Some("getrandom: unknown error"), |
46 |
| - Error::UNAVAILABLE => Some("getrandom: unavailable"), |
47 |
| - _ => None, |
48 |
| - } |
| 51 | + None |
49 | 52 | }
|
50 | 53 | }
|
51 |
| -} |
52 | 54 |
|
53 |
| -impl fmt::Debug for Error { |
54 |
| - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
55 |
| - match self.msg() { |
56 |
| - Some(msg) => write!(f, "Error(\"{}\")", msg), |
57 |
| - None => write!(f, "Error(0x{:08X})", self.0), |
| 55 | + pub fn custom_code(&self) -> Option<u16> { |
| 56 | + let custom = self.0.get().checked_sub(Self::CUSTOM_START)?; |
| 57 | + if custom <= u16::max_value() as u32 { |
| 58 | + Some(custom as u16) |
| 59 | + } else { |
| 60 | + None |
58 | 61 | }
|
59 | 62 | }
|
60 | 63 | }
|
61 | 64 |
|
62 |
| -impl fmt::Display for Error { |
63 |
| - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
64 |
| - match self.msg() { |
65 |
| - Some(msg) => write!(f, "{}", msg), |
66 |
| - None => write!(f, "getrandom: unknown code 0x{:08X}", self.0), |
67 |
| - } |
| 65 | +#[cfg(any(unix, target_os = "redox"))] |
| 66 | +fn os_err_desc(errno: i32, buf: &mut [u8]) -> Option<&str> { |
| 67 | + let buf_ptr = buf.as_mut_ptr() as *mut libc::c_char; |
| 68 | + if unsafe { libc::strerror_r(errno, buf_ptr, buf.len()) } != 0 { |
| 69 | + return None; |
68 | 70 | }
|
| 71 | + |
| 72 | + // Take up to trailing null byte |
| 73 | + let idx = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); |
| 74 | + core::str::from_utf8(&buf[..idx]).ok() |
| 75 | +} |
| 76 | + |
| 77 | +#[cfg(not(any(unix, target_os = "redox")))] |
| 78 | +fn os_err_desc(_errno: i32, _buf: &mut [u8]) -> Option<&str> { |
| 79 | + None |
69 | 80 | }
|
70 | 81 |
|
71 |
| -impl From<NonZeroU32> for Error { |
72 |
| - fn from(code: NonZeroU32) -> Self { |
73 |
| - Error(code) |
| 82 | +impl fmt::Debug for Error { |
| 83 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 84 | + let mut dbg = f.debug_struct("Error"); |
| 85 | + if let Some(errno) = self.raw_os_error() { |
| 86 | + dbg.field("os_error", &errno); |
| 87 | + let mut buf = [0u8; 128]; |
| 88 | + if let Some(desc) = os_err_desc(errno, &mut buf) { |
| 89 | + dbg.field("description", &desc); |
| 90 | + } |
| 91 | + } else if let Some(custom) = self.custom_code() { |
| 92 | + dbg.field("custom_error", &custom); |
| 93 | + if let Some(desc) = crate::imp::custom_description(custom) { |
| 94 | + dbg.field("description", &desc); |
| 95 | + } |
| 96 | + } else { |
| 97 | + dbg.field("unknown_error", &self.0); |
| 98 | + } |
| 99 | + dbg.finish() |
74 | 100 | }
|
75 | 101 | }
|
76 | 102 |
|
77 |
| -impl From<&Error> for Error { |
78 |
| - fn from(error: &Error) -> Self { |
79 |
| - *error |
| 103 | +impl fmt::Display for Error { |
| 104 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 105 | + if let Some(errno) = self.raw_os_error() { |
| 106 | + let mut buf = [0u8; 128]; |
| 107 | + if let Some(desc) = os_err_desc(errno, &mut buf) { |
| 108 | + f.write_str(desc) |
| 109 | + } else { |
| 110 | + write!(f, "OS Error: {}", errno) |
| 111 | + } |
| 112 | + } else if let Some(custom) = self.custom_code() { |
| 113 | + if let Some(desc) = crate::imp::custom_description(custom) { |
| 114 | + f.write_str(desc) |
| 115 | + } else { |
| 116 | + write!(f, "Custom Error: {}", custom) |
| 117 | + } |
| 118 | + } else { |
| 119 | + write!(f, "Unknown Error: {}", self.0) |
| 120 | + } |
80 | 121 | }
|
81 | 122 | }
|
82 | 123 |
|
|
0 commit comments