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/// Describes how to apply a lock type to the implementing type.
8///
9/// An implementation of `LockFor<L>` for some `Self` means that `Self` can
10/// be used to unlock some state that is under the lock indicated by `L`.
11pub trait LockFor<L> {
12    /// The data produced by locking the state indicated by `L` in `Self`.
13    type Data;
14
15    /// A guard providing read and write access to the data.
16    type Guard<'l>: DerefMut<Target = Self::Data>
17    where
18        Self: 'l;
19
20    /// Locks `Self` for lock `L`.
21    fn lock(&self) -> Self::Guard<'_>;
22}
23
24/// Describes how to acquire reader and writer locks to the implementing type.
25///
26/// An implementation of `RwLockFor<L>` for some `Self` means that `Self` can
27/// be used to unlock some state that is under the lock indicated by `L`.
28pub trait RwLockFor<L> {
29    /// The data produced by locking the state indicated by `L` in `Self`.
30    type Data;
31
32    /// A guard providing read access to the data.
33    type ReadGuard<'l>: Deref<Target = Self::Data>
34    where
35        Self: 'l;
36
37    /// A guard providing write access to the data.
38    type WriteGuard<'l>: DerefMut<Target = Self::Data>
39    where
40        Self: 'l;
41
42    /// Acquires a read lock on the data in `Self` indicated by `L`.
43    fn read_lock(&self) -> Self::ReadGuard<'_>;
44
45    /// Acquires a write lock on the data in `Self` indicated by `L`.
46    fn write_lock(&self) -> Self::WriteGuard<'_>;
47}
48
49#[cfg(test)]
50mod example {
51    //! Example implementations of the traits in this crate.
52
53    use std::sync::{Mutex, MutexGuard};
54
55    use super::*;
56
57    enum LockLevel {}
58
59    impl<T> LockFor<LockLevel> for Mutex<T> {
60        type Data = T;
61        type Guard<'l>
62            = MutexGuard<'l, T>
63        where
64            Self: 'l;
65
66        fn lock(&self) -> Self::Guard<'_> {
67            self.lock().unwrap()
68        }
69    }
70}