[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <D8F7D2RPRVAO.2EF39MZXM6FPR@proton.me>
Date: Thu, 13 Mar 2025 14:19:53 +0000
From: Benno Lossin <benno.lossin@...ton.me>
To: Alexandre Courbot <acourbot@...dia.com>, Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>, Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>, Danilo Krummrich <dakr@...nel.org>, Björn Roy Baron <bjorn3_gh@...tonmail.com>, Andreas Hindborg <a.hindborg@...nel.org>, Alice Ryhl <aliceryhl@...gle.com>, Trevor Gross <tmgross@...ch.edu>
Cc: rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org
Subject: Re: [PATCH] rust/revocable: add try_with() convenience method
On Thu Mar 13, 2025 at 1:40 PM CET, Alexandre Courbot wrote:
> diff --git a/rust/kernel/revocable.rs b/rust/kernel/revocable.rs
> index 1e5a9d25c21b279b01f90b02997492aa4880d84f..0157b20373b5b2892cb618b46958bfe095e428b6 100644
> --- a/rust/kernel/revocable.rs
> +++ b/rust/kernel/revocable.rs
> @@ -105,6 +105,28 @@ pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
> }
> }
>
> + /// Tries to access the wrapped object and run the closure `f` on it with the guard held.
> + ///
> + /// This is a convenience method to run short non-sleepable code blocks while ensuring the
> + /// guard is dropped afterwards. [`Self::try_access`] carries the risk that the caller
> + /// will forget to explicitly drop that returned guard before calling sleepable code ; this
Space after `;`?
> + /// method adds an extra safety to make sure it doesn't happen.
To be clear, you still can call a sleeping function form within the
closure and have the same issue, but I agree that that should not happen
accidentally (or at least not as often).
> + ///
> + /// Returns `Err(ENXIO)` if the wrapped object has been revoked, or the result of `f` after it
> + /// has been run.
> + pub fn try_with<R, F: Fn(&T) -> Result<R>>(&self, f: F) -> Result<R> {
This (and below) can be a `FnOnce(&T) -> Result<R>`.
Would it make sense to not use `Result` here and continue with `Option`?
---
Cheers,
Benno
> + self.try_access().ok_or(ENXIO).and_then(|t| f(&*t))
> + }
> +
> + /// Tries to access the wrapped object and run the closure `f` on it with the guard held.
> + ///
> + /// This is the same as [`Self::try_with`], with the exception that `f` is expected to
> + /// always succeed and thus does not need to return a `Result`. Thus the only error case is if
> + /// the wrapped object has been revoked.
> + pub fn try_with_ok<R, F: Fn(&T) -> R>(&self, f: F) -> Result<R> {
> + self.try_with(|t| Ok(f(t)))
> + }
> +
> /// Tries to access the revocable wrapped object.
> ///
> /// Returns `None` if the object has been revoked and is therefore no longer accessible.
>
> ---
> base-commit: 4d872d51bc9d7b899c1f61534e3dbde72613f627
> change-id: 20250313-try_with-cc9f91dd3b60
>
> Best regards,
Powered by blists - more mailing lists