Skip to content

Commit 107d2b0

Browse files
wedsonafojeda
authored andcommitted
rust: error: Add from_result() helper
Add a helper function to easily return C result codes from a Rust function that calls functions which return a Result<T>. Lina: Imported from rust-for-linux/rust, originally developed by Wedson as part of file_operations.rs. Added the allow() flags since there is no user in the kernel crate yet and fixed a typo in a comment. Replaced the macro with a function taking a closure, per discussion on the ML. Co-developed-by: Fox Chen <[email protected]> Signed-off-by: Fox Chen <[email protected]> Co-developed-by: Miguel Ojeda <[email protected]> Signed-off-by: Miguel Ojeda <[email protected]> Signed-off-by: Wedson Almeida Filho <[email protected]> Reviewed-by: Martin Rodriguez Reboredo <[email protected]> Signed-off-by: Asahi Lina <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 1e6af0f commit 107d2b0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

rust/kernel/error.rs

+39
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,42 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
237237
}
238238
Ok(ptr)
239239
}
240+
241+
/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
242+
/// a C integer result.
243+
///
244+
/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
245+
/// from inside `extern "C"` functions that need to return an integer error result.
246+
///
247+
/// `T` should be convertible from an `i16` via `From<i16>`.
248+
///
249+
/// # Examples
250+
///
251+
/// ```ignore
252+
/// # use kernel::from_result;
253+
/// # use kernel::bindings;
254+
/// unsafe extern "C" fn probe_callback(
255+
/// pdev: *mut bindings::platform_device,
256+
/// ) -> core::ffi::c_int {
257+
/// from_result(|| {
258+
/// let ptr = devm_alloc(pdev)?;
259+
/// bindings::platform_set_drvdata(pdev, ptr);
260+
/// Ok(0)
261+
/// })
262+
/// }
263+
/// ```
264+
// TODO: Remove `dead_code` marker once an in-kernel client is available.
265+
#[allow(dead_code)]
266+
pub(crate) fn from_result<T, F>(f: F) -> T
267+
where
268+
T: From<i16>,
269+
F: FnOnce() -> Result<T>,
270+
{
271+
match f() {
272+
Ok(v) => v,
273+
// NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
274+
// `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
275+
// therefore a negative `errno` always fits in an `i16` and will not overflow.
276+
Err(e) => T::from(e.to_errno() as i16),
277+
}
278+
}

0 commit comments

Comments
 (0)