Skip to main content

starnix_sync/
lock_traits.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use core::ops::{Deref, DerefMut};
6
7/// A trait for types that represent a lock level in the lock dependency tracker.
8pub trait LockLevel {
9    /// The unique identifier for this lock level.
10    const LOCK_ID: usize;
11    /// The name of the lock level.
12    fn name() -> &'static str;
13}
14
15/// Describes how to apply a lock type to the implementing type.
16///
17/// An implementation of `LockFor<L>` for some `Self` means that `Self` can
18/// be used to unlock some state that is under the lock indicated by `L`.
19pub trait LockFor<L> {
20    /// The data produced by locking the state indicated by `L` in `Self`.
21    type Data;
22
23    /// A guard providing read and write access to the data.
24    type Guard<'l>: DerefMut<Target = Self::Data>
25    where
26        Self: 'l;
27
28    /// Locks `Self` for lock `L`.
29    fn lock(&self) -> Self::Guard<'_>;
30}
31
32/// Describes how to acquire reader and writer locks to the implementing type.
33///
34/// An implementation of `RwLockFor<L>` for some `Self` means that `Self` can
35/// be used to unlock some state that is under the lock indicated by `L`.
36pub trait RwLockFor<L> {
37    /// The data produced by locking the state indicated by `L` in `Self`.
38    type Data;
39
40    /// A guard providing read access to the data.
41    type ReadGuard<'l>: Deref<Target = Self::Data>
42    where
43        Self: 'l;
44
45    /// A guard providing write access to the data.
46    type WriteGuard<'l>: DerefMut<Target = Self::Data>
47    where
48        Self: 'l;
49
50    /// Acquires a read lock on the data in `Self` indicated by `L`.
51    fn read_lock(&self) -> Self::ReadGuard<'_>;
52
53    /// Acquires a write lock on the data in `Self` indicated by `L`.
54    fn write_lock(&self) -> Self::WriteGuard<'_>;
55}
56
57#[cfg(test)]
58mod example {
59    //! Example implementations of the traits in this crate.
60
61    use fuchsia_sync::{Mutex, MutexGuard};
62
63    use super::*;
64
65    enum LockLevel {}
66
67    impl<T> LockFor<LockLevel> for Mutex<T> {
68        type Data = T;
69        type Guard<'l>
70            = MutexGuard<'l, T>
71        where
72            Self: 'l;
73
74        fn lock(&self) -> Self::Guard<'_> {
75            self.lock()
76        }
77    }
78}