rustls/
lock.rs

1#[cfg(not(feature = "std"))]
2pub use no_std_lock::*;
3#[cfg(feature = "std")]
4pub use std_lock::*;
5
6#[cfg(feature = "std")]
7mod std_lock {
8    use std::sync::Mutex as StdMutex;
9    pub use std::sync::MutexGuard;
10
11    /// A wrapper around [`std::sync::Mutex`].
12    #[derive(Debug)]
13    pub struct Mutex<T> {
14        inner: StdMutex<T>,
15    }
16
17    impl<T> Mutex<T> {
18        /// Creates a new mutex in an unlocked state ready for use.
19        pub fn new(data: T) -> Self {
20            Self {
21                inner: StdMutex::new(data),
22            }
23        }
24
25        /// Acquires the mutex, blocking the current thread until it is able to do so.
26        ///
27        /// This will return `None` in the case the mutex is poisoned.
28        #[inline]
29        pub fn lock(&self) -> Option<MutexGuard<'_, T>> {
30            self.inner.lock().ok()
31        }
32    }
33}
34
35#[cfg(not(feature = "std"))]
36mod no_std_lock {
37    use alloc::boxed::Box;
38    use alloc::sync::Arc;
39    use core::fmt::Debug;
40    use core::ops::DerefMut;
41
42    /// A no-std compatible wrapper around [`Lock`].
43    #[derive(Debug)]
44    pub struct Mutex<T> {
45        inner: Arc<dyn Lock<T>>,
46    }
47
48    impl<T: Send + 'static> Mutex<T> {
49        /// Creates a new mutex in an unlocked state ready for use.
50        pub fn new<M>(val: T) -> Self
51        where
52            M: MakeMutex,
53            T: Send + 'static,
54        {
55            Self {
56                inner: M::make_mutex(val),
57            }
58        }
59
60        /// Acquires the mutex, blocking the current thread until it is able to do so.
61        ///
62        /// This will return `None` in the case the mutex is poisoned.
63        #[inline]
64        pub fn lock(&self) -> Option<MutexGuard<'_, T>> {
65            self.inner.lock().ok()
66        }
67    }
68
69    /// A lock protecting shared data.
70    pub trait Lock<T>: Debug + Send + Sync {
71        /// Acquire the lock.
72        fn lock(&self) -> Result<MutexGuard<'_, T>, Poisoned>;
73    }
74
75    /// A lock builder.
76    pub trait MakeMutex {
77        /// Create a new mutex.
78        fn make_mutex<T>(value: T) -> Arc<dyn Lock<T>>
79        where
80            T: Send + 'static;
81    }
82
83    /// A no-std compatible mutex guard.
84    pub type MutexGuard<'a, T> = Box<dyn DerefMut<Target = T> + 'a>;
85
86    /// A marker type used to indicate `Lock::lock` failed due to a poisoned lock.
87    pub struct Poisoned;
88}