[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <bc99d578-0905-5cf6-db0d-1ebad2b3d9b2@gmail.com>
Date: Wed, 29 Mar 2023 11:55:01 -0300
From: Martin Rodriguez Reboredo <yakoyoku@...il.com>
To: Asahi Lina <lina@...hilina.net>, Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>,
Wedson Almeida Filho <wedsonaf@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Sven Van Asbroeck <thesven73@...il.com>
Cc: Fox Chen <foxhlchen@...il.com>,
Andreas Hindborg <a.hindborg@...sung.com>,
rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org,
asahi@...ts.linux.dev
Subject: Re: [PATCH v2 6/6] rust: error: Add from_result() helper
On 3/29/23 09:04, Asahi Lina wrote:
> [...]
>
> +
> +/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
> +/// a C integer result.
> +///
> +/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
> +/// from inside `extern "C"` functions that need to return an integer error result.
> +///
> +/// `T` should be convertible from an `i16` via `From<i16>`.
> +///
> +/// # Examples
> +///
> +/// ```ignore
> +/// # use kernel::from_result;
> +/// # use kernel::bindings;
> +/// unsafe extern "C" fn probe_callback(
> +/// pdev: *mut bindings::platform_device,
> +/// ) -> core::ffi::c_int {
> +/// from_result(|| {
> +/// let ptr = devm_alloc(pdev)?;
> +/// bindings::platform_set_drvdata(pdev, ptr);
> +/// Ok(0)
> +/// })
> +/// }
> +/// ```
> +// TODO: Remove `dead_code` marker once an in-kernel client is available.
> +#[allow(dead_code)]
> +pub(crate) fn from_result<T, F>(f: F) -> T
> +where
> + T: From<i16>,
> + F: FnOnce() -> Result<T>,
> +{
> + match f() {
> + Ok(v) => v,
> + // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
> + // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
> + // therefore a negative `errno` always fits in an `i16` and will not overflow.
> + Err(e) => T::from(e.to_errno() as i16),
> + }
> +}
>
Reviewed-by: Martin Rodriguez Reboredo
Powered by blists - more mailing lists