From: Boqun Feng Date: Fri, 7 Mar 2025 23:26:58 +0000 (-0800) Subject: rust: sync: lock: Add an example for Guard:: Lock_ref() X-Git-Tag: v6.15-rc1~220^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c2849afafd08a1c3ad881129de48ebe1642f7675;p=thirdparty%2Fkernel%2Flinux.git rust: sync: lock: Add an example for Guard:: Lock_ref() To provide examples on usage of `Guard::lock_ref()` along with the unit test, an "assert a lock is held by a guard" example is added. (Also apply feedback from Benno.) Signed-off-by: Boqun Feng Signed-off-by: Ingo Molnar Reviewed-by: Benno Lossin Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20250223072114.3715-1-boqun.feng@gmail.com Link: https://lore.kernel.org/r/20250307232717.1759087-9-boqun.feng@gmail.com --- diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs index 8e7e6d5f61e4c..f53e87d04cd26 100644 --- a/rust/kernel/sync/lock.rs +++ b/rust/kernel/sync/lock.rs @@ -201,6 +201,30 @@ unsafe impl Sync for Guard<'_, T, B> {} impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> { /// Returns the lock that this guard originates from. + /// + /// # Examples + /// + /// The following example shows how to use [`Guard::lock_ref()`] to assert the corresponding + /// lock is held. + /// + /// ``` + /// # use kernel::{new_spinlock, stack_pin_init, sync::lock::{Backend, Guard, Lock}}; + /// + /// fn assert_held(guard: &Guard<'_, T, B>, lock: &Lock) { + /// // Address-equal means the same lock. + /// assert!(core::ptr::eq(guard.lock_ref(), lock)); + /// } + /// + /// // Creates a new lock on the stack. + /// stack_pin_init!{ + /// let l = new_spinlock!(42) + /// } + /// + /// let g = l.lock(); + /// + /// // `g` originates from `l`. + /// assert_held(&g, &l); + /// ``` pub fn lock_ref(&self) -> &'a Lock { self.lock }