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 #[derive(Debug)]
13 pub struct Mutex<T> {
14 inner: StdMutex<T>,
15 }
16
17 impl<T> Mutex<T> {
18 pub fn new(data: T) -> Self {
20 Self {
21 inner: StdMutex::new(data),
22 }
23 }
24
25 #[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 #[derive(Debug)]
44 pub struct Mutex<T> {
45 inner: Arc<dyn Lock<T>>,
46 }
47
48 impl<T: Send + 'static> Mutex<T> {
49 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 #[inline]
64 pub fn lock(&self) -> Option<MutexGuard<'_, T>> {
65 self.inner.lock().ok()
66 }
67 }
68
69 pub trait Lock<T>: Debug + Send + Sync {
71 fn lock(&self) -> Result<MutexGuard<'_, T>, Poisoned>;
73 }
74
75 pub trait MakeMutex {
77 fn make_mutex<T>(value: T) -> Arc<dyn Lock<T>>
79 where
80 T: Send + 'static;
81 }
82
83 pub type MutexGuard<'a, T> = Box<dyn DerefMut<Target = T> + 'a>;
85
86 pub struct Poisoned;
88}