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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use core::cell::UnsafeCell;
use core::marker::PhantomData;

use super::Invariant;
type Id<'id> = PhantomData<Invariant<&'id ()>>;

/// Borrowing-owner of zero or more [`LCell`](struct.LCell.html)
/// instances.
///
/// Use `LCellOwner::scope(|owner| ...)` to create an instance of this
/// type.  The key piece of Rust syntax that enables this is
/// `for<'id>`.  This allows creating an invariant lifetime within a
/// closure, which is different to any other Rust lifetime thanks to
/// the techniques explained in various places: section 6.3 of [this
/// thesis from Gankra (formerly
/// Gankro)](https://raw.githubusercontent.com/Gankra/thesis/master/thesis.pdf),
/// [this Reddit
/// post](https://www.reddit.com/r/rust/comments/3oo0oe/sound_unchecked_indexing_with_lifetimebased_value/),
/// and [this Rust playground
/// example](https://play.rust-lang.org/?gist=21a00b0e181a918f8ca4&version=stable).
/// Also see [this Reddit
/// comment](https://www.reddit.com/r/rust/comments/3aahl1/outside_of_closures_what_are_some_other_uses_for/csavac5/)
/// and its linked playground code.
///
/// Alternatively, if the **generativity** feature is enabled, the
/// [`generativity`](https://crates.io/crates/generativity) crate can
/// be used to create an owner as follows: `make_guard!(guard); let
/// mut owner = LCellOwner::new(guard);`.  However note that the Rust
/// compiler error messages may be more confusing with
/// **generativity** if you make a mistake and use the wrong owner for
/// a cell.
///
/// Some history: `GhostCell` by
/// [**pythonesque**](https://github.com/pythonesque) predates the
/// creation of `LCell`, and inspired it.  Discussion of `GhostCell`
/// on Reddit showed that a lifetime-based approach to cells was
/// feasible, but unfortunately the `ghost_cell.rs` source didn't seem
/// to be available under a community-friendly licence.  So I went
/// back to first principles and created `LCell` from `TCell` code,
/// combined with invariant lifetime code derived from the various
/// community sources that predate `GhostCell`.  Later `Send` and
/// `Sync` support for `LCell` was contributed independently.
///
/// See also [crate documentation](index.html).
pub struct LCellOwner<'id> {
    _id: Id<'id>,
}

impl<'id> LCellOwner<'id> {
    /// Create a new `LCellOwner`, with a new lifetime, that exists
    /// only within the scope of the execution of the given closure
    /// call.  If two scope calls are nested, then the two owners get
    /// different lifetimes.
    ///
    /// ```rust
    /// use qcell::{LCellOwner, LCell};
    /// LCellOwner::scope(|owner| {
    ///     let cell = LCell::new(100);
    ///     assert_eq!(cell.ro(&owner), &100);
    /// })
    /// ```
    pub fn scope<F>(f: F)
    where
        F: for<'scope_id> FnOnce(LCellOwner<'scope_id>),
    {
        f(Self { _id: PhantomData })
    }

    /// Create a new `LCellOwner` with a unique lifetime from a `Guard`.
    ///
    /// ```rust
    /// use qcell::{generativity::make_guard, LCellOwner, LCell};
    /// make_guard!(guard);
    /// let mut owner = LCellOwner::new(guard);
    /// let cell = LCell::new(100);
    /// assert_eq!(cell.ro(&owner), &100);
    /// ```
    #[cfg(feature = "generativity")]
    #[cfg_attr(docsrs, doc(cfg(feature = "generativity")))]
    pub fn new(_guard: generativity::Guard<'id>) -> Self {
        Self { _id: PhantomData }
    }

    /// Create a new cell owned by this owner instance.  See also
    /// [`LCell::new`].
    ///
    /// [`LCell::new`]: struct.LCell.html
    pub fn cell<T>(&self, value: T) -> LCell<'id, T> {
        LCell::<T>::new(value)
    }

    /// Borrow contents of a `LCell` immutably (read-only).  Many
    /// `LCell` instances can be borrowed immutably at the same time
    /// from the same owner.
    #[inline]
    pub fn ro<'a, T: ?Sized>(&'a self, lc: &'a LCell<'id, T>) -> &'a T {
        unsafe { &*lc.value.get() }
    }

    /// Borrow contents of a `LCell` mutably (read-write).  Only one
    /// `LCell` at a time can be borrowed from the owner using this
    /// call.  The returned reference must go out of scope before
    /// another can be borrowed.
    #[inline]
    pub fn rw<'a, T: ?Sized>(&'a mut self, lc: &'a LCell<'id, T>) -> &'a mut T {
        unsafe { &mut *lc.value.get() }
    }

    /// Borrow contents of two `LCell` instances mutably.  Panics if
    /// the two `LCell` instances point to the same memory.
    #[inline]
    pub fn rw2<'a, T: ?Sized, U: ?Sized>(
        &'a mut self,
        lc1: &'a LCell<'id, T>,
        lc2: &'a LCell<'id, U>,
    ) -> (&'a mut T, &'a mut U) {
        assert!(
            lc1 as *const _ as *const () as usize != lc2 as *const _ as *const () as usize,
            "Illegal to borrow same LCell twice with rw2()"
        );
        unsafe { (&mut *lc1.value.get(), &mut *lc2.value.get()) }
    }

    /// Borrow contents of three `LCell` instances mutably.  Panics if
    /// any pair of `LCell` instances point to the same memory.
    #[inline]
    pub fn rw3<'a, T: ?Sized, U: ?Sized, V: ?Sized>(
        &'a mut self,
        lc1: &'a LCell<'id, T>,
        lc2: &'a LCell<'id, U>,
        lc3: &'a LCell<'id, V>,
    ) -> (&'a mut T, &'a mut U, &'a mut V) {
        assert!(
            (lc1 as *const _ as *const () as usize != lc2 as *const _ as *const () as usize)
                && (lc2 as *const _ as *const () as usize != lc3 as *const _ as *const () as usize)
                && (lc3 as *const _ as *const () as usize != lc1 as *const _ as *const () as usize),
            "Illegal to borrow same LCell twice with rw3()"
        );
        unsafe {
            (
                &mut *lc1.value.get(),
                &mut *lc2.value.get(),
                &mut *lc3.value.get(),
            )
        }
    }
}

/// Cell whose contents are owned (for borrowing purposes) by a
/// [`LCellOwner`].
///
/// To borrow from this cell, use the borrowing calls on the
/// [`LCellOwner`] instance that owns it, i.e. that shares the same
/// Rust lifetime.
///
/// See also [crate documentation](index.html).
///
/// [`LCellOwner`]: struct.LCellOwner.html
#[repr(transparent)]
pub struct LCell<'id, T: ?Sized> {
    _id: Id<'id>,
    value: UnsafeCell<T>,
}

impl<'id, T> LCell<'id, T> {
    /// Create a new `LCell`.  The owner of this cell is inferred by
    /// Rust from the context.  So the owner lifetime is whatever
    /// lifetime is required by the first use of the new `LCell`.
    #[inline]
    pub fn new(value: T) -> LCell<'id, T> {
        LCell {
            _id: PhantomData,
            value: UnsafeCell::new(value),
        }
    }

    /// Destroy the cell and return the contained value
    ///
    /// Safety: Since this consumes the cell, there can be no other
    /// references to the cell or the data at this point.
    #[inline]
    pub fn into_inner(self) -> T {
        self.value.into_inner()
    }
}

impl<'id, T: ?Sized> LCell<'id, T> {
    /// Borrow contents of this cell immutably (read-only).  Many
    /// `LCell` instances can be borrowed immutably at the same time
    /// from the same owner.
    #[inline]
    pub fn ro<'a>(&'a self, owner: &'a LCellOwner<'id>) -> &'a T {
        owner.ro(self)
    }

    /// Borrow contents of this cell mutably (read-write).  Only one
    /// `LCell` at a time can be borrowed from the owner using this
    /// call.  The returned reference must go out of scope before
    /// another can be borrowed.  To mutably borrow from two or three
    /// cells at the same time, see [`LCellOwner::rw2`] or
    /// [`LCellOwner::rw3`].
    #[inline]
    pub fn rw<'a>(&'a self, owner: &'a mut LCellOwner<'id>) -> &'a mut T {
        owner.rw(self)
    }

    /// Returns a mutable reference to the underlying data
    ///
    /// Note that this is only useful at the beginning-of-life or
    /// end-of-life of the cell when you have exclusive access to it.
    /// Normally you'd use [`LCell::rw`] or [`LCellOwner::rw`] to get
    /// a mutable reference to the contents of the cell.
    ///
    /// Safety: This call borrows `LCell` mutably which guarantees
    /// that we possess the only reference.  This means that there can
    /// be no active borrows of other forms, even ones obtained using
    /// an immutable reference.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        self.value.get_mut()
    }
}

impl<'id, T: Default + ?Sized> Default for LCell<'id, T> {
    fn default() -> Self {
        LCell::new(T::default())
    }
}

// LCell already automatically implements Send, but not
// Sync. We can add these implementations though, since it's fine to
// send a &LCell to another thread, and even mutably borrow the value
// there, as long as T is Send and Sync.
//
// The reason why LCell<T>'s impl of Sync requires T: Send + Sync
// instead of just T: Sync is that LCell provides interior mutability.
// If you send a &LCell<T> (and its owner) to a different thread, you
// can call .rw() to get a &mut T, and use std::mem::swap() to move
// the T, effectively sending the T to that other thread. That's not
// allowed if T: !Send.
//
// Note that the bounds on T for LCell<T>'s impl of Sync are the same
// as those of std::sync::RwLock<T>. That's not a coincidence.
// The way these types let you access T concurrently is the same,
// even though the locking mechanisms are different.
unsafe impl<'id, T: Send + Sync + ?Sized> Sync for LCell<'id, T> {}

#[cfg(test)]
mod tests {
    use super::{LCell, LCellOwner};
    use std::rc::Rc;

    #[test]
    fn lcell() {
        LCellOwner::scope(|mut owner| {
            let c1 = LCell::new(100u32);
            let c2 = owner.cell(200u32);
            (*owner.rw(&c1)) += 1;
            (*owner.rw(&c2)) += 2;
            let c1ref = owner.ro(&c1);
            let c2ref = owner.ro(&c2);
            let total = *c1ref + *c2ref;
            assert_eq!(total, 303);
        });
    }

    #[test]
    #[cfg(feature = "generativity")]
    fn generativity() {
        generativity::make_guard!(guard);
        let mut owner = LCellOwner::new(guard);
        let c1 = LCell::new(100_u32);
        let c2 = LCell::new(200_u32);
        (*owner.rw(&c1)) += 1;
        (*owner.rw(&c2)) += 2;
        let c1ref = owner.ro(&c1);
        let c2ref = owner.ro(&c2);
        let total = *c1ref + *c2ref;
        assert_eq!(total, 303);
    }

    #[test]
    #[should_panic]
    fn lcell_rw2() {
        LCellOwner::scope(|mut owner| {
            let c1 = Rc::new(LCell::new(100u32));
            let (mutref1, mutref2) = owner.rw2(&c1, &c1);
            *mutref1 += 1;
            *mutref2 += 1;
        });
    }

    #[test]
    #[should_panic]
    fn lcell_rw3_1() {
        LCellOwner::scope(|mut owner| {
            let c1 = Rc::new(LCell::new(100u32));
            let c2 = Rc::new(LCell::new(200u32));
            let (mutref1, mutref2, mutref3) = owner.rw3(&c1, &c1, &c2);
            *mutref1 += 1;
            *mutref2 += 1;
            *mutref3 += 1;
        });
    }

    #[test]
    #[should_panic]
    fn lcell_rw3_2() {
        LCellOwner::scope(|mut owner| {
            let c1 = Rc::new(LCell::new(100u32));
            let c2 = Rc::new(LCell::new(200u32));
            let (mutref1, mutref2, mutref3) = owner.rw3(&c1, &c2, &c1);
            *mutref1 += 1;
            *mutref2 += 1;
            *mutref3 += 1;
        });
    }

    #[test]
    #[should_panic]
    fn lcell_rw3_3() {
        LCellOwner::scope(|mut owner| {
            let c1 = Rc::new(LCell::new(100u32));
            let c2 = Rc::new(LCell::new(200u32));
            let (mutref1, mutref2, mutref3) = owner.rw3(&c2, &c1, &c1);
            *mutref1 += 1;
            *mutref2 += 1;
            *mutref3 += 1;
        });
    }

    #[test]
    fn lcell_get_mut() {
        LCellOwner::scope(|owner| {
            let mut cell = LCell::new(100u32);
            let mut_ref = cell.get_mut();
            *mut_ref = 50;
            let cell_ref = owner.ro(&cell);
            assert_eq!(*cell_ref, 50);
        });
    }

    #[test]
    fn lcell_into_inner() {
        let cell = LCell::new(100u32);
        assert_eq!(cell.into_inner(), 100);
    }

    #[test]
    fn lcell_unsized() {
        LCellOwner::scope(|mut owner| {
            struct Squares(u32);
            struct Integers(u64);
            trait Series {
                fn step(&mut self);
                fn value(&self) -> u64;
            }
            impl Series for Squares {
                fn step(&mut self) {
                    self.0 += 1;
                }
                fn value(&self) -> u64 {
                    (self.0 as u64) * (self.0 as u64)
                }
            }
            impl Series for Integers {
                fn step(&mut self) {
                    self.0 += 1;
                }
                fn value(&self) -> u64 {
                    self.0
                }
            }
            fn series<'id>(init: u32, is_squares: bool) -> Box<LCell<'id, dyn Series>> {
                if is_squares {
                    Box::new(LCell::new(Squares(init)))
                } else {
                    Box::new(LCell::new(Integers(init as u64)))
                }
            }

            let own = &mut owner;
            let cell1 = series(4, false);
            let cell2 = series(7, true);
            let cell3 = series(3, true);
            assert_eq!(cell1.ro(own).value(), 4);
            cell1.rw(own).step();
            assert_eq!(cell1.ro(own).value(), 5);
            assert_eq!(own.ro(&cell2).value(), 49);
            own.rw(&cell2).step();
            assert_eq!(own.ro(&cell2).value(), 64);
            let (r1, r2, r3) = own.rw3(&cell1, &cell2, &cell3);
            r1.step();
            r2.step();
            r3.step();
            assert_eq!(cell1.ro(own).value(), 6);
            assert_eq!(cell2.ro(own).value(), 81);
            assert_eq!(cell3.ro(own).value(), 16);
            let (r1, r2) = own.rw2(&cell1, &cell2);
            r1.step();
            r2.step();
            assert_eq!(cell1.ro(own).value(), 7);
            assert_eq!(cell2.ro(own).value(), 100);
        });
    }
}