| 1 | //! The `Errno` type, which is a minimal wrapper around an error code. |
| 2 | //! |
| 3 | //! We define the error constants as individual `const`s instead of an enum |
| 4 | //! because we may not know about all of the host's error values and we don't |
| 5 | //! want unrecognized values to create undefined behavior. |
| 6 | |
| 7 | use crate::backend; |
| 8 | #[cfg (all(not(feature = "std" ), error_in_core))] |
| 9 | use core::error; |
| 10 | use core::{fmt, result}; |
| 11 | #[cfg (feature = "std" )] |
| 12 | use std::error; |
| 13 | |
| 14 | /// A specialized [`Result`] type for `rustix` APIs. |
| 15 | pub type Result<T> = result::Result<T, Errno>; |
| 16 | |
| 17 | pub use backend::io::errno::Errno; |
| 18 | |
| 19 | impl Errno { |
| 20 | /// Shorthand for `std::io::Error::from(self).kind()`. |
| 21 | #[cfg (feature = "std" )] |
| 22 | #[inline ] |
| 23 | pub fn kind(self) -> std::io::ErrorKind { |
| 24 | std::io::Error::from(self).kind() |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl fmt::Display for Errno { |
| 29 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 30 | #[cfg (feature = "std" )] |
| 31 | { |
| 32 | std::io::Error::from(*self).fmt(f) |
| 33 | } |
| 34 | #[cfg (not(feature = "std" ))] |
| 35 | { |
| 36 | write!(f, "os error {}" , self.raw_os_error()) |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl fmt::Debug for Errno { |
| 42 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 43 | #[cfg (feature = "std" )] |
| 44 | { |
| 45 | std::io::Error::from(*self).fmt(f) |
| 46 | } |
| 47 | #[cfg (not(feature = "std" ))] |
| 48 | { |
| 49 | write!(f, "os error {}" , self.raw_os_error()) |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[cfg (any(feature = "std" , error_in_core))] |
| 55 | impl error::Error for Errno {} |
| 56 | |
| 57 | #[cfg (feature = "std" )] |
| 58 | impl From<Errno> for std::io::Error { |
| 59 | #[inline ] |
| 60 | fn from(err: Errno) -> Self { |
| 61 | Self::from_raw_os_error(code:err.raw_os_error() as _) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Call `f` until it either succeeds or fails other than [`Errno::INTR`]. |
| 66 | #[inline ] |
| 67 | pub fn retry_on_intr<T, F: FnMut() -> Result<T>>(mut f: F) -> Result<T> { |
| 68 | loop { |
| 69 | match f() { |
| 70 | Err(Errno::INTR) => (), |
| 71 | result: Result => return result, |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |