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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use crate::{borrow_mut, is_borrowed, unborrow_mut, BorrowFlag, Trace, STACK};
use std::{
    cell::{Cell, UnsafeCell},
    marker::Unsize,
    mem,
    ops::CoerceUnsized,
    rc::Rc,
};

/// Node containing arbitrary data.
///
/// Ensures that no double-mutable borrows exist and allows the contained item to
/// [Suspend](crate::Suspend) itself.
///
/// Node is fundamentally the same as [RefCell](std::cell::RefCell), but does one more thing:
/// it allows suspension of the last emitted node by using its `&mut`. Suspending allows the
/// node to be reborrowed without aliasing.
pub struct Node<T: ?Sized> {
    item: Rc<(Cell<BorrowFlag>, UnsafeCell<T>)>,
    size: usize,
    trace: Trace,
    stack: *mut Vec<(*const Cell<BorrowFlag>, *mut (), usize)>,
}

impl<T, U> CoerceUnsized<Node<U>> for Node<T>
where
    T: Unsize<U> + ?Sized,
    U: ?Sized,
{
}

impl<T> Clone for Node<T> {
    fn clone(&self) -> Self {
        Self {
            item: self.item.clone(),
            size: self.size,
            trace: self.trace.clone(),
            stack: STACK.with(|x| x.get()),
        }
    }
}

impl<T> Node<T> {
    /// Create a new node.
    pub fn new(item: T) -> Self {
        Self {
            item: Rc::new((Cell::new(0), UnsafeCell::new(item))),
            size: mem::size_of::<T>(),
            trace: Trace::empty(),
            stack: STACK.with(|x| x.get()),
        }
    }

    /// Create a new node with a tracing function.
    ///
    /// The trace function is called with the current indentation value. It can be used to log
    /// calls to nodes and see how various nodes call upon other nodes.
    ///
    /// Requires the `trace` feature to be enabled to actually use the `trace` function.
    pub fn new_with_trace(item: T, trace: impl Fn(usize) + 'static) -> Self {
        Self {
            item: Rc::new((Cell::new(0), UnsafeCell::new(item))),
            size: mem::size_of::<T>(),
            trace: Trace::new(trace),
            stack: STACK.with(|x| x.get()),
        }
    }
}

impl<T: ?Sized> Node<T> {
    /// Acquire a `&mut` to the contents of the node and allow it to [Suspend](crate::Suspend) itself.
    ///
    /// ```
    /// use revent::Node;
    ///
    /// let node = Node::new(123);
    ///
    /// node.emit(|x| {
    ///     *x = 456;
    ///     println!("{}", x);
    /// });
    /// ```
    ///
    /// # Panics #
    ///
    /// Panics if the node has already been accessed without being suspended.
    ///
    /// ```should_panic
    /// use revent::Node;
    /// let node = Node::new(123);
    ///
    /// node.emit(|_| {
    ///     node.emit(|_| {});
    /// });
    /// ```
    ///
    /// The mitigation is to call suspend on the `emit` lambda argument.
    /// ```
    /// use revent::{Node, Suspend};
    /// let node = Node::new(123);
    ///
    /// node.emit(|x| {
    ///     x.suspend(|| {
    ///         node.emit(|_| {});
    ///     });
    /// });
    /// ```
    pub fn emit<F: FnOnce(&mut T) -> R, R>(&self, handler: F) -> R {
        self.trace.log();

        if is_borrowed(self.flag()) {
            panic!("revent: emit: accessing already borrowed item");
        }
        borrow_mut(self.flag());

        unsafe { &mut *self.stack }.push((self.flag(), self.data().get() as *mut _, self.size));

        // unsafe: `item` is an `Rc`, which guarantees the existence and validity of the
        // pointee. It is also safeguarded by `self.used`, which we have proven above to be
        // `false`, otherwise we would have panicked.
        let object = unsafe { &mut *self.data().get() };
        let data = (handler)(object);

        unsafe { &mut *self.stack }.pop();
        unborrow_mut(self.flag());
        data
    }

    /// Returns true if two `Node`s point to the same allocation.
    #[inline]
    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
        Rc::ptr_eq(&this.item, &other.item)
    }

    #[inline]
    fn data(&self) -> &UnsafeCell<T> {
        &self.item.1
    }

    #[inline]
    fn flag(&self) -> &Cell<BorrowFlag> {
        &self.item.0
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn emit_works() {
        let node = Node::new(123);
        node.emit(|x| {
            assert_eq!(*x, 123);
            *x = 1;
        });
        node.emit(|x| {
            assert_eq!(*x, 1);
        });
    }
}

#[cfg(all(test, feature = "trace"))]
mod trace_tests {
    use crate::*;
    use std::{cell::RefCell, rc::Rc};

    #[test]
    fn tracing() {
        let out = Rc::new(RefCell::new(None));

        let capture = out.clone();
        let node = Node::new_with_trace((), move |indent| {
            *capture.borrow_mut() = Some(indent);
        });

        node.emit(|_| {});

        assert!(matches!(*out.borrow(), Some(0)));
    }

    #[quickcheck_macros::quickcheck]
    fn tracing_nested(nestings: u8) {
        let out = Rc::new(RefCell::new(None));

        let capture = out.clone();
        let node = Node::new_with_trace((), move |indent| {
            *capture.borrow_mut() = Some(indent);
        });

        fn call(node: &Node<()>, count: u8) {
            if count == 0 {
                return;
            }
            node.emit(|x| {
                x.suspend(|| {
                    call(node, count - 1);
                });
            });
        };

        call(&node, nestings);

        if nestings == 0 {
            assert!(matches!(*out.borrow(), None));
        } else {
            assert_eq!(out.borrow().unwrap(), usize::from(nestings - 1));
        }
    }
}