1use std::ops;
2
3use crate::{maker::*, Lockable, LockableNew};
4
5pub struct SpinMutex<T> {
7 mutex: parking_lot::Mutex<T>,
8}
9
10impl<T> LockableNew for SpinMutex<T> {
11 type Value = T;
12
13 fn new(t: T) -> Self {
15 Self {
16 mutex: parking_lot::Mutex::new(t),
17 }
18 }
19}
20
21impl<T: Default> Default for SpinMutex<T> {
22 fn default() -> Self {
23 Self::new(Default::default())
24 }
25}
26
27impl<T> Lockable for SpinMutex<T> {
28 type GuardMut<'a> = SpinMutexGuard<'a, T>
29 where
30 Self: 'a;
31
32 #[inline]
33 fn lock(&self) -> Self::GuardMut<'_> {
34 SpinMutexGuard {
35 locker: self,
36 guard: Some(self.mutex.lock()),
37 }
38 }
39
40 #[inline]
41 fn try_lock(&self) -> Option<Self::GuardMut<'_>> {
42 if let Some(guard) = self.mutex.try_lock() {
43 Some(SpinMutexGuard {
44 locker: self,
45 guard: Some(guard),
46 })
47 } else {
48 None
49 }
50 }
51
52 #[inline]
53 fn unlock(guard: Self::GuardMut<'_>) -> &Self {
54 let locker = guard.locker;
55
56 drop(guard);
57
58 locker
59 }
60}
61
62pub struct SpinMutexGuard<'a, T> {
64 locker: &'a SpinMutex<T>,
66 guard: Option<parking_lot::MutexGuard<'a, T>>,
67}
68
69impl<'a, T> Drop for SpinMutexGuard<'a, T> {
70 fn drop(&mut self) {
71 drop(self.guard.take())
72 }
73}
74
75impl<'a, T> ops::Deref for SpinMutexGuard<'a, T> {
76 type Target = T;
77
78 #[inline]
79 fn deref(&self) -> &Self::Target {
80 self.guard.as_deref().unwrap()
81 }
82}
83
84impl<'a, T> ops::DerefMut for SpinMutexGuard<'a, T> {
85 #[inline]
86 fn deref_mut(&mut self) -> &mut Self::Target {
87 self.guard.as_deref_mut().unwrap()
88 }
89}
90
91unsafe impl<'a, T: Send> Send for SpinMutexGuard<'a, T> {}
92
93pub type AsyncSpinMutex<T> =
95 AsyncLockableMaker<SpinMutex<T>, SpinMutex<DefaultAsyncLockableMediator>>;