1use std::{
2 cell::UnsafeCell,
3 ops::{Deref, DerefMut},
4 sync::atomic::{
5 AtomicBool,
6 Ordering::{Acquire, Release},
7 },
8};
9
10pub struct FastLockGuard<'a, T> {
11 mu: &'a FastLock<T>,
12}
13
14impl<'a, T> Drop for FastLockGuard<'a, T> {
15 fn drop(&mut self) {
16 assert!(self.mu.lock.swap(false, Release));
17 }
18}
19
20impl<'a, T> Deref for FastLockGuard<'a, T> {
21 type Target = T;
22
23 fn deref(&self) -> &T {
24 #[allow(unsafe_code)]
25 unsafe {
26 &*self.mu.inner.get()
27 }
28 }
29}
30
31impl<'a, T> DerefMut for FastLockGuard<'a, T> {
32 fn deref_mut(&mut self) -> &mut T {
33 #[allow(unsafe_code)]
34 unsafe {
35 &mut *self.mu.inner.get()
36 }
37 }
38}
39
40pub struct FastLock<T> {
41 lock: AtomicBool,
42 inner: UnsafeCell<T>,
43}
44
45impl<T> FastLock<T> {
46 pub fn new(inner: T) -> FastLock<T> {
47 FastLock { lock: AtomicBool::new(false), inner: UnsafeCell::new(inner) }
48 }
49
50 pub fn try_lock(&self) -> Option<FastLockGuard<'_, T>> {
51 let lock_result = self.lock.compare_and_swap(false, true, Acquire);
52
53 let success = !lock_result;
56
57 if success { Some(FastLockGuard { mu: self }) } else { None }
58 }
59}