Skip to content

Commit 6378447

Browse files
wedsonafojeda
authored andcommitted
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 <[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]>
1 parent 6152b77 commit 6378447

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

rust/kernel/error.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ impl Error {
7676
///
7777
/// It is a bug to pass an out-of-range `errno`. `EINVAL` would
7878
/// be returned in such a case.
79-
#[allow(dead_code)]
8079
pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
8180
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
8281
// TODO: Make it a `WARN_ONCE` once available.
@@ -180,3 +179,13 @@ impl From<core::convert::Infallible> for Error {
180179
/// it should still be modeled as returning a `Result` rather than
181180
/// just an [`Error`].
182181
pub type Result<T = ()> = core::result::Result<T, Error>;
182+
183+
/// Converts an integer as returned by a C kernel function to an error if it's negative, and
184+
/// `Ok(())` otherwise.
185+
pub fn to_result(err: core::ffi::c_int) -> Result {
186+
if err < 0 {
187+
Err(Error::from_errno(err))
188+
} else {
189+
Ok(())
190+
}
191+
}

0 commit comments

Comments
 (0)