1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#[cfg(not(feature = "std"))]
pub use no_std_lock::*;
#[cfg(feature = "std")]
pub use std_lock::*;

#[cfg(feature = "std")]
mod std_lock {
    use std::sync::Mutex as StdMutex;
    pub use std::sync::MutexGuard;

    /// A wrapper around [`std::sync::Mutex`].
    #[derive(Debug)]
    pub struct Mutex<T> {
        inner: std::sync::Mutex<T>,
    }

    impl<T> Mutex<T> {
        /// Creates a new mutex in an unlocked state ready for use.
        pub fn new(data: T) -> Self {
            Self {
                inner: StdMutex::new(data),
            }
        }

        /// Acquires the mutex, blocking the current thread until it is able to do so.
        ///
        /// This will return `None` in the case the mutex is poisoned.
        #[inline]
        pub fn lock(&self) -> Option<MutexGuard<'_, T>> {
            self.inner.lock().ok()
        }
    }
}

#[cfg(not(feature = "std"))]
mod no_std_lock {
    use alloc::boxed::Box;
    use alloc::sync::Arc;
    use core::fmt::Debug;
    use core::ops::DerefMut;

    #[derive(Debug)]
    /// A no-std compatible wrapper around [`Lock`].
    pub struct Mutex<T> {
        inner: Arc<dyn Lock<T>>,
    }

    impl<T: Send + 'static> Mutex<T> {
        /// Creates a new mutex in an unlocked state ready for use.
        pub fn new<M>(val: T) -> Self
        where
            M: MakeMutex,
            T: Send + 'static,
        {
            Self {
                inner: M::make_mutex(val),
            }
        }

        /// Acquires the mutex, blocking the current thread until it is able to do so.
        ///
        /// This will return `None` in the case the mutex is poisoned.
        #[inline]
        pub fn lock(&self) -> Option<MutexGuard<'_, T>> {
            self.inner.lock().ok()
        }
    }

    /// A lock protecting shared data.
    pub trait Lock<T>: Debug + Send + Sync {
        /// Acquire the lock.
        fn lock(&self) -> Result<MutexGuard<'_, T>, Poisoned>;
    }

    /// A lock builder.                                                                                     
    pub trait MakeMutex {
        /// Create a new mutex.                                                                             
        fn make_mutex<T>(value: T) -> Arc<dyn Lock<T>>
        where
            T: Send + 'static;
    }

    /// A no-std compatible mutex guard.
    pub type MutexGuard<'a, T> = Box<dyn DerefMut<Target = T> + 'a>;

    /// A marker type used to indicate `Lock::lock` failed due to a poisoned lock.
    pub struct Poisoned;
}