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
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;

use crate::raw::root::RED4ext as red;

/// A read-write spin lock read guard. Permits any number of readers to access the locked data.
pub struct RwSpinLockReadGuard<'a, T> {
    lock: &'a red::SharedSpinLock,
    value: NonNull<T>,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> RwSpinLockReadGuard<'a, T> {
    #[inline]
    pub(crate) unsafe fn new(lock: &'a red::SharedSpinLock, value: NonNull<T>) -> Self {
        unsafe { red::SharedSpinLock_LockShared(lock as *const _ as *mut red::SharedSpinLock) };
        Self {
            value,
            lock,
            phantom: PhantomData,
        }
    }
}

impl<T> Deref for RwSpinLockReadGuard<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { self.value.as_ref() }
    }
}

impl<T> Drop for RwSpinLockReadGuard<'_, T> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            red::SharedSpinLock_UnlockShared(self.lock as *const _ as *mut red::SharedSpinLock)
        };
    }
}

/// A read-write spin lock write guard. Permits only one thread at a time to access the locked data.
pub struct RwSpinLockWriteGuard<'a, T> {
    lock: &'a red::SharedSpinLock,
    value: NonNull<T>,
    phantom: PhantomData<&'a mut T>,
}

impl<'a, T> RwSpinLockWriteGuard<'a, T> {
    #[inline]
    pub(crate) unsafe fn new(lock: &'a red::SharedSpinLock, value: NonNull<T>) -> Self {
        unsafe { red::SharedSpinLock_Lock(lock as *const _ as *mut red::SharedSpinLock) };
        Self {
            value,
            lock,
            phantom: PhantomData,
        }
    }
}

impl<T> Deref for RwSpinLockWriteGuard<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { self.value.as_ref() }
    }
}

impl<T> DerefMut for RwSpinLockWriteGuard<'_, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.value.as_ptr() }
    }
}

impl<T> Drop for RwSpinLockWriteGuard<'_, T> {
    #[inline]
    fn drop(&mut self) {
        unsafe { red::SharedSpinLock_Unlock(self.lock as *const _ as *mut red::SharedSpinLock) };
    }
}