Skip to content

Commit

Permalink
rust: error: Add to_result() helper
Browse files Browse the repository at this point in the history
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 <[email protected]>
Reviewed-by: Andreas Hindborg <[email protected]>
Reviewed-by: Gary Guo <[email protected]>
Reviewed-by: Martin Rodriguez Reboredo <[email protected]>
Signed-off-by: Asahi Lina <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
[ Add a removal of `#[allow(dead_code)]`. ]
Signed-off-by: Miguel Ojeda <[email protected]>
  • Loading branch information
wedsonaf authored and ojeda committed Apr 10, 2023
1 parent 5a172a0 commit 3a36ce4
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(())
}
}

0 comments on commit 3a36ce4

Please sign in to comment.