Skip to content

Commit 35b5c7d

Browse files
wutchzoneintel-lab-lkp
authored andcommitted
rust: error: modify from_errno to use try_from_errno
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: Rust-for-Linux#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>
1 parent b7ed2b6 commit 35b5c7d

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

rust/kernel/error.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -100,20 +100,17 @@ impl Error {
100100
///
101101
/// It is a bug to pass an out-of-range `errno`. `EINVAL` would
102102
/// be returned in such a case.
103-
pub fn from_errno(errno: crate::ffi::c_int) -> Error {
104-
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
103+
pub fn from_errno(errno: core::ffi::c_int) -> Error {
104+
if let Some(error) = Self::try_from_errno(errno) {
105+
error
106+
} else {
105107
// TODO: Make it a `WARN_ONCE` once available.
106108
crate::pr_warn!(
107109
"attempted to create `Error` with out of range `errno`: {}",
108110
errno
109111
);
110-
return code::EINVAL;
112+
code::EINVAL
111113
}
112-
113-
// INVARIANT: The check above ensures the type invariant
114-
// will hold.
115-
// SAFETY: `errno` is checked above to be in a valid range.
116-
unsafe { Error::from_errno_unchecked(errno) }
117114
}
118115

119116
/// Creates an [`Error`] from a kernel error code.

0 commit comments

Comments
 (0)