error.rs 1.9 KB

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