|
6 | 6 | // option. This file may not be copied, modified, or distributed
|
7 | 7 | // except according to those terms.
|
8 | 8 |
|
| 9 | +use core::num::NonZeroU32; |
| 10 | +use core::convert::From; |
| 11 | +use core::fmt; |
| 12 | +#[cfg(not(target_env = "sgx"))] |
| 13 | +use std::{io, error}; |
| 14 | + |
| 15 | +pub const UNKNOWN_ERROR: Error = Error(unsafe { |
| 16 | + NonZeroU32::new_unchecked(0x756e6b6e) // "unkn" |
| 17 | +}); |
| 18 | + |
| 19 | +pub const UNAVAILABLE_ERROR: Error = Error(unsafe { |
| 20 | + NonZeroU32::new_unchecked(0x4e416e61) // "NAna" |
| 21 | +}); |
| 22 | + |
9 | 23 | #[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
10 |
| -pub enum Error { |
11 |
| - /// Call was interrupted. |
12 |
| - /// |
13 |
| - /// Typically it can be retried. |
14 |
| - Interrupted, |
15 |
| - /// RNG source is unavailable on a given system. |
16 |
| - Unavailable, |
17 |
| - /// Unknown error. |
18 |
| - Unknown, |
19 |
| - #[doc(hidden)] |
20 |
| - __Nonexhaustive, |
| 24 | +pub struct Error(NonZeroU32); |
| 25 | + |
| 26 | +impl Error { |
| 27 | + pub fn code(&self) -> NonZeroU32 { |
| 28 | + self.0 |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl fmt::Display for Error { |
| 33 | + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 34 | + match *self { |
| 35 | + UNKNOWN_ERROR => write!(f, "Getrandom Error: unknown"), |
| 36 | + UNAVAILABLE_ERROR => write!(f, "Getrandom Error: unavailable"), |
| 37 | + code => write!(f, "Getrandom Error: {}", code.0.get()), |
| 38 | + } |
| 39 | + } |
21 | 40 | }
|
| 41 | + |
| 42 | +#[cfg(not(target_env = "sgx"))] |
| 43 | +impl From<io::Error> for Error { |
| 44 | + fn from(err: io::Error) -> Self { |
| 45 | + err.raw_os_error() |
| 46 | + .map(|code| Error(unsafe { |
| 47 | + // all supported targets use 0 as success code |
| 48 | + NonZeroU32::new_unchecked(code as u32) |
| 49 | + })) |
| 50 | + // in practice this should never happen |
| 51 | + .unwrap_or(UNKNOWN_ERROR) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[cfg(not(target_env = "sgx"))] |
| 56 | +impl Into<io::Error> for Error { |
| 57 | + fn into(self) -> io::Error { |
| 58 | + match self { |
| 59 | + UNKNOWN_ERROR => io::Error::new(io::ErrorKind::Other, |
| 60 | + "getrandom error: unknown"), |
| 61 | + UNAVAILABLE_ERROR => io::Error::new(io::ErrorKind::Other, |
| 62 | + "getrandom error: entropy source is unavailable"), |
| 63 | + code => io::Error::from_raw_os_error(code.0.get() as i32), |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +#[cfg(not(target_env = "sgx"))] |
| 69 | +impl error::Error for Error { } |
0 commit comments