Commit c2849afa authored by Boqun Feng's avatar Boqun Feng Committed by Ingo Molnar
Browse files

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: default avatarBoqun Feng <boqun.feng@gmail.com>
Signed-off-by: default avatarIngo Molnar <mingo@kernel.org>
Reviewed-by: default avatarBenno Lossin <benno.lossin@proton.me>
Reviewed-by: default avatarAlice Ryhl <aliceryhl@google.com>
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
parent 8f65291d
Loading
Loading
Loading
Loading
+24 −0
Original line number Diff line number Diff line
@@ -201,6 +201,30 @@ unsafe impl<T: Sync + ?Sized, B: Backend> 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<T, B: Backend>(guard: &Guard<'_, T, B>, lock: &Lock<T, B>) {
    ///     // 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<T, B> {
        self.lock
    }