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
use core::cell::UnsafeCell;
use core::intrinsics;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};

pub struct Mutex<T>(AtomicBool, UnsafeCell<T>);
pub struct MutexGuard<'a, T>(&'a Mutex<T>) where T: 'a;

impl<T> Mutex<T> {
    pub const fn new(x: T) -> Mutex<T> {
        Mutex(AtomicBool::new(false), UnsafeCell::new(x))
    }

    pub fn lock<'a>(&'a self) -> MutexGuard<'a, T> {
        // Spin until we acquire.
        while self.0.compare_and_swap(false, true, Ordering::Acquire) == true { }

        MutexGuard(self)
    }
}

unsafe impl<T: Send> Sync for Mutex<T> { }

impl<'a, T> Drop for MutexGuard<'a, T> {
    fn drop(&mut self) {
        (self.0).0.store(false, Ordering::Release);
    }
}

impl<'a, T> Deref for MutexGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe {
            intrinsics::transmute::<*mut T, &T>((self.0).1.get())
        }
    }
}

impl<'a, T> DerefMut for MutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe {
            intrinsics::transmute::<*mut T, &mut T>((self.0).1.get())
        }
    }
}