diff options
author | Wedson Almeida Filho <wedsonaf@gmail.com> | 2023-04-03 11:48:13 +0200 |
---|---|---|
committer | Miguel Ojeda <ojeda@kernel.org> | 2023-04-12 18:41:04 +0200 |
commit | 086fbfa3b328901fa8b369093ba468864e20544e (patch) | |
tree | d0dffc6df92019dd32b6ffb5eca65306241a32e1 /rust | |
parent | rust: error: Add Error::from_errno{_unchecked}() (diff) | |
download | linux-086fbfa3b328901fa8b369093ba468864e20544e.tar.xz linux-086fbfa3b328901fa8b369093ba468864e20544e.zip |
rust: error: Add to_result() helper
Add a to_result() helper to convert kernel C return values to a Rust
Result, mapping >=0 values to Ok(()) and negative values to Err(...),
with Error::from_errno() ensuring that the errno is within range.
Lina: Imported from rust-for-linux/rust, originally developed by Wedson
as part of the AMBA device driver support.
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Signed-off-by: Asahi Lina <lina@asahilina.net>
Link: https://lore.kernel.org/r/20230224-rust-error-v3-4-03779bddc02b@asahilina.net
[ Add a removal of `#[allow(dead_code)]`. ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Diffstat (limited to 'rust')
-rw-r--r-- | rust/kernel/error.rs | 11 |
1 files changed, 10 insertions, 1 deletions
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 0223d48ab43d..7e25871063df 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -76,7 +76,6 @@ impl Error { /// /// It is a bug to pass an out-of-range `errno`. `EINVAL` would /// be returned in such a case. - #[allow(dead_code)] pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error { if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 { // TODO: Make it a `WARN_ONCE` once available. @@ -180,3 +179,13 @@ impl From<core::convert::Infallible> for Error { /// it should still be modeled as returning a `Result` rather than /// just an [`Error`]. pub type Result<T = ()> = core::result::Result<T, Error>; + +/// Converts an integer as returned by a C kernel function to an error if it's negative, and +/// `Ok(())` otherwise. +pub fn to_result(err: core::ffi::c_int) -> Result { + if err < 0 { + Err(Error::from_errno(err)) + } else { + Ok(()) + } +} |