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
use std::cell::UnsafeCell;

use vasi::VirtualAddressSpaceIndependent;

use super::{Root, Tag};

/// Analagous to [std::cell::Cell]. In particular like [std::cell::Cell], it
/// doesn't perform any atomic operations internally, making it relatively
/// inexpensive.
///
/// Unlike [std::cell::Cell], 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 access.
#[derive(Debug, VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct RootedCell<T> {
    tag: Tag,
    val: UnsafeCell<T>,
}

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

    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        // Since we have the only reference to `self`, we don't need to check the root.
        unsafe { &mut *self.val.get() }
    }

    #[inline]
    pub fn set(&self, root: &Root, val: T) {
        // Replace the current value, and just drop the old value.
        drop(self.replace(root, val))
    }

    #[inline]
    pub fn replace(&self, root: &Root, val: T) -> T {
        // Prove that the root is held for this tag.
        assert_eq!(
            root.tag, self.tag,
            "Expected {:?} Got {:?}",
            self.tag, root.tag
        );

        unsafe { self.val.get().replace(val) }
    }

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

impl<T: Copy> RootedCell<T> {
    #[inline]
    pub fn get(&self, root: &Root) -> T {
        // Prove that the root is held for this tag.
        assert_eq!(
            root.tag, self.tag,
            "Expected {:?} Got {:?}",
            self.tag, root.tag
        );

        unsafe { *self.val.get() }
    }
}

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

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

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

    #[test]
    fn get() {
        let root = Root::new();
        let c = RootedCell::new(&root, 1);
        assert_eq!(c.get(&root), 1);
    }

    #[test]
    fn get_mut() {
        let root = Root::new();
        let mut c = RootedCell::new(&root, 1);
        assert_eq!(*c.get_mut(), 1);
    }

    #[test]
    fn set() {
        let root = Root::new();
        let c = RootedCell::new(&root, 1);
        c.set(&root, 2);
        assert_eq!(c.get(&root), 2);
    }

    #[test]
    fn replace() {
        let root = Root::new();
        let c = RootedCell::new(&root, 1);
        let old = c.replace(&root, 2);
        assert_eq!(old, 1);
        assert_eq!(c.get(&root), 2);
    }

    #[test]
    fn share_with_worker_thread() {
        let root = Root::new();
        let rc = RootedRc::new(&root, RootedCell::new(&root, 0));
        let root = {
            let rc = { rc.clone(&root) };
            thread::spawn(move || {
                rc.set(&root, 3);
                rc.explicit_drop(&root);
                root
            })
            .join()
            .unwrap()
        };
        assert_eq!(rc.get(&root), 3);
        rc.explicit_drop(&root);
    }

    #[test]
    fn worker_thread_get_mut() {
        let root = Root::new();
        let cell = RootedCell::new(&root, 0);
        let cell = {
            thread::spawn(move || {
                // Move into closure and make mutable.
                let mut cell = cell;
                // Since we have a mutable reference, we don't
                // need the root to access.
                *cell.get_mut() = 3;
                // Return cell to parent thread.
                cell
            })
            .join()
            .unwrap()
        };
        assert_eq!(cell.get(&root), 3);
    }
}