rust: error: modify `from_errno` to use `try_from_errno`
authorDaniel Sedlak <daniel@sedlak.dev>
Sat, 7 Dec 2024 11:24:45 +0000 (12:24 +0100)
committerMiguel Ojeda <ojeda@kernel.org>
Tue, 17 Dec 2024 22:52:06 +0000 (23:52 +0100)
Modify the from_errno function to use try_from_errno to
reduce code duplication while still maintaining all existing
behavior and error handling and also reduces unsafe code.

Link: https://github.com/Rust-for-Linux/linux/issues/1125
Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Co-developed-by: Guilherme Augusto Martins da Silva <guilhermev2huehue@gmail.com>
Signed-off-by: Guilherme Augusto Martins da Silva <guilhermev2huehue@gmail.com>
Signed-off-by: Daniel Sedlak <daniel@sedlak.dev>
Reviewed-by: Fiona Behrens <me@kloenk.dev>
Link: https://lore.kernel.org/r/20241207112445.55502-1-daniel@sedlak.dev
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
rust/kernel/error.rs

index 5fece574ec023b6946d911b0bd624e67e2647527..914e8dec1abd7871fd25d637aa9fd1f21c711438 100644 (file)
@@ -101,19 +101,16 @@ impl Error {
     /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
     /// be returned in such a case.
     pub fn from_errno(errno: crate::ffi::c_int) -> Error {
-        if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
+        if let Some(error) = Self::try_from_errno(errno) {
+            error
+        } else {
             // TODO: Make it a `WARN_ONCE` once available.
             crate::pr_warn!(
                 "attempted to create `Error` with out of range `errno`: {}",
                 errno
             );
-            return code::EINVAL;
+            code::EINVAL
         }
-
-        // INVARIANT: The check above ensures the type invariant
-        // will hold.
-        // SAFETY: `errno` is checked above to be in a valid range.
-        unsafe { Error::from_errno_unchecked(errno) }
     }
 
     /// Creates an [`Error`] from a kernel error code.