nest-guard 0.1.0

Utility for working with nested guard-type APIs
Documentation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! This crate works around the following weakness in standard Rust. It is
//! generally impossible to write:
//!
//!   // Say that you're working with a Weak<RefCell<u32>> for safe, shared
//!   // mutability.
//!   let x = Rc::new(RefCell::new(0));
//!   let x = Rc::downgrade(&x);
//!
//!   // This doesn't work. The Rc returned by x.upgrade() is dropped at the end
//!   // of the statement, and therefore ref_inner can't be used.
//!   let ref_inner = x.upgrade().unwrap().borrow();
//!   assert_eq!(0, *ref_inner);
//!
//! With this crate, replacing `borrow` with `nest_borrow` Just Works
//!
//!   let x = Rc::new(RefCell::new(0));
//!   let x = Rc::downgrade(&x);
//!
//!   let ref_inner = x.upgrade().unwrap().nest_borrow();
//!   assert_eq!(0, *ref_inner);
//!
//! The implementation relies on one `unsafe` function to prevent rustc from
//! being overly strict.
//!
//! The implementation guarantees that the "outer temporary" (Rc in the above
//! example) does in fact outlive the reference to it.
//!
//! The implementation has no runtime overhead.
//!
//! Arbitrary nesting depth is supported
//!
//!   let x = RefCell::new(RefCell::new(RefCell::new(0)));
//!   let ref_inner = x.borrow().nest_borrow().nest_borrow();
//!   assert_eq!(0, *ref_inner);
//!
//! `nest_*` functions also work fine in the initial position of the chain, in
//! which position they behave like their unprefixed analogues. The following
//! two lines are identical.
//!
//!   let ref_inner = x.     borrow().nest_borrow().nest_borrow();
//!   let ref_inner = x.nest_borrow().nest_borrow().nest_borrow();
//!
//! If you ever have had to work with the miserable experience of reassigning a
//! stack of guards, you may recognize that this code doesn't compile
//!
//!   let x = RefCell::new(RefCell::new(0));
//!   let ys: Vec<_> = (1..10).map(|i| RefCell::new(RefCell::new(i))).collect();
//!
//!   let mut ref1 = x.borrow();
//!   let mut ref2 = ref1.borrow_mut();
//!
//!   for y in ys.iter() {
//!     let mut yref1 = y.borrow();
//!     let mut yref2 = yref1.borrow_mut();
//!     mem::swap(ref2.deref_mut(), yref2.deref_mut());
//!     ref2 = yref2;
//!     ref1 = yref1;
//!   }
//!
//! However, the analogue using this crate again Just Works
//!
//!   let x = RefCell::new(RefCell::new(0));
//!   let ys: Vec<_> = (1..10).map(|i| RefCell::new(RefCell::new(i))).collect();
//!
//!   let mut ref1 = x.borrow().nest_borrow_mut();
//!
//!   for y in ys.iter() {
//!     let mut yref = y.borrow().nest_borrow_mut();
//!     mem::swap(ref1.deref_mut(), yref.deref_mut());
//!     ref1 = yref;
//!   }
//!
//! The following methods are provided, via extension traits
//!   std::cell::RefCell::nest_borrow
//!   std::cell::RefCell::nest_borrow_mut
//!   std::cell::RefCell::try_nest_borrow
//!   std::cell::RefCell::try_nest_borrow_mut
//!   std::rc::Weak::nest_upgrade
//!   std::sync::Weak::nest_upgrade
//!   std::sync::Mutex::nest_lock
//!   std::sync::Mutex::nest_try_lock
//!   std::sync::RwLock::nest_try_read
//!   std::sync::RwLock::nest_try_write

use std::ops::{Deref, DerefMut};

pub use self::cell::*;
pub use self::rc::*;
pub use self::sync::*;

/// NOTE that drop order is guaranteed first-to-last, so the inner ref is
/// dropped before the outer ref, which we rely on in our unsafe transmutes.
pub struct Nested<T, Inner: Deref<Target = T>, Outer> {
    inner: Inner,
    #[allow(dead_code)]
    outer: Outer,
}
impl<T, Inner: Deref<Target = T>, Outer> Deref for Nested<T, Inner, Outer> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}
impl<T, Inner: DerefMut<Target = T>, Outer> DerefMut for Nested<T, Inner, Outer> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

/// # Safety
///   At each usage site in this file, the justification is the same. We work
///   around rustc's inability to understand self-referential structs by casting
///   away the lifetime, and manually ensure that the referenced object outlives
///   the reference by bundling them both into the `Nested` struct.
unsafe fn remove_lifetime<'b, T>(x: &T) -> &'b T {
    unsafe { &*(x as *const T) }
}

mod cell {
    use std::cell::*;

    use super::*;

    pub trait NestedRefCell<'a, T>: Deref<Target = RefCell<T>> + Sized + 'a {
        fn nest_borrow(self) -> Nested<T, Ref<'a, T>, Self> {
            let me = unsafe { remove_lifetime(&self) };
            let inner = RefCell::borrow(me);
            Nested { inner, outer: self }
        }
        fn nest_try_borrow(self) -> Result<Nested<T, Ref<'a, T>, Self>, BorrowError> {
            let me = unsafe { remove_lifetime(&self) };
            let inner = RefCell::try_borrow(me)?;
            Ok(Nested { inner, outer: self })
        }
        fn nest_borrow_mut(self) -> Nested<T, RefMut<'a, T>, Self> {
            let me = unsafe { remove_lifetime(&self) };
            let inner = RefCell::borrow_mut(me);
            Nested { inner, outer: self }
        }
        fn nest_try_borrow_mut(self) -> Result<Nested<T, RefMut<'a, T>, Self>, BorrowMutError> {
            let me = unsafe { remove_lifetime(&self) };
            let inner = RefCell::try_borrow_mut(me)?;
            Ok(Nested { inner, outer: self })
        }
    }
    impl<'a, T, Outer: Deref<Target = RefCell<T>> + Sized + 'a> NestedRefCell<'a, T> for Outer {}

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

        #[test]
        fn test_many_refcell() {
            let x = RefCell::new(RefCell::new(RefCell::new(0)));
            {
                let z = x.borrow().nest_borrow().nest_borrow();
                assert_eq!(0, *z);
            }
            {
                let z = x
                    .try_borrow()
                    .unwrap()
                    .nest_try_borrow()
                    .unwrap()
                    .nest_try_borrow()
                    .unwrap();
                assert_eq!(0, *z);
            }
            {
                let mut z = x.borrow().nest_borrow().nest_borrow_mut();
                *z = 1;
                assert_eq!(1, *z);
            }
            {
                {
                    let mut y = x.borrow().nest_borrow_mut();
                    *y = RefCell::new(2);
                }
                let z = x.borrow().nest_borrow().nest_borrow();
                assert_eq!(2, *z);
            }
        }
    }
}
mod rc {
    use std::rc::*;

    use super::*;

    pub trait NestedRcWeak<'a, T>: Deref<Target = Weak<T>> + Sized + 'a {
        fn nest_upgrade(self) -> Option<Nested<T, Rc<T>, Self>> {
            let inner = Weak::upgrade(&self)?;
            Some(Nested { inner, outer: self })
        }
    }
    impl<'a, T, Outer: Deref<Target = Weak<T>> + Sized + 'a> NestedRcWeak<'a, T> for Outer {}
    #[cfg(test)]
    mod test {
        use super::*;

        #[test]
        fn test_many_rc() {
            let x1: Rc<i32> = Rc::new(0);
            let y1: Weak<i32> = Rc::downgrade(&x1);

            let x2: Rc<Weak<i32>> = Rc::new(y1);
            let y2: Weak<Weak<i32>> = Rc::downgrade(&x2);

            let x3: Rc<Weak<Weak<i32>>> = Rc::new(y2);
            let y3: Weak<Weak<Weak<i32>>> = Rc::downgrade(&x3);

            let z = y3
                .upgrade()
                .unwrap()
                .nest_upgrade()
                .unwrap()
                .nest_upgrade()
                .unwrap();
            assert_eq!(0, *z);
        }
    }
}

mod sync {
    use std::sync::*;

    use super::*;

    pub trait NestedArcWeak<'a, T>: Deref<Target = Weak<T>> + Sized + 'a {
        fn nest_upgrade(self) -> Option<Nested<T, Arc<T>, Self>> {
            let inner = Weak::upgrade(&self)?;
            Some(Nested { inner, outer: self })
        }
    }
    impl<'a, T, Outer: Deref<Target = Weak<T>> + Sized + 'a> NestedArcWeak<'a, T> for Outer {}

    pub trait NestedMutex<'a, T>: Deref<Target = Mutex<T>> + Sized + 'a {
        fn nest_lock(self) -> LockResult<Nested<T, MutexGuard<'a, T>, Self>> {
            let me = unsafe { remove_lifetime(&self) };
            match me.lock() {
                Ok(inner) => Ok(Nested { inner, outer: self }),
                Err(err) => {
                    let inner = err.into_inner();
                    Err(PoisonError::new(Nested { inner, outer: self }))
                }
            }
        }
        fn nest_try_lock(self) -> TryLockResult<Nested<T, MutexGuard<'a, T>, Self>> {
            let me = unsafe { remove_lifetime(&self) };
            match me.try_lock() {
                Ok(inner) => Ok(Nested { inner, outer: self }),
                Err(err) => match err {
                    TryLockError::Poisoned(err) => {
                        let inner = err.into_inner();
                        Err(TryLockError::Poisoned(PoisonError::new(Nested {
                            inner,
                            outer: self,
                        })))
                    }
                    TryLockError::WouldBlock => Err(TryLockError::WouldBlock),
                },
            }
        }
    }
    impl<'a, T, Outer: Deref<Target = Mutex<T>> + Sized + 'a> NestedMutex<'a, T> for Outer {}

    pub trait NestedRwLock<'a, T>: Deref<Target = RwLock<T>> + Sized + 'a {
        fn nest_try_read(self) -> TryLockResult<Nested<T, RwLockReadGuard<'a, T>, Self>> {
            let me = unsafe { remove_lifetime(&self) };
            match me.try_read() {
                Ok(inner) => Ok(Nested { inner, outer: self }),
                Err(err) => match err {
                    TryLockError::Poisoned(err) => {
                        let inner = err.into_inner();
                        Err(TryLockError::Poisoned(PoisonError::new(Nested {
                            inner,
                            outer: self,
                        })))
                    }
                    TryLockError::WouldBlock => Err(TryLockError::WouldBlock),
                },
            }
        }
        fn nest_try_write(self) -> TryLockResult<Nested<T, RwLockWriteGuard<'a, T>, Self>> {
            let me = unsafe { remove_lifetime(&self) };
            match me.try_write() {
                Ok(inner) => Ok(Nested { inner, outer: self }),
                Err(err) => match err {
                    TryLockError::Poisoned(err) => {
                        let inner = err.into_inner();
                        Err(TryLockError::Poisoned(PoisonError::new(Nested {
                            inner,
                            outer: self,
                        })))
                    }
                    TryLockError::WouldBlock => Err(TryLockError::WouldBlock),
                },
            }
        }
    }
    impl<'a, T, Outer: Deref<Target = RwLock<T>> + Sized + 'a> NestedRwLock<'a, T> for Outer {}

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

        #[test]
        fn test_many_arc() {
            let x1: Arc<i32> = Arc::new(0);
            let y1: Weak<i32> = Arc::downgrade(&x1);

            let x2: Arc<Weak<i32>> = Arc::new(y1);
            let y2: Weak<Weak<i32>> = Arc::downgrade(&x2);

            let x3: Arc<Weak<Weak<i32>>> = Arc::new(y2);
            let y3: Weak<Weak<Weak<i32>>> = Arc::downgrade(&x3);

            let z = y3
                .upgrade()
                .unwrap()
                .nest_upgrade()
                .unwrap()
                .nest_upgrade()
                .unwrap();
            assert_eq!(0, *z);
        }

        #[test]
        fn test_many_rwlock() {
            let x = RwLock::new(RwLock::new(RwLock::new(0)));
            {
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(0, *z);
            }
            {
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(0, *z);
            }
            {
                let mut z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_write()
                    .unwrap();
                *z = 1;
                assert_eq!(1, *z);
            }
            {
                {
                    let mut y = x.try_read().unwrap().nest_try_write().unwrap();
                    *y = RwLock::new(2);
                }
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(2, *z);
            }
        }
        #[test]
        fn test_many_mutex() {
            let x = RwLock::new(RwLock::new(RwLock::new(0)));
            {
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(0, *z);
            }
            {
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(0, *z);
            }
            {
                let mut z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_write()
                    .unwrap();
                *z = 1;
                assert_eq!(1, *z);
            }
            {
                {
                    let mut y = x.try_read().unwrap().nest_try_write().unwrap();
                    *y = RwLock::new(2);
                }
                let z = x
                    .try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap()
                    .nest_try_read()
                    .unwrap();
                assert_eq!(2, *z);
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::cell::*;
    use std::mem;
    use std::rc::*;

    use super::*;

    #[test]
    fn test_rc_refcell() {
        let x = Rc::new(RefCell::new(0));
        let x = Rc::downgrade(&x);
        assert_eq!(0, *x.upgrade().unwrap().borrow());
        {
            let z = x.upgrade().unwrap().nest_borrow();
            assert_eq!(0, *z);
        }
    }

    // #[test]
    // fn test_reassign_refcell_stack_does_not_compile() {
    //   let x = RefCell::new(RefCell::new(0));
    //   let ys: Vec<_> = (1..10).map(|i|
    // RefCell::new(RefCell::new(i))).collect();

    //   let mut ref1 = x.borrow();
    //   let mut ref2 = ref1.borrow_mut();

    //   for y in ys.iter() {
    //     let mut yref1 = y.borrow();
    //     let mut yref2 = yref1.borrow_mut();
    //     mem::swap(ref2.deref_mut(), yref2.deref_mut());
    //     ref2 = yref2;
    //     ref1 = yref1;
    //   }
    // }

    #[test]
    fn test_reassign_refcell_stack() {
        let x = RefCell::new(RefCell::new(0));
        let ys: Vec<_> = (1..10).map(|i| RefCell::new(RefCell::new(i))).collect();

        let mut ref1 = x.borrow().nest_borrow_mut();

        for y in ys.iter() {
            let mut yref = y.borrow().nest_borrow_mut();
            mem::swap(ref1.deref_mut(), yref.deref_mut());
            ref1 = yref;
        }
    }
}