webrtc_util/sync/
mod.rs

1use std::{ops, sync};
2
3/// A synchronous mutual exclusion primitive useful for protecting shared data.
4#[derive(Default, Debug)]
5pub struct Mutex<T>(sync::Mutex<T>);
6
7impl<T> Mutex<T> {
8    /// Creates a new mutex in an unlocked state ready for use.
9    pub fn new(value: T) -> Self {
10        Self(sync::Mutex::new(value))
11    }
12
13    /// Acquires a mutex, blocking the current thread until it is able to do so.
14    pub fn lock(&self) -> MutexGuard<'_, T> {
15        let guard = self.0.lock().unwrap();
16
17        MutexGuard(guard)
18    }
19
20    /// Consumes this mutex, returning the underlying data.
21    pub fn into_inner(self) -> T {
22        self.0.into_inner().unwrap()
23    }
24}
25
26/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
27/// dropped (falls out of scope), the lock will be unlocked.
28pub struct MutexGuard<'a, T>(sync::MutexGuard<'a, T>);
29
30impl<T> ops::Deref for MutexGuard<'_, T> {
31    type Target = T;
32
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl<T> ops::DerefMut for MutexGuard<'_, T> {
39    fn deref_mut(&mut self) -> &mut Self::Target {
40        &mut self.0
41    }
42}
43
44/// A synchronous reader-writer lock.
45#[derive(Default, Debug)]
46pub struct RwLock<T>(sync::RwLock<T>);
47
48impl<T> RwLock<T> {
49    /// Creates a new mutex in an unlocked state ready for use.
50    pub fn new(value: T) -> Self {
51        Self(sync::RwLock::new(value))
52    }
53
54    /// Locks this rwlock with shared read access, blocking the current thread
55    /// until it can be acquired.
56    pub fn read(&self) -> RwLockReadGuard<'_, T> {
57        let guard = self.0.read().unwrap();
58
59        RwLockReadGuard(guard)
60    }
61
62    /// Locks this rwlock with exclusive write access, blocking the current
63    /// thread until it can be acquired.
64    pub fn write(&self) -> RwLockWriteGuard<'_, T> {
65        let guard = self.0.write().unwrap();
66
67        RwLockWriteGuard(guard)
68    }
69}
70
71/// RAII structure used to release the shared read access of a lock when
72/// dropped.
73pub struct RwLockReadGuard<'a, T>(sync::RwLockReadGuard<'a, T>);
74
75impl<T> ops::Deref for RwLockReadGuard<'_, T> {
76    type Target = T;
77
78    fn deref(&self) -> &Self::Target {
79        &self.0
80    }
81}
82
83/// RAII structure used to release the exclusive write access of a lock when
84/// dropped.
85pub struct RwLockWriteGuard<'a, T>(sync::RwLockWriteGuard<'a, T>);
86
87impl<T> ops::Deref for RwLockWriteGuard<'_, T> {
88    type Target = T;
89
90    fn deref(&self) -> &Self::Target {
91        &self.0
92    }
93}
94
95impl<T> ops::DerefMut for RwLockWriteGuard<'_, T> {
96    fn deref_mut(&mut self) -> &mut Self::Target {
97        &mut self.0
98    }
99}