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

pub struct FastLockGuard<'a, T> {
    mu: &'a FastLock<T>,
}

impl<'a, T> Drop for FastLockGuard<'a, T> {
    fn drop(&mut self) {
        assert!(self.mu.lock.swap(false, Release));
    }
}

impl<'a, T> Deref for FastLockGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        #[allow(unsafe_code)]
        unsafe {
            &*self.mu.inner.get()
        }
    }
}

impl<'a, T> DerefMut for FastLockGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        #[allow(unsafe_code)]
        unsafe {
            &mut *self.mu.inner.get()
        }
    }
}

pub struct FastLock<T> {
    lock: AtomicBool,
    inner: UnsafeCell<T>,
}

impl<T> FastLock<T> {
    pub fn new(inner: T) -> FastLock<T> {
        FastLock { lock: AtomicBool::new(false), inner: UnsafeCell::new(inner) }
    }

    pub fn try_lock(&self) -> Option<FastLockGuard<'_, T>> {
        let lock_result = self.lock.compare_and_swap(false, true, Acquire);

        // `compare_and_swap` returns the last value if successful,
        // otherwise the current value. If we succeed, it should return false.
        let success = !lock_result;

        if success { Some(FastLockGuard { mu: self }) } else { None }
    }
}