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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use alloc::alloc::Global;
use core::alloc::Allocator;
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
use crate::poison::{self, LockResult, TryLockError, TryLockResult};

#[cfg(all(not(target_os="dos"), not(windows)))]
mod posix;

#[cfg(all(not(target_os="dos"), windows))]
mod winapi;

#[cfg(target_os="dos")]
mod dos;

#[cfg(all(not(target_os="dos"), not(windows)))]
use posix::SysMutex;

#[cfg(all(not(target_os="dos"), windows))]
use winapi::SysMutex;

#[cfg(target_os="dos")]
use dos::SysMutex;

pub struct Mutex<T: ?Sized, A: Allocator + Clone = Global> {
    inner: SysMutex<A>,
    poison: poison::Flag,
    data: UnsafeCell<T>,
}

unsafe impl<T: ?Sized + Send, A: Allocator + Clone> Send for Mutex<T, A> { }

unsafe impl<T: ?Sized + Send, A: Allocator + Clone> Sync for Mutex<T, A> { }

#[must_use="if unused the Mutex will immediately unlock"]
pub struct MutexGuard<'a, T: ?Sized + 'a, A: Allocator + Clone = Global> {
    lock: &'a Mutex<T, A>,
    poison: poison::Guard,
}

impl<T: ?Sized, A: Allocator + Clone> !Send for MutexGuard<'_, T, A> { }

unsafe impl<T: ?Sized + Sync, A: Allocator + Clone> Sync for MutexGuard<'_, T, A> { }

impl<T, A: Allocator + Clone> Mutex<T, A> {
    pub const fn new_in(t: T, allocator: A) -> Mutex<T, A> {
        Mutex { inner: SysMutex::new_in(allocator), poison: poison::Flag::new(), data: UnsafeCell::new(t) }
    }
}

impl<T> Mutex<T> {
    pub const fn new(t: T) -> Mutex<T> {
        Mutex::new_in(t, Global)
    }
}

impl<T: ?Sized, A: Allocator + Clone> Mutex<T, A> {
    pub fn lock(&self) -> LockResult<MutexGuard<'_, T, A>> {
        unsafe {
            self.inner.lock();
            MutexGuard::new(self)
        }
    }

    pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T, A>> {
        unsafe {
            if self.inner.try_lock() {
                Ok(MutexGuard::new(self)?)
            } else {
                Err(TryLockError::WouldBlock)
            }
        }
    }

    pub fn is_poisoned(&self) -> bool {
        self.poison.get()
    }

    pub fn clear_poison(&self) {
        self.poison.clear();
    }

    pub fn into_inner(self) -> LockResult<T>
    where
        T: Sized,
    {
        let data = self.data.into_inner();
        poison::map_result(self.poison.borrow(), |()| data)
    }

    pub fn get_mut(&mut self) -> LockResult<&mut T> {
        let data = self.data.get_mut();
        poison::map_result(self.poison.borrow(), |()| data)
    }
}

impl<T> From<T> for Mutex<T> {
    fn from(t: T) -> Self {
        Mutex::new(t)
    }
}

impl<T: Default> Default for Mutex<T> {
    fn default() -> Mutex<T> {
        Mutex::new(Default::default())
    }
}

impl<T: ?Sized + fmt::Debug, A: Allocator + Clone> fmt::Debug for Mutex<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("Mutex");
        match self.try_lock() {
            Ok(guard) => {
                d.field("data", &&*guard);
            }
            Err(TryLockError::Poisoned(err)) => {
                d.field("data", &&**err.get_ref());
            }
            Err(TryLockError::WouldBlock) => {
                d.field("data", &format_args!("<locked>"));
            }
        }
        d.field("poisoned", &self.poison.get());
        d.finish_non_exhaustive()
    }
}

impl<'mutex, T: ?Sized, A: Allocator + Clone> MutexGuard<'mutex, T, A> {
    unsafe fn new(lock: &'mutex Mutex<T, A>) -> LockResult<MutexGuard<'mutex, T, A>> {
        poison::map_result(lock.poison.guard(), |guard| MutexGuard { lock, poison: guard })
    }
}

impl<T: ?Sized, A: Allocator + Clone> Deref for MutexGuard<'_, T, A> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.lock.data.get() }
    }
}

impl<T: ?Sized, A: Allocator + Clone> DerefMut for MutexGuard<'_, T, A> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.lock.data.get() }
    }
}

impl<T: ?Sized, A: Allocator + Clone> Drop for MutexGuard<'_, T, A> {
    fn drop(&mut self) {
        unsafe {
            self.lock.poison.done(&self.poison);
            self.lock.inner.unlock();
        }
    }
}

impl<T: ?Sized + fmt::Debug, A: Allocator + Clone> fmt::Debug for MutexGuard<'_, T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: ?Sized + fmt::Display, A: Allocator + Clone> fmt::Display for MutexGuard<'_, T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}