Skip to contentSkip to conversation

rust: error: make `from_errno` use `try_from_errno`

PATCH Superseded Daniel Sedlak 2 participants 2 messages Nov 4, 2024 Rust

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: error: make `from_errno` use `try_from_errno`

Thanks to this simplification we are able to remove another redundant unsafe.

---
 rust/kernel/error.rs | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
rust/kernel/error.rs +4 -7
index 7cd3bbab52f2..2339b1fc7353 100644
@@ -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: core::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.
Signature · 1 line
2.47.0
#1 lore raw

Hi Daniel,

Quoted 3 lines · Daniel Sedlak

Thanks to this simplification we are able to remove another redundant unsafe.

Please describe a bit the change, i.e. the "what" (this describes the "why", which is needed to, so that is good).

Quoted 1 line

Please add the Suggested-by and the Link tags as mentioned in the issue.

rust/kernel/error.rs impl Error { · line 106

Quoted 4 lines
rust/kernel/error.rs +3 -1
-        if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
+        if let Some(error) = Self::try_from_errno(errno) {
+            error
+        } else {

Could we use let else here to simplify even further?

Please also see the discussion about who will finally send the patch and whether to have you both as co-authors at:

https://lore.kernel.org/rust-for-linux/CANiq72=fcjmDqqYT+wLKNr1qQRgcomaBcaedUxzLXmiLvU5hrQ@mail.gmail.com/

Thanks!

Cheers,
Miguel