1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Kernel errors. 4 //! 5 //! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h) 6 7 use alloc::collections::TryReserveError; 8 9 /// Contains the C-compatible error codes. 10 pub mod code { 11 /// Out of memory. 12 pub const ENOMEM: super::Error = super::Error(-(crate::bindings::ENOMEM as i32)); 13 } 14 15 /// Generic integer kernel error. 16 /// 17 /// The kernel defines a set of integer generic error codes based on C and 18 /// POSIX ones. These codes may have a more specific meaning in some contexts. 19 /// 20 /// # Invariants 21 /// 22 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`). 23 #[derive(Clone, Copy, PartialEq, Eq)] 24 pub struct Error(core::ffi::c_int); 25 26 impl Error { 27 /// Returns the kernel error code. 28 pub fn to_kernel_errno(self) -> core::ffi::c_int { 29 self.0 30 } 31 } 32 33 impl From<TryReserveError> for Error { 34 fn from(_: TryReserveError) -> Error { 35 code::ENOMEM 36 } 37 } 38 39 /// A [`Result`] with an [`Error`] error type. 40 /// 41 /// To be used as the return type for functions that may fail. 42 /// 43 /// # Error codes in C and Rust 44 /// 45 /// In C, it is common that functions indicate success or failure through 46 /// their return value; modifying or returning extra data through non-`const` 47 /// pointer parameters. In particular, in the kernel, functions that may fail 48 /// typically return an `int` that represents a generic error code. We model 49 /// those as [`Error`]. 50 /// 51 /// In Rust, it is idiomatic to model functions that may fail as returning 52 /// a [`Result`]. Since in the kernel many functions return an error code, 53 /// [`Result`] is a type alias for a [`core::result::Result`] that uses 54 /// [`Error`] as its error type. 55 /// 56 /// Note that even if a function does not return anything when it succeeds, 57 /// it should still be modeled as returning a `Result` rather than 58 /// just an [`Error`]. 59 pub type Result<T = ()> = core::result::Result<T, Error>; 60