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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use std::cell::{Cell, UnsafeCell};

use vasi::VirtualAddressSpaceIndependent;

use crate::explicit_drop::ExplicitDrop;

use super::{Root, Tag};

/// Analagous to [std::cell::RefCell]. In particular like [std::cell::RefCell]
/// and unlike [std::sync::Mutex], it  doesn't perform any atomic operations
/// internally, making it relatively inexpensive.
///
/// Unlike [std::cell::RefCell], this type is [Send] and [Sync] if `T` is
/// [Send]. This is safe because the owner is required to prove access to the
/// associated [Root], which is `![Sync]`, to borrow.
#[derive(Debug, VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct RootedRefCell<T> {
    tag: Tag,
    val: UnsafeCell<T>,
    reader_count: Cell<u32>,
    writer: Cell<bool>,
}

impl<T> RootedRefCell<T> {
    /// Create a RootedRefCell associated with `root`.
    #[inline]
    pub fn new(root: &Root, val: T) -> Self {
        Self {
            tag: root.tag(),
            val: UnsafeCell::new(val),
            reader_count: Cell::new(0),
            writer: Cell::new(false),
        }
    }

    /// Borrow a reference. Panics if `root` is for the wrong [Root], or
    /// if this object is alread mutably borrowed.
    #[inline]
    pub fn borrow<'a>(&'a self, root: &'a Root) -> RootedRefCellRef<'a, T> {
        // Prove that the root is held for this tag.
        assert_eq!(
            root.tag, self.tag,
            "Expected {:?} Got {:?}",
            self.tag, root.tag
        );

        assert!(!self.writer.get());

        self.reader_count.set(self.reader_count.get() + 1);

        RootedRefCellRef { guard: self }
    }

    /// Borrow a mutable reference. Panics if `root` is for the wrong
    /// [Root], or if this object is already borrowed.
    #[inline]
    pub fn borrow_mut<'a>(&'a self, root: &'a Root) -> RootedRefCellRefMut<'a, T> {
        // Prove that the root is held for this tag.
        assert_eq!(
            root.tag, self.tag,
            "Expected {:?} Got {:?}",
            self.tag, root.tag
        );

        assert!(!self.writer.get());
        assert!(self.reader_count.get() == 0);

        self.writer.set(true);

        RootedRefCellRefMut { guard: self }
    }

    #[inline]
    pub fn into_inner(self) -> T {
        self.val.into_inner()
    }
}

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

impl<T> ExplicitDrop for RootedRefCell<T>
where
    T: ExplicitDrop,
{
    type ExplicitDropParam = <T as ExplicitDrop>::ExplicitDropParam;
    type ExplicitDropResult = <T as ExplicitDrop>::ExplicitDropResult;

    fn explicit_drop(self, param: &Self::ExplicitDropParam) -> Self::ExplicitDropResult {
        self.val.into_inner().explicit_drop(param)
    }
}

pub struct RootedRefCellRef<'a, T> {
    guard: &'a RootedRefCell<T>,
}

impl<'a, T> std::ops::Deref for RootedRefCellRef<'a, T> {
    type Target = T;

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

impl<'a, T> Drop for RootedRefCellRef<'a, T> {
    #[inline]
    fn drop(&mut self) {
        self.guard
            .reader_count
            .set(self.guard.reader_count.get() - 1);
    }
}

pub struct RootedRefCellRefMut<'a, T> {
    guard: &'a RootedRefCell<T>,
}

impl<'a, T> std::ops::Deref for RootedRefCellRefMut<'a, T> {
    type Target = T;

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

impl<'a, T> std::ops::DerefMut for RootedRefCellRefMut<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.guard.val.get().as_mut().unwrap() }
    }
}

impl<'a, T> Drop for RootedRefCellRefMut<'a, T> {
    #[inline]
    fn drop(&mut self) {
        self.guard.writer.set(false);
    }
}

#[cfg(test)]
mod test_rooted_refcell {
    use std::thread;

    use super::*;
    use crate::explicit_drop::ExplicitDrop;
    use crate::rootedcell::rc::RootedRc;

    #[test]
    fn construct_and_drop() {
        let root = Root::new();
        let _ = RootedRefCell::new(&root, 0);
    }

    #[test]
    fn share_with_worker_thread() {
        let root = Root::new();
        let rc = RootedRc::new(&root, RootedRefCell::new(&root, 0));
        let root = {
            let rc = { rc.clone(&root) };
            thread::spawn(move || {
                let mut borrow = rc.borrow_mut(&root);
                *borrow = 3;
                // Drop rc with lock still held.
                drop(borrow);
                rc.explicit_drop(&root);
                root
            })
            .join()
            .unwrap()
        };
        let borrow = rc.borrow(&root);
        assert_eq!(*borrow, 3);
        drop(borrow);
        rc.explicit_drop(&root);
    }
}