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
use core::{
    cell::UnsafeCell,
    fmt,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::NonNull,
    sync::atomic::{AtomicUsize, Ordering},
};

/// Atomic ReFCell - ArfCell
///
/// Like a refcell (or RwLock), but atomic, has a const constructor,
/// and doesn't panic
pub struct ArfCell<T> {
    state: AtomicUsize,
    item: UnsafeCell<T>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BorrowError {
    mutable: bool,
}

unsafe impl<T> Sync for ArfCell<T> where T: Send {}

pub struct MutArfGuard<'a, T> {
    cell: NonNull<ArfCell<T>>,
    plt: PhantomData<&'a mut T>,
}

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

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.cell.as_ref().item.get() }
    }
}

impl<'a, T> DerefMut for MutArfGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.cell.as_mut().item.get_mut() }
    }
}

impl<'a, T> Drop for MutArfGuard<'a, T> {
    fn drop(&mut self) {
        unsafe {
            self.cell.as_ref().state.store(0, Ordering::Release);
        }
    }
}

pub struct ArfGuard<'a, T> {
    cell: NonNull<ArfCell<T>>,
    plt: PhantomData<&'a mut T>,
}

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

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.cell.as_ref().item.get() }
    }
}

impl<'a, T> Drop for ArfGuard<'a, T> {
    fn drop(&mut self) {
        unsafe {
            let x = self.cell.as_ref().state.fetch_sub(1, Ordering::AcqRel);
            debug_assert!(x != 0, "Underflow on refcnt release!");
        }
    }
}

impl<T> ArfCell<T> {
    const MUTLOCK: usize = (usize::MAX / 2) + 1;

    pub const fn new(item: T) -> Self {
        ArfCell {
            state: AtomicUsize::new(0),
            item: UnsafeCell::new(item),
        }
    }

    pub fn borrow_mut(&self) -> Result<MutArfGuard<'_, T>, BorrowError> {
        self.state
            .compare_exchange(
                0,
                Self::MUTLOCK,
                // TODO: Relax these
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .map_err(|_| BorrowError { mutable: false })?;

        Ok(MutArfGuard {
            cell: unsafe { NonNull::new_unchecked(self as *const Self as *mut Self) },
            plt: PhantomData,
        })
    }

    pub fn borrow(&self) -> Result<ArfGuard<'_, T>, BorrowError> {
        // proactive check we aren't mutably locked
        if self.state.load(Ordering::Acquire) >= Self::MUTLOCK {
            return Err(BorrowError { mutable: true });
        }

        // TODO: Check the old value to see if we're close to overflowing the refcnt?

        // Now fetch-add, and see how it goes
        let old = self.state.fetch_add(1, Ordering::AcqRel);
        if old >= Self::MUTLOCK {
            // Oops, we raced with a mutable lock. We lose.
            // It's okay we incremented `state` here anyway - the mutable lock will
            // unconditionally reset to zero, and future borrowers will hopefully be
            // caught by the proactive check above to reduce the chance of
            // overflowing the refcount.
            return Err(BorrowError { mutable: true });
        }

        Ok(ArfGuard {
            cell: unsafe { NonNull::new_unchecked(self as *const Self as *mut Self) },
            plt: PhantomData,
        })
    }
}

// === impl BorrowError ===

impl fmt::Display for BorrowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.mutable {
            write!(f, "already mutably borrowed")
        } else {
            write!(f, "already borrowed")
        }
    }
}