owning_ref_lockable/
lib.rs

1#![warn(missing_docs)]
2
3/*!
4# An owning reference.
5
6This crate provides the _owning reference_ types `OwningRef` and `OwningRefMut`
7that enables it to bundle a reference together with the owner of the data it points to.
8This allows moving and dropping of a `OwningRef` without needing to recreate the reference.
9
10This can sometimes be useful because Rust borrowing rules normally prevent
11moving a type that has been moved from. For example, this kind of code gets rejected:
12
13```rust,ignore
14fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) {
15    let v = vec![1, 2, 3, 4];
16    let s = &v[1..3];
17    (v, s)
18}
19```
20
21Even though, from a memory-layout point of view, this can be entirely safe
22if the new location of the vector still lives longer than the lifetime `'a`
23of the reference because the backing allocation of the vector does not change.
24
25This library enables this safe usage by keeping the owner and the reference
26bundled together in a wrapper type that ensure that lifetime constraint:
27
28```rust
29# extern crate owning_ref;
30# use owning_ref::OwningRef;
31# fn main() {
32fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> {
33    let v = vec![1, 2, 3, 4];
34    let or = OwningRef::new(v);
35    let or = or.map(|v| &v[1..3]);
36    or
37}
38# }
39```
40
41It works by requiring owner types to dereference to stable memory locations
42and preventing mutable access to root containers, which in practice requires heap allocation
43as provided by `Box<T>`, `Rc<T>`, etc.
44
45Also provided are typedefs for common owner type combinations,
46which allow for less verbose type signatures. For example, `BoxRef<T>` instead of `OwningRef<Box<T>, T>`.
47
48The crate also provides the more advanced `OwningHandle` type,
49which allows more freedom in bundling a dependent handle object
50along with the data it depends on, at the cost of some unsafe needed in the API.
51See the documentation around `OwningHandle` for more details.
52
53# Examples
54
55## Basics
56
57```
58extern crate owning_ref;
59use owning_ref::BoxRef;
60
61fn main() {
62    // Create an array owned by a Box.
63    let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;
64
65    // Transfer into a BoxRef.
66    let arr: BoxRef<[i32]> = BoxRef::new(arr);
67    assert_eq!(&*arr, &[1, 2, 3, 4]);
68
69    // We can slice the array without losing ownership or changing type.
70    let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]);
71    assert_eq!(&*arr, &[2, 3]);
72
73    // Also works for Arc, Rc, String and Vec!
74}
75```
76
77## Caching a reference to a struct field
78
79```
80extern crate owning_ref;
81use owning_ref::BoxRef;
82
83fn main() {
84    struct Foo {
85        tag: u32,
86        x: u16,
87        y: u16,
88        z: u16,
89    }
90    let foo = Foo { tag: 1, x: 100, y: 200, z: 300 };
91
92    let or = BoxRef::new(Box::new(foo)).map(|foo| {
93        match foo.tag {
94            0 => &foo.x,
95            1 => &foo.y,
96            2 => &foo.z,
97            _ => panic!(),
98        }
99    });
100
101    assert_eq!(*or, 200);
102}
103```
104
105## Caching a reference to an entry in a vector
106
107```
108extern crate owning_ref;
109use owning_ref::VecRef;
110
111fn main() {
112    let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]);
113    assert_eq!(*v, 4);
114}
115```
116
117## Caching a subslice of a String
118
119```
120extern crate owning_ref;
121use owning_ref::StringRef;
122
123fn main() {
124    let s = StringRef::new("hello world".to_owned())
125        .map(|s| s.split(' ').nth(1).unwrap());
126
127    assert_eq!(&*s, "world");
128}
129```
130
131## Reference counted slices that share ownership of the backing storage
132
133```
134extern crate owning_ref;
135use owning_ref::RcRef;
136use std::rc::Rc;
137
138fn main() {
139    let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>);
140    assert_eq!(&*rc, &[1, 2, 3, 4]);
141
142    let rc_a: RcRef<[i32]> = rc.clone().map(|s| &s[0..2]);
143    let rc_b = rc.clone().map(|s| &s[1..3]);
144    let rc_c = rc.clone().map(|s| &s[2..4]);
145    assert_eq!(&*rc_a, &[1, 2]);
146    assert_eq!(&*rc_b, &[2, 3]);
147    assert_eq!(&*rc_c, &[3, 4]);
148
149    let rc_c_a = rc_c.clone().map(|s| &s[1]);
150    assert_eq!(&*rc_c_a, &4);
151}
152```
153
154## Atomic reference counted slices that share ownership of the backing storage
155
156```
157extern crate owning_ref;
158use owning_ref::ArcRef;
159use std::sync::Arc;
160
161fn main() {
162    use std::thread;
163
164    fn par_sum(rc: ArcRef<[i32]>) -> i32 {
165        if rc.len() == 0 {
166            return 0;
167        } else if rc.len() == 1 {
168            return rc[0];
169        }
170        let mid = rc.len() / 2;
171        let left = rc.clone().map(|s| &s[..mid]);
172        let right = rc.map(|s| &s[mid..]);
173
174        let left = thread::spawn(move || par_sum(left));
175        let right = thread::spawn(move || par_sum(right));
176
177        left.join().unwrap() + right.join().unwrap()
178    }
179
180    let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]);
181    let rc: ArcRef<[i32]> = rc.into();
182
183    assert_eq!(par_sum(rc), 10);
184}
185```
186
187## References into RAII locks
188
189```
190extern crate owning_ref;
191use owning_ref::RefRef;
192use std::cell::{RefCell, Ref};
193
194fn main() {
195    let refcell = RefCell::new((1, 2, 3, 4));
196    // Also works with Mutex and RwLock
197
198    let refref = {
199        let refref = RefRef::new(refcell.borrow()).map(|x| &x.3);
200        assert_eq!(*refref, 4);
201
202        // We move the RAII lock and the reference to one of
203        // the subfields in the data it guards here:
204        refref
205    };
206
207    assert_eq!(*refref, 4);
208
209    drop(refref);
210
211    assert_eq!(*refcell.borrow(), (1, 2, 3, 4));
212}
213```
214
215## Mutable reference
216
217When the owned container implements `DerefMut`, it is also possible to make
218a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`)
219
220```
221extern crate owning_ref;
222use owning_ref::RefMutRefMut;
223use std::cell::{RefCell, RefMut};
224
225fn main() {
226    let refcell = RefCell::new((1, 2, 3, 4));
227
228    let mut refmut_refmut = {
229        let mut refmut_refmut = RefMutRefMut::new(refcell.borrow_mut()).map_mut(|x| &mut x.3);
230        assert_eq!(*refmut_refmut, 4);
231        *refmut_refmut *= 2;
232
233        refmut_refmut
234    };
235
236    assert_eq!(*refmut_refmut, 8);
237    *refmut_refmut *= 2;
238
239    drop(refmut_refmut);
240
241    assert_eq!(*refcell.borrow(), (1, 2, 3, 16));
242}
243```
244*/
245
246extern crate stable_deref_trait;
247pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
248
249/// An owning reference.
250///
251/// This wraps an owner `O` and a reference `&T` pointing
252/// at something reachable from `O::Target` while keeping
253/// the ability to move `self` around.
254///
255/// The owner is usually a pointer that points at some base type.
256///
257/// For more details and examples, see the module and method docs.
258pub struct OwningRef<O, T: ?Sized> {
259    owner: O,
260    reference: *const T,
261}
262
263/// An mutable owning reference.
264///
265/// This wraps an owner `O` and a reference `&mut T` pointing
266/// at something reachable from `O::Target` while keeping
267/// the ability to move `self` around.
268///
269/// The owner is usually a pointer that points at some base type.
270///
271/// For more details and examples, see the module and method docs.
272pub struct OwningRefMut<O, T: ?Sized> {
273    owner: O,
274    reference: *mut T,
275}
276
277/// Helper trait for an erased concrete type an owner dereferences to.
278/// This is used in form of a trait object for keeping
279/// something around to (virtually) call the destructor.
280pub trait Erased {}
281impl<T> Erased for T {}
282
283/// Helper trait for erasing the concrete type of what an owner derferences to,
284/// for example `Box<T> -> Box<dyn Erased>`. This would be unneeded with
285/// higher kinded types support in the language.
286pub unsafe trait IntoErased<'a> {
287    /// Owner with the dereference type substituted to `Erased`.
288    type Erased;
289    /// Perform the type erasure.
290    fn into_erased(self) -> Self::Erased;
291}
292
293/////////////////////////////////////////////////////////////////////////////
294// OwningRef
295/////////////////////////////////////////////////////////////////////////////
296
297impl<O, T: ?Sized> OwningRef<O, T> {
298    /// Creates a new owning reference from a owner
299    /// initialized to the direct dereference of it.
300    ///
301    /// # Example
302    /// ```
303    /// extern crate owning_ref;
304    /// use owning_ref::OwningRef;
305    ///
306    /// fn main() {
307    ///     let owning_ref = OwningRef::new(Box::new(42));
308    ///     assert_eq!(*owning_ref, 42);
309    /// }
310    /// ```
311    pub fn new(o: O) -> Self
312        where O: StableAddress,
313              O: Deref<Target = T>,
314    {
315        OwningRef {
316            reference: &*o,
317            owner: o,
318        }
319    }
320
321    /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
322    /// Instead, the caller is responsible to make the same promises as implementing the trait.
323    ///
324    /// This is useful for cases where coherence rules prevents implementing the trait
325    /// without adding a dependency to this crate in a third-party library.
326    pub unsafe fn new_assert_stable_address(o: O) -> Self
327        where O: Deref<Target = T>,
328    {
329        OwningRef {
330            reference: &*o,
331            owner: o,
332        }
333    }
334
335    /// Converts `self` into a new owning reference that points at something reachable
336    /// from the previous one.
337    ///
338    /// This can be a reference to a field of `U`, something reachable from a field of
339    /// `U`, or even something unrelated with a `'static` lifetime.
340    ///
341    /// # Example
342    /// ```
343    /// extern crate owning_ref;
344    /// use owning_ref::OwningRef;
345    ///
346    /// fn main() {
347    ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
348    ///
349    ///     // create a owning reference that points at the
350    ///     // third element of the array.
351    ///     let owning_ref = owning_ref.map(|array| &array[2]);
352    ///     assert_eq!(*owning_ref, 3);
353    /// }
354    /// ```
355    pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
356        where O: StableAddress,
357              F: FnOnce(&T) -> &U
358    {
359        OwningRef {
360            reference: f(&self),
361            owner: self.owner,
362        }
363    }
364
365    /// Converts `self` into a new owning reference that points at something reachable
366    /// from the previous one or from the owner itself.
367    ///
368    /// This can be a reference to a field of `U`, something reachable from a field of
369    /// `U` or from the owner `O`, or even something unrelated with a `'static` lifetime.
370    ///
371    /// # Example
372    /// ```
373    /// extern crate owning_ref;
374    /// use owning_ref::OwningRef;
375    ///
376    /// fn main() {
377    ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
378    ///     let owning_ref = owning_ref.map(|array| &array[2]);
379    ///     assert_eq!(*owning_ref, 3);
380    ///
381    ///     // create a owning reference that points at the
382    ///     // second element of the array from the owning ref that was pointing to the third
383    ///     let owning_ref = owning_ref.map_with_owner(|array, _prev| &array[1]);
384    ///     assert_eq!(*owning_ref, 2);
385    /// }
386    /// ```
387    pub fn map_with_owner<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
388        where O: StableAddress,
389              F: for<'a> FnOnce(&'a O, &'a T) -> &'a U
390    {
391        OwningRef {
392            reference: f(&self.owner, &self),
393            owner: self.owner,
394        }
395    }
396
397    /// Tries to convert `self` into a new owning reference that points
398    /// at something reachable from the previous one.
399    ///
400    /// This can be a reference to a field of `U`, something reachable from a field of
401    /// `U`, or even something unrelated with a `'static` lifetime.
402    ///
403    /// # Example
404    /// ```
405    /// extern crate owning_ref;
406    /// use owning_ref::OwningRef;
407    ///
408    /// fn main() {
409    ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
410    ///
411    ///     // create a owning reference that points at the
412    ///     // third element of the array.
413    ///     let owning_ref = owning_ref.try_map(|array| {
414    ///         if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
415    ///     });
416    ///     assert_eq!(*owning_ref.unwrap(), 3);
417    /// }
418    /// ```
419    pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
420        where O: StableAddress,
421              F: FnOnce(&T) -> Result<&U, E>
422    {
423        Ok(OwningRef {
424            reference: f(&self)?,
425            owner: self.owner,
426        })
427    }
428
429    /// Tries to convert `self` into a new owning reference that points
430    /// at something reachable from the previous one.
431    ///
432    /// This can be a reference to a field of `U`, something reachable from a field of
433    /// `U`, or even something unrelated with a `'static` lifetime.
434    ///
435    /// # Example
436    /// ```
437    /// extern crate owning_ref;
438    /// use owning_ref::OwningRef;
439    ///
440    /// fn main() {
441    ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
442    ///     let owning_ref = owning_ref.map(|array| &array[2]);
443    ///
444    ///     // create a owning reference that points at the
445    ///     // second element of the array from the owning ref that was pointing to the third
446    ///     let owning_ref = owning_ref.try_map_with_owner(|array, _prev| {
447    ///         if array[1] == 2 { Ok(&array[1]) } else { Err(()) }
448    ///     });
449    ///     assert_eq!(*owning_ref.unwrap(), 2);
450    /// }
451    /// ```
452    pub fn try_map_with_owner<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
453        where O: StableAddress,
454              F: for<'a> FnOnce(&'a O, &'a T) -> Result<&'a U, E>
455    {
456        Ok(OwningRef {
457            reference: f(&self.owner, &self)?,
458            owner: self.owner,
459        })
460    }
461
462    /// Converts `self` into a new owning reference with a different owner type.
463    ///
464    /// The new owner type needs to still contain the original owner in some way
465    /// so that the reference into it remains valid. This function is marked unsafe
466    /// because the user needs to manually uphold this guarantee.
467    pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<P, T>
468        where O: StableAddress,
469              P: StableAddress,
470              F: FnOnce(O) -> P
471    {
472        OwningRef {
473            reference: self.reference,
474            owner: f(self.owner),
475        }
476    }
477
478    /// Converts `self` into a new owning reference where the owner is wrapped
479    /// in an additional `Box<O>`.
480    ///
481    /// This can be used to safely erase the owner of any `OwningRef<O, T>`
482    /// to a `OwningRef<Box<dyn Erased>, T>`.
483    pub fn map_owner_box(self) -> OwningRef<Box<O>, T> {
484        OwningRef {
485            reference: self.reference,
486            owner: Box::new(self.owner),
487        }
488    }
489
490    /// Erases the concrete base type of the owner with a trait object.
491    ///
492    /// This allows mixing of owned references with different owner base types.
493    ///
494    /// # Example
495    /// ```
496    /// extern crate owning_ref;
497    /// use owning_ref::{OwningRef, Erased};
498    ///
499    /// fn main() {
500    ///     // NB: Using the concrete types here for explicitnes.
501    ///     // For less verbose code type aliases like `BoxRef` are provided.
502    ///
503    ///     let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]>
504    ///         = OwningRef::new(Box::new([1, 2, 3, 4]));
505    ///
506    ///     let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
507    ///         = OwningRef::new(Box::new(vec![(0, false), (1, true)]));
508    ///
509    ///     let owning_ref_a: OwningRef<Box<[i32; 4]>, i32>
510    ///         = owning_ref_a.map(|a| &a[0]);
511    ///
512    ///     let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, i32>
513    ///         = owning_ref_b.map(|a| &a[1].0);
514    ///
515    ///     let owning_refs: [OwningRef<Box<dyn Erased>, i32>; 2]
516    ///         = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()];
517    ///
518    ///     assert_eq!(*owning_refs[0], 1);
519    ///     assert_eq!(*owning_refs[1], 1);
520    /// }
521    /// ```
522    pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T>
523        where O: IntoErased<'a>,
524    {
525        OwningRef {
526            reference: self.reference,
527            owner: self.owner.into_erased(),
528        }
529    }
530
531    // TODO: wrap_owner
532
533    /// A reference to the underlying owner.
534    pub fn as_owner(&self) -> &O {
535        &self.owner
536    }
537
538    /// Discards the reference and retrieves the owner.
539    pub fn into_owner(self) -> O {
540        self.owner
541    }
542}
543
544impl<O, T: ?Sized> OwningRefMut<O, T> {
545    /// Creates a new owning reference from a owner
546    /// initialized to the direct dereference of it.
547    ///
548    /// # Example
549    /// ```
550    /// extern crate owning_ref;
551    /// use owning_ref::OwningRefMut;
552    ///
553    /// fn main() {
554    ///     let owning_ref_mut = OwningRefMut::new(Box::new(42));
555    ///     assert_eq!(*owning_ref_mut, 42);
556    /// }
557    /// ```
558    pub fn new(mut o: O) -> Self
559        where O: StableAddress,
560              O: DerefMut<Target = T>,
561    {
562        OwningRefMut {
563            reference: &mut *o,
564            owner: o,
565        }
566    }
567
568    /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
569    /// Instead, the caller is responsible to make the same promises as implementing the trait.
570    ///
571    /// This is useful for cases where coherence rules prevents implementing the trait
572    /// without adding a dependency to this crate in a third-party library.
573    pub unsafe fn new_assert_stable_address(mut o: O) -> Self
574        where O: DerefMut<Target = T>,
575    {
576        OwningRefMut {
577            reference: &mut *o,
578            owner: o,
579        }
580    }
581
582    /// Converts `self` into a new _shared_ owning reference that points at
583    /// something reachable from the previous one.
584    ///
585    /// This can be a reference to a field of `U`, something reachable from a field of
586    /// `U`, or even something unrelated with a `'static` lifetime.
587    ///
588    /// # Example
589    /// ```
590    /// extern crate owning_ref;
591    /// use owning_ref::OwningRefMut;
592    ///
593    /// fn main() {
594    ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
595    ///
596    ///     // create a owning reference that points at the
597    ///     // third element of the array.
598    ///     let owning_ref = owning_ref_mut.map(|array| &array[2]);
599    ///     assert_eq!(*owning_ref, 3);
600    /// }
601    /// ```
602    pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U>
603        where O: StableAddress,
604              F: FnOnce(&mut T) -> &U
605    {
606        OwningRef {
607            reference: f(&mut self),
608            owner: self.owner,
609        }
610    }
611
612    /// Converts `self` into a new _mutable_ owning reference that points at
613    /// something reachable from the previous one.
614    ///
615    /// This can be a reference to a field of `U`, something reachable from a field of
616    /// `U`, or even something unrelated with a `'static` lifetime.
617    ///
618    /// # Example
619    /// ```
620    /// extern crate owning_ref;
621    /// use owning_ref::OwningRefMut;
622    ///
623    /// fn main() {
624    ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
625    ///
626    ///     // create a owning reference that points at the
627    ///     // third element of the array.
628    ///     let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]);
629    ///     assert_eq!(*owning_ref_mut, 3);
630    /// }
631    /// ```
632    pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U>
633        where O: StableAddress,
634              F: FnOnce(&mut T) -> &mut U
635    {
636        OwningRefMut {
637            reference: f(&mut self),
638            owner: self.owner,
639        }
640    }
641
642    /// Tries to convert `self` into a new _shared_ owning reference that points
643    /// at something reachable from the previous one.
644    ///
645    /// This can be a reference to a field of `U`, something reachable from a field of
646    /// `U`, or even something unrelated with a `'static` lifetime.
647    ///
648    /// # Example
649    /// ```
650    /// extern crate owning_ref;
651    /// use owning_ref::OwningRefMut;
652    ///
653    /// fn main() {
654    ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
655    ///
656    ///     // create a owning reference that points at the
657    ///     // third element of the array.
658    ///     let owning_ref = owning_ref_mut.try_map(|array| {
659    ///         if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
660    ///     });
661    ///     assert_eq!(*owning_ref.unwrap(), 3);
662    /// }
663    /// ```
664    pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E>
665        where O: StableAddress,
666              F: FnOnce(&mut T) -> Result<&U, E>
667    {
668        Ok(OwningRef {
669            reference: f(&mut self)?,
670            owner: self.owner,
671        })
672    }
673
674    /// Tries to convert `self` into a new _mutable_ owning reference that points
675    /// at something reachable from the previous one.
676    ///
677    /// This can be a reference to a field of `U`, something reachable from a field of
678    /// `U`, or even something unrelated with a `'static` lifetime.
679    ///
680    /// # Example
681    /// ```
682    /// extern crate owning_ref;
683    /// use owning_ref::OwningRefMut;
684    ///
685    /// fn main() {
686    ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
687    ///
688    ///     // create a owning reference that points at the
689    ///     // third element of the array.
690    ///     let owning_ref_mut = owning_ref_mut.try_map_mut(|array| {
691    ///         if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) }
692    ///     });
693    ///     assert_eq!(*owning_ref_mut.unwrap(), 3);
694    /// }
695    /// ```
696    pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E>
697        where O: StableAddress,
698              F: FnOnce(&mut T) -> Result<&mut U, E>
699    {
700        Ok(OwningRefMut {
701            reference: f(&mut self)?,
702            owner: self.owner,
703        })
704    }
705
706    /// Converts `self` into a new owning reference with a different owner type.
707    ///
708    /// The new owner type needs to still contain the original owner in some way
709    /// so that the reference into it remains valid. This function is marked unsafe
710    /// because the user needs to manually uphold this guarantee.
711    pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T>
712        where O: StableAddress,
713              P: StableAddress,
714              F: FnOnce(O) -> P
715    {
716        OwningRefMut {
717            reference: self.reference,
718            owner: f(self.owner),
719        }
720    }
721
722    /// Converts `self` into a new owning reference where the owner is wrapped
723    /// in an additional `Box<O>`.
724    ///
725    /// This can be used to safely erase the owner of any `OwningRefMut<O, T>`
726    /// to a `OwningRefMut<Box<dyn Erased>, T>`.
727    pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> {
728        OwningRefMut {
729            reference: self.reference,
730            owner: Box::new(self.owner),
731        }
732    }
733
734    /// Erases the concrete base type of the owner with a trait object.
735    ///
736    /// This allows mixing of owned references with different owner base types.
737    ///
738    /// # Example
739    /// ```
740    /// extern crate owning_ref;
741    /// use owning_ref::{OwningRefMut, Erased};
742    ///
743    /// fn main() {
744    ///     // NB: Using the concrete types here for explicitnes.
745    ///     // For less verbose code type aliases like `BoxRef` are provided.
746    ///
747    ///     let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]>
748    ///         = OwningRefMut::new(Box::new([1, 2, 3, 4]));
749    ///
750    ///     let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
751    ///         = OwningRefMut::new(Box::new(vec![(0, false), (1, true)]));
752    ///
753    ///     let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32>
754    ///         = owning_ref_mut_a.map_mut(|a| &mut a[0]);
755    ///
756    ///     let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32>
757    ///         = owning_ref_mut_b.map_mut(|a| &mut a[1].0);
758    ///
759    ///     let owning_refs_mut: [OwningRefMut<Box<dyn Erased>, i32>; 2]
760    ///         = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()];
761    ///
762    ///     assert_eq!(*owning_refs_mut[0], 1);
763    ///     assert_eq!(*owning_refs_mut[1], 1);
764    /// }
765    /// ```
766    pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T>
767        where O: IntoErased<'a>,
768    {
769        OwningRefMut {
770            reference: self.reference,
771            owner: self.owner.into_erased(),
772        }
773    }
774
775    // TODO: wrap_owner
776
777    /// A reference to the underlying owner.
778    pub fn as_owner(&self) -> &O {
779        &self.owner
780    }
781
782    /// A mutable reference to the underlying owner.
783    pub fn as_owner_mut(&mut self) -> &mut O {
784        &mut self.owner
785    }
786
787    /// Discards the reference and retrieves the owner.
788    pub fn into_owner(self) -> O {
789        self.owner
790    }
791}
792
793/////////////////////////////////////////////////////////////////////////////
794// OwningHandle
795/////////////////////////////////////////////////////////////////////////////
796
797use std::ops::{Deref, DerefMut};
798use std::future::Future;
799
800/// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows
801/// consumers to pass around an owned object and a dependent reference,
802/// `OwningHandle` contains an owned object and a dependent _object_.
803///
804/// `OwningHandle` can encapsulate a `RefMut` along with its associated
805/// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`.
806/// However, the API is completely generic and there are no restrictions on
807/// what types of owning and dependent objects may be used.
808///
809/// `OwningHandle` is created by passing an owner object (which dereferences
810/// to a stable address) along with a callback which receives a pointer to
811/// that stable location. The callback may then dereference the pointer and
812/// mint a dependent object, with the guarantee that the returned object will
813/// not outlive the referent of the pointer.
814///
815/// Since the callback needs to dereference a raw pointer, it requires `unsafe`
816/// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is
817/// implemented for common data structures. Types that implement `ToHandle` can
818/// be wrapped into an `OwningHandle` without passing a callback.
819pub struct OwningHandle<O, H>
820    where O: StableAddress, H: Deref,
821{
822    handle: H,
823    _owner: O,
824}
825
826impl<O, H> Deref for OwningHandle<O, H>
827    where O: StableAddress, H: Deref,
828{
829    type Target = H::Target;
830    fn deref(&self) -> &H::Target {
831        self.handle.deref()
832    }
833}
834
835unsafe impl<O, H> StableAddress for OwningHandle<O, H>
836    where O: StableAddress, H: StableAddress,
837{}
838
839impl<O, H> DerefMut for OwningHandle<O, H>
840    where O: StableAddress, H: DerefMut,
841{
842    fn deref_mut(&mut self) -> &mut H::Target {
843        self.handle.deref_mut()
844    }
845}
846
847/// Trait to implement the conversion of owner to handle for common types.
848pub trait ToHandle {
849    /// The type of handle to be encapsulated by the OwningHandle.
850    type Handle: Deref;
851
852    /// Given an appropriately-long-lived pointer to ourselves, create a
853    /// handle to be encapsulated by the `OwningHandle`.
854    unsafe fn to_handle(x: *const Self) -> Self::Handle;
855}
856
857/// Trait to implement the conversion of owner to mutable handle for common types.
858pub trait ToHandleMut {
859    /// The type of handle to be encapsulated by the OwningHandle.
860    type HandleMut: DerefMut;
861
862    /// Given an appropriately-long-lived pointer to ourselves, create a
863    /// mutable handle to be encapsulated by the `OwningHandle`.
864    unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut;
865}
866
867impl<O, H> OwningHandle<O, H>
868    where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref,
869{
870    /// Create a new `OwningHandle` for a type that implements `ToHandle`. For types
871    /// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts
872    /// a callback to perform the conversion.
873    pub fn new(o: O) -> Self {
874        OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) })
875    }
876}
877
878impl<O, H> OwningHandle<O, H>
879    where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
880{
881    /// Create a new mutable `OwningHandle` for a type that implements `ToHandleMut`.
882    pub fn new_mut(o: O) -> Self {
883        OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) })
884    }
885}
886
887impl<O, H> OwningHandle<O, H>
888    where O: StableAddress, H: Deref,
889{
890    /// Create a new OwningHandle. The provided callback will be invoked with
891    /// a pointer to the object owned by `o`, and the returned value is stored
892    /// as the object to which this `OwningHandle` will forward `Deref` and
893    /// `DerefMut`.
894    pub fn new_with_fn<F>(o: O, f: F) -> Self
895        where F: FnOnce(*const O::Target) -> H
896    {
897        let h: H;
898        {
899            h = f(o.deref() as *const O::Target);
900        }
901
902        OwningHandle {
903          handle: h,
904          _owner: o,
905        }
906    }
907
908    /// Create a new OwningHandle. The provided callback will be invoked with
909    /// a pointer to the object owned by `o`, and the returned value is stored
910    /// as the object to which this `OwningHandle` will forward `Deref` and
911    /// `DerefMut`.
912    pub async fn new_with_async_fn<F, T>(o: O, f: F) -> Self
913        where
914            F: FnOnce(*const O::Target) -> T,
915            T: Future<Output = H>,
916    {
917        let h: H;
918        {
919            let r = f(o.deref() as *const O::Target);
920            h = r.await;
921        }
922
923        OwningHandle {
924          handle: h,
925          _owner: o,
926        }
927    }
928
929    /// Create a new OwningHandle. The provided callback will be invoked with
930    /// a pointer to the object owned by `o`, and the returned value is stored
931    /// as the object to which this `OwningHandle` will forward `Deref` and
932    /// `DerefMut`.
933    pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
934        where F: FnOnce(*const O::Target) -> Result<H, E>
935    {
936        let h: H;
937        {
938            h = f(o.deref() as *const O::Target)?;
939        }
940
941        Ok(OwningHandle {
942          handle: h,
943          _owner: o,
944        })
945    }
946
947    /// Create a new OwningHandle. The provided callback will be invoked with
948    /// a pointer to the object owned by `o`, and the returned value is stored
949    /// as the object to which this `OwningHandle` will forward `Deref` and
950    /// `DerefMut`.
951    pub async fn try_new_async<F, E, T>(o: O, f: F) -> Result<Self, E>
952        where
953            F: FnOnce(*const O::Target) -> T,
954            T: Future<Output = Result<H, E>>,
955    {
956        let h: H;
957        {
958            let r = f(o.deref() as *const O::Target);
959            h = r.await?;
960        }
961
962        Ok(OwningHandle {
963          handle: h,
964          _owner: o,
965        })
966    }
967
968    /// Converts `self` into a new owning handle based on a function
969    /// that converts the existing handle into a new one.
970    ///
971    /// This can be used to convert a RAII guard, for example.
972    pub fn map<F, N: Deref>(self, f: F) -> OwningHandle<O, N>
973        where F: FnOnce(H) -> N
974    {
975        OwningHandle {
976          handle: f(self.handle),
977          _owner: self._owner,
978        }
979    }
980
981    /// A getter for the underlying owner.
982    pub fn as_owner(&self) -> &O {
983        &self._owner
984    }
985
986    /// Discards the dependent object and returns the owner.
987    pub fn into_owner(self) -> O {
988        self._owner
989    }
990}
991
992/////////////////////////////////////////////////////////////////////////////
993// std traits
994/////////////////////////////////////////////////////////////////////////////
995
996use std::convert::From;
997use std::fmt::{self, Debug};
998use std::marker::{Send, Sync};
999use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
1000use std::hash::{Hash, Hasher};
1001use std::borrow::Borrow;
1002
1003impl<O, T: ?Sized> Deref for OwningRef<O, T> {
1004    type Target = T;
1005
1006    fn deref(&self) -> &T {
1007        unsafe {
1008            &*self.reference
1009        }
1010    }
1011}
1012
1013impl<O, T: ?Sized> Deref for OwningRefMut<O, T> {
1014    type Target = T;
1015
1016    fn deref(&self) -> &T {
1017        unsafe {
1018            &*self.reference
1019        }
1020    }
1021}
1022
1023impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> {
1024    fn deref_mut(&mut self) -> &mut T {
1025        unsafe {
1026            &mut *self.reference
1027        }
1028    }
1029}
1030
1031unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {}
1032
1033unsafe impl<O, T: ?Sized> StableAddress for OwningRefMut<O, T> {}
1034
1035impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> {
1036    fn as_ref(&self) -> &T {
1037        &*self
1038    }
1039}
1040
1041impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> {
1042    fn as_ref(&self) -> &T {
1043        &*self
1044    }
1045}
1046
1047impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> {
1048    fn as_mut(&mut self) -> &mut T {
1049        &mut *self
1050    }
1051}
1052
1053impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> {
1054    fn borrow(&self) -> &T {
1055        &*self
1056    }
1057}
1058
1059impl<O, T: ?Sized> From<O> for OwningRef<O, T>
1060    where O: StableAddress,
1061          O: Deref<Target = T>,
1062{
1063    fn from(owner: O) -> Self {
1064        OwningRef::new(owner)
1065    }
1066}
1067
1068impl<O, T: ?Sized> From<O> for OwningRefMut<O, T>
1069    where O: StableAddress,
1070          O: DerefMut<Target = T>
1071{
1072    fn from(owner: O) -> Self {
1073        OwningRefMut::new(owner)
1074    }
1075}
1076
1077impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T>
1078    where O: StableAddress,
1079          O: DerefMut<Target = T>
1080{
1081    fn from(other: OwningRefMut<O, T>) -> Self {
1082        OwningRef {
1083            owner: other.owner,
1084            reference: other.reference,
1085        }
1086    }
1087}
1088
1089// ^ FIXME: Is a Into impl for calling into_owner() possible as well?
1090
1091impl<O, T: ?Sized> Debug for OwningRef<O, T>
1092    where O: Debug,
1093          T: Debug,
1094{
1095    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1096        write!(f,
1097               "OwningRef {{ owner: {:?}, reference: {:?} }}",
1098               self.as_owner(),
1099               &**self)
1100    }
1101}
1102
1103impl<O, T: ?Sized> Debug for OwningRefMut<O, T>
1104    where O: Debug,
1105          T: Debug,
1106{
1107    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1108        write!(f,
1109               "OwningRefMut {{ owner: {:?}, reference: {:?} }}",
1110               self.as_owner(),
1111               &**self)
1112    }
1113}
1114
1115impl<O, T: ?Sized> Clone for OwningRef<O, T>
1116    where O: CloneStableAddress,
1117{
1118    fn clone(&self) -> Self {
1119        OwningRef {
1120            owner: self.owner.clone(),
1121            reference: self.reference,
1122        }
1123    }
1124}
1125
1126unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
1127    where O: CloneStableAddress {}
1128
1129unsafe impl<O, T: ?Sized> Send for OwningRef<O, T>
1130    where O: Send, for<'a> (&'a T): Send {}
1131unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T>
1132    where O: Sync, for<'a> (&'a T): Sync {}
1133
1134unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T>
1135    where O: Send, for<'a> (&'a mut T): Send {}
1136unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T>
1137    where O: Sync, for<'a> (&'a mut T): Sync {}
1138
1139impl Debug for dyn Erased {
1140    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1141        write!(f, "<dyn Erased>",)
1142    }
1143}
1144
1145impl<O, T: ?Sized> PartialEq for OwningRef<O, T> where T: PartialEq {
1146    fn eq(&self, other: &Self) -> bool {
1147        (&*self as &T).eq(&*other as &T)
1148     }
1149}
1150
1151impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {}
1152
1153impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> where T: PartialOrd {
1154    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1155        (&*self as &T).partial_cmp(&*other as &T)
1156    }
1157}
1158
1159impl<O, T: ?Sized> Ord for OwningRef<O, T> where T: Ord {
1160    fn cmp(&self, other: &Self) -> Ordering {
1161        (&*self as &T).cmp(&*other as &T)
1162    }
1163}
1164
1165impl<O, T: ?Sized> Hash for OwningRef<O, T> where T: Hash {
1166    fn hash<H: Hasher>(&self, state: &mut H) {
1167        (&*self as &T).hash(state);
1168    }
1169}
1170
1171impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> where T: PartialEq {
1172    fn eq(&self, other: &Self) -> bool {
1173        (&*self as &T).eq(&*other as &T)
1174     }
1175}
1176
1177impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {}
1178
1179impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> where T: PartialOrd {
1180    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1181        (&*self as &T).partial_cmp(&*other as &T)
1182    }
1183}
1184
1185impl<O, T: ?Sized> Ord for OwningRefMut<O, T> where T: Ord {
1186    fn cmp(&self, other: &Self) -> Ordering {
1187        (&*self as &T).cmp(&*other as &T)
1188    }
1189}
1190
1191impl<O, T: ?Sized> Hash for OwningRefMut<O, T> where T: Hash {
1192    fn hash<H: Hasher>(&self, state: &mut H) {
1193        (&*self as &T).hash(state);
1194    }
1195}
1196
1197/////////////////////////////////////////////////////////////////////////////
1198// std types integration and convenience type defs
1199/////////////////////////////////////////////////////////////////////////////
1200
1201use std::boxed::Box;
1202use std::rc::Rc;
1203use std::sync::Arc;
1204use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
1205use std::cell::{Ref, RefCell, RefMut};
1206
1207impl<T: 'static> ToHandle for RefCell<T> {
1208    type Handle = Ref<'static, T>;
1209    unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() }
1210}
1211
1212impl<T: 'static> ToHandleMut for RefCell<T> {
1213    type HandleMut = RefMut<'static, T>;
1214    unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
1215}
1216
1217// NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision
1218// about which handle creation to use (i.e. read() vs try_read()) as well as
1219// what to do with error results.
1220
1221/// Typedef of a owning reference that uses a `Box` as the owner.
1222pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>;
1223/// Typedef of a owning reference that uses a `Vec` as the owner.
1224pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>;
1225/// Typedef of a owning reference that uses a `String` as the owner.
1226pub type StringRef = OwningRef<String, str>;
1227
1228/// Typedef of a owning reference that uses a `Rc` as the owner.
1229pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>;
1230/// Typedef of a owning reference that uses a `Arc` as the owner.
1231pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>;
1232
1233/// Typedef of a owning reference that uses a `Ref` as the owner.
1234pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>;
1235/// Typedef of a owning reference that uses a `RefMut` as the owner.
1236pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>;
1237/// Typedef of a owning reference that uses a `MutexGuard` as the owner.
1238pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>;
1239/// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner.
1240pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>;
1241/// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner.
1242pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
1243
1244/// Typedef of a mutable owning reference that uses a `Box` as the owner.
1245pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>;
1246/// Typedef of a mutable owning reference that uses a `Vec` as the owner.
1247pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>;
1248/// Typedef of a mutable owning reference that uses a `String` as the owner.
1249pub type StringRefMut = OwningRefMut<String, str>;
1250
1251/// Typedef of a mutable owning reference that uses a `RefMut` as the owner.
1252pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>;
1253/// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner.
1254pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>;
1255/// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner.
1256pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRefMut<RwLockWriteGuard<'a, T>, U>;
1257
1258unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> {
1259    type Erased = Box<dyn Erased + 'a>;
1260    fn into_erased(self) -> Self::Erased {
1261        self
1262    }
1263}
1264unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> {
1265    type Erased = Rc<dyn Erased + 'a>;
1266    fn into_erased(self) -> Self::Erased {
1267        self
1268    }
1269}
1270unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> {
1271    type Erased = Arc<dyn Erased + 'a>;
1272    fn into_erased(self) -> Self::Erased {
1273        self
1274    }
1275}
1276
1277/// Typedef of a owning reference that uses an erased `Box` as the owner.
1278pub type ErasedBoxRef<U> = OwningRef<Box<dyn Erased>, U>;
1279/// Typedef of a owning reference that uses an erased `Rc` as the owner.
1280pub type ErasedRcRef<U> = OwningRef<Rc<dyn Erased>, U>;
1281/// Typedef of a owning reference that uses an erased `Arc` as the owner.
1282pub type ErasedArcRef<U> = OwningRef<Arc<dyn Erased>, U>;
1283
1284/// Typedef of a mutable owning reference that uses an erased `Box` as the owner.
1285pub type ErasedBoxRefMut<U> = OwningRefMut<Box<dyn Erased>, U>;
1286
1287#[cfg(test)]
1288mod tests {
1289    mod owning_ref {
1290        use super::super::OwningRef;
1291        use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef};
1292        use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1293        use std::hash::{Hash, Hasher};
1294        use std::collections::hash_map::DefaultHasher;
1295        use std::collections::HashMap;
1296        use std::rc::Rc;
1297
1298        #[derive(Debug, PartialEq)]
1299        struct Example(u32, String, [u8; 3]);
1300        fn example() -> Example {
1301            Example(42, "hello world".to_string(), [1, 2, 3])
1302        }
1303
1304        #[test]
1305        fn new_deref() {
1306            let or: OwningRef<Box<()>, ()> = OwningRef::new(Box::new(()));
1307            assert_eq!(&*or, &());
1308        }
1309
1310        #[test]
1311        fn into() {
1312            let or: OwningRef<Box<()>, ()> = Box::new(()).into();
1313            assert_eq!(&*or, &());
1314        }
1315
1316        #[test]
1317        fn map_offset_ref() {
1318            let or: BoxRef<Example> = Box::new(example()).into();
1319            let or: BoxRef<_, u32> = or.map(|x| &x.0);
1320            assert_eq!(&*or, &42);
1321
1322            let or: BoxRef<Example> = Box::new(example()).into();
1323            let or: BoxRef<_, u8> = or.map(|x| &x.2[1]);
1324            assert_eq!(&*or, &2);
1325        }
1326
1327        #[test]
1328        fn map_heap_ref() {
1329            let or: BoxRef<Example> = Box::new(example()).into();
1330            let or: BoxRef<_, str> = or.map(|x| &x.1[..5]);
1331            assert_eq!(&*or, "hello");
1332        }
1333
1334        #[test]
1335        fn map_static_ref() {
1336            let or: BoxRef<()> = Box::new(()).into();
1337            let or: BoxRef<_, str> = or.map(|_| "hello");
1338            assert_eq!(&*or, "hello");
1339        }
1340
1341        #[test]
1342        fn map_chained() {
1343            let or: BoxRef<String> = Box::new(example().1).into();
1344            let or: BoxRef<_, str> = or.map(|x| &x[1..5]);
1345            let or: BoxRef<_, str> = or.map(|x| &x[..2]);
1346            assert_eq!(&*or, "el");
1347        }
1348
1349        #[test]
1350        fn map_chained_inference() {
1351            let or = BoxRef::new(Box::new(example().1))
1352                .map(|x| &x[..5])
1353                .map(|x| &x[1..3]);
1354            assert_eq!(&*or, "el");
1355        }
1356
1357        #[test]
1358        fn as_owner() {
1359            let or: BoxRef<String> = Box::new(example().1).into();
1360            let or = or.map(|x| &x[..5]);
1361            assert_eq!(&*or, "hello");
1362            assert_eq!(&**or.as_owner(), "hello world");
1363        }
1364
1365        #[test]
1366        fn into_owner() {
1367            let or: BoxRef<String> = Box::new(example().1).into();
1368            let or = or.map(|x| &x[..5]);
1369            assert_eq!(&*or, "hello");
1370            let s = *or.into_owner();
1371            assert_eq!(&s, "hello world");
1372        }
1373
1374        #[test]
1375        fn fmt_debug() {
1376            let or: BoxRef<String> = Box::new(example().1).into();
1377            let or = or.map(|x| &x[..5]);
1378            let s = format!("{:?}", or);
1379            assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }");
1380        }
1381
1382        #[test]
1383        fn erased_owner() {
1384            let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example()))
1385                .map(|x| &x.1[..]);
1386
1387            let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1))
1388                .map(|x| &x[..]);
1389
1390            let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1391            assert!(os.iter().all(|e| &e[..] == "hello world"));
1392        }
1393
1394        #[test]
1395        fn non_static_erased_owner() {
1396            let foo = [413, 612];
1397            let bar = &foo;
1398
1399            // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure
1400            // (see https://github.com/rust-lang/rust/issues/22340)
1401            // So we use a function to identify the lifetimes instead.
1402            fn borrow<'a>(a: &'a &[i32; 2]) -> &'a i32 {
1403                &a[0]
1404            }
1405
1406            let o: BoxRef<&[i32; 2]> = Box::new(bar).into();
1407            let o: BoxRef<&[i32; 2], i32> = o.map(borrow);
1408            let o: BoxRef<dyn Erased, i32> = o.erase_owner();
1409
1410            assert_eq!(*o, 413);
1411        }
1412
1413        #[test]
1414        fn raii_locks() {
1415            use super::super::{RefRef, RefMutRef};
1416            use std::cell::RefCell;
1417            use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef};
1418            use std::sync::{Mutex, RwLock};
1419
1420            {
1421                let a = RefCell::new(1);
1422                let a = {
1423                    let a = RefRef::new(a.borrow());
1424                    assert_eq!(*a, 1);
1425                    a
1426                };
1427                assert_eq!(*a, 1);
1428                drop(a);
1429            }
1430            {
1431                let a = RefCell::new(1);
1432                let a = {
1433                    let a = RefMutRef::new(a.borrow_mut());
1434                    assert_eq!(*a, 1);
1435                    a
1436                };
1437                assert_eq!(*a, 1);
1438                drop(a);
1439            }
1440            {
1441                let a = Mutex::new(1);
1442                let a = {
1443                    let a = MutexGuardRef::new(a.lock().unwrap());
1444                    assert_eq!(*a, 1);
1445                    a
1446                };
1447                assert_eq!(*a, 1);
1448                drop(a);
1449            }
1450            {
1451                let a = RwLock::new(1);
1452                let a = {
1453                    let a = RwLockReadGuardRef::new(a.read().unwrap());
1454                    assert_eq!(*a, 1);
1455                    a
1456                };
1457                assert_eq!(*a, 1);
1458                drop(a);
1459            }
1460            {
1461                let a = RwLock::new(1);
1462                let a = {
1463                    let a = RwLockWriteGuardRef::new(a.write().unwrap());
1464                    assert_eq!(*a, 1);
1465                    a
1466                };
1467                assert_eq!(*a, 1);
1468                drop(a);
1469            }
1470        }
1471
1472        #[test]
1473        fn eq() {
1474            let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1475            let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1476            assert_eq!(or1.eq(&or2), true);
1477        }
1478
1479        #[test]
1480        fn cmp() {
1481            let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1482            let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1483            assert_eq!(or1.cmp(&or2), Ordering::Less);
1484        }
1485
1486        #[test]
1487        fn partial_cmp() {
1488            let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1489            let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1490            assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
1491        }
1492
1493        #[test]
1494        fn hash() {
1495            let mut h1 = DefaultHasher::new();
1496            let mut h2 = DefaultHasher::new();
1497
1498            let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1499            let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1500
1501            or1.hash(&mut h1);
1502            or2.hash(&mut h2);
1503
1504            assert_eq!(h1.finish(), h2.finish());
1505        }
1506
1507        #[test]
1508        fn borrow() {
1509            let mut hash = HashMap::new();
1510            let     key  = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]);
1511
1512            hash.insert(key.clone().map(|s| &s[..3]), 42);
1513            hash.insert(key.clone().map(|s| &s[4..]), 23);
1514
1515            assert_eq!(hash.get("foo"), Some(&42));
1516            assert_eq!(hash.get("bar"), Some(&23));
1517        }
1518
1519        #[test]
1520        fn total_erase() {
1521            let a: OwningRef<Vec<u8>, [u8]>
1522                = OwningRef::new(vec![]).map(|x| &x[..]);
1523            let b: OwningRef<Box<[u8]>, [u8]>
1524                = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1525
1526            let c: OwningRef<Rc<Vec<u8>>, [u8]> = unsafe {a.map_owner(Rc::new)};
1527            let d: OwningRef<Rc<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Rc::new)};
1528
1529            let e: OwningRef<Rc<dyn Erased>, [u8]> = c.erase_owner();
1530            let f: OwningRef<Rc<dyn Erased>, [u8]> = d.erase_owner();
1531
1532            let _g = e.clone();
1533            let _h = f.clone();
1534        }
1535
1536        #[test]
1537        fn total_erase_box() {
1538            let a: OwningRef<Vec<u8>, [u8]>
1539                = OwningRef::new(vec![]).map(|x| &x[..]);
1540            let b: OwningRef<Box<[u8]>, [u8]>
1541                = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1542
1543            let c: OwningRef<Box<Vec<u8>>, [u8]> = a.map_owner_box();
1544            let d: OwningRef<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
1545
1546            let _e: OwningRef<Box<dyn Erased>, [u8]> = c.erase_owner();
1547            let _f: OwningRef<Box<dyn Erased>, [u8]> = d.erase_owner();
1548        }
1549
1550        #[test]
1551        fn try_map1() {
1552            use std::any::Any;
1553
1554            let x = Box::new(123_i32);
1555            let y: Box<dyn Any> = x;
1556
1557            OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap();
1558        }
1559
1560        #[test]
1561        fn try_map2() {
1562            use std::any::Any;
1563
1564            let x = Box::new(123_u32);
1565            let y: Box<dyn Any> = x;
1566
1567            OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap_err();
1568        }
1569
1570        #[test]
1571        fn map_with_owner() {
1572            let owning_ref: BoxRef<Example> = Box::new(example()).into();
1573            let owning_ref = owning_ref.map(|owner| &owner.1);
1574
1575            owning_ref.map_with_owner(|owner, ref_field| {
1576                assert_eq!(owner.1, *ref_field);
1577                ref_field
1578            });
1579        }
1580
1581        #[test]
1582        fn try_map_with_owner_ok() {
1583            let owning_ref: BoxRef<Example> = Box::new(example()).into();
1584            let owning_ref = owning_ref.map(|owner| &owner.1);
1585
1586            owning_ref.try_map_with_owner(|owner, ref_field| {
1587                assert_eq!(owner.1, *ref_field);
1588                Ok(ref_field) as Result<_, ()>
1589            }).unwrap();
1590        }
1591
1592        #[test]
1593        fn try_map_with_owner_err() {
1594            let owning_ref: BoxRef<Example> = Box::new(example()).into();
1595            let owning_ref = owning_ref.map(|owner| &owner.1);
1596
1597            owning_ref.try_map_with_owner(|owner, ref_field| {
1598                assert_eq!(owner.1, *ref_field);
1599                Err(()) as Result<&(), _>
1600            }).unwrap_err();
1601        }
1602    }
1603
1604    mod owning_handle {
1605        use super::super::OwningHandle;
1606        use super::super::RcRef;
1607        use std::rc::Rc;
1608        use std::cell::RefCell;
1609        use std::sync::Arc;
1610        use std::sync::RwLock;
1611
1612        #[test]
1613        fn owning_handle() {
1614            use std::cell::RefCell;
1615            let cell = Rc::new(RefCell::new(2));
1616            let cell_ref = RcRef::new(cell);
1617            let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1618            assert_eq!(*handle, 2);
1619            *handle = 3;
1620            assert_eq!(*handle, 3);
1621        }
1622
1623        #[tokio::test]
1624        async fn owning_handle_async() {
1625            use std::cell::RefCell;
1626            let cell = Rc::new(RefCell::new(2));
1627            let cell_ref = RcRef::new(cell);
1628            let mut handle = OwningHandle::new_with_async_fn(cell_ref, |x| async move { unsafe { x.as_ref() }.unwrap().borrow_mut() }).await;
1629            assert_eq!(*handle, 2);
1630            *handle = 3;
1631            assert_eq!(*handle, 3);
1632        }
1633
1634        #[test]
1635        fn owning_handle_map() {
1636            use std::cell::{Ref, RefCell};
1637            let cell = Rc::new(RefCell::new(('a', 'b')));
1638            let cell_ref = RcRef::new(cell);
1639            let handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow());
1640            assert_eq!(*handle, ('a', 'b'));
1641            let handle_map = handle.map(|r| Ref::map(r, |i| &i.0));
1642            assert_eq!(*handle_map, 'a');
1643        }
1644
1645        #[test]
1646        fn try_owning_handle_ok() {
1647            use std::cell::RefCell;
1648            let cell = Rc::new(RefCell::new(2));
1649            let cell_ref = RcRef::new(cell);
1650            let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1651                Ok(unsafe {
1652                    x.as_ref()
1653                }.unwrap().borrow_mut())
1654            }).unwrap();
1655            assert_eq!(*handle, 2);
1656            *handle = 3;
1657            assert_eq!(*handle, 3);
1658        }
1659
1660        #[tokio::test]
1661        async fn try_owning_handle_ok_async() {
1662            use std::cell::RefCell;
1663            let cell = Rc::new(RefCell::new(2));
1664            let cell_ref = RcRef::new(cell);
1665            let mut handle = OwningHandle::try_new_async::<_, (), _>(cell_ref, |x| async move {
1666                Ok(unsafe {
1667                    x.as_ref()
1668                }.unwrap().borrow_mut())
1669            }).await.unwrap();
1670            assert_eq!(*handle, 2);
1671            *handle = 3;
1672            assert_eq!(*handle, 3);
1673        }
1674
1675        #[test]
1676        fn try_owning_handle_err() {
1677            use std::cell::RefCell;
1678            let cell = Rc::new(RefCell::new(2));
1679            let cell_ref = RcRef::new(cell);
1680            let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1681                if false {
1682                    return Ok(unsafe {
1683                        x.as_ref()
1684                    }.unwrap().borrow_mut())
1685                }
1686                Err(())
1687            });
1688            assert!(handle.is_err());
1689        }
1690
1691        #[tokio::test]
1692        async fn try_owning_handle_err_async() {
1693            use std::cell::RefCell;
1694            let cell = Rc::new(RefCell::new(2));
1695            let cell_ref = RcRef::new(cell);
1696            let handle = OwningHandle::try_new_async::<_, (), _>(cell_ref, |x| async move {
1697                if false {
1698                    return Ok(unsafe {
1699                        x.as_ref()
1700                    }.unwrap().borrow_mut())
1701                }
1702                Err(())
1703            }).await;
1704            assert!(handle.is_err());
1705        }
1706
1707        #[test]
1708        fn nested() {
1709            use std::cell::RefCell;
1710            use std::sync::{Arc, RwLock};
1711
1712            let result = {
1713                let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1714                let curr = RcRef::new(complex);
1715                let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1716                let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1717                assert_eq!(*curr, "someString");
1718                *curr = "someOtherString";
1719                curr
1720            };
1721            assert_eq!(*result, "someOtherString");
1722        }
1723
1724        #[tokio::test]
1725        async fn nested_async() {
1726            use std::cell::RefCell;
1727            use std::sync::{Arc, RwLock};
1728
1729            let result = {
1730                let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1731                let curr = RcRef::new(complex);
1732                let curr = OwningHandle::new_with_async_fn(curr, |x| async move {unsafe { x.as_ref() }.unwrap().borrow_mut()}).await;
1733                let mut curr = OwningHandle::new_with_async_fn(curr, |x| async move {unsafe { x.as_ref() }.unwrap().try_write().unwrap()}).await;
1734                assert_eq!(*curr, "someString");
1735                *curr = "someOtherString";
1736                curr
1737            };
1738            assert_eq!(*result, "someOtherString");
1739        }
1740
1741        #[test]
1742        fn owning_handle_safe() {
1743            use std::cell::RefCell;
1744            let cell = Rc::new(RefCell::new(2));
1745            let cell_ref = RcRef::new(cell);
1746            let handle = OwningHandle::new(cell_ref);
1747            assert_eq!(*handle, 2);
1748        }
1749
1750        #[test]
1751        fn owning_handle_mut_safe() {
1752            use std::cell::RefCell;
1753            let cell = Rc::new(RefCell::new(2));
1754            let cell_ref = RcRef::new(cell);
1755            let mut handle = OwningHandle::new_mut(cell_ref);
1756            assert_eq!(*handle, 2);
1757            *handle = 3;
1758            assert_eq!(*handle, 3);
1759        }
1760
1761        #[test]
1762        fn owning_handle_safe_2() {
1763            let result = {
1764                let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1765                let curr = RcRef::new(complex);
1766                let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1767                let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1768                assert_eq!(*curr, "someString");
1769                *curr = "someOtherString";
1770                curr
1771            };
1772            assert_eq!(*result, "someOtherString");
1773        }
1774
1775        #[tokio::test]
1776        async fn owning_handle_safe_2_async() {
1777            let result = {
1778                let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1779                let curr = RcRef::new(complex);
1780                let curr = OwningHandle::new_with_async_fn(curr, |x| async move { unsafe { x.as_ref() }.unwrap().borrow_mut()}).await;
1781                let mut curr = OwningHandle::new_with_async_fn(curr, |x| async move { unsafe { x.as_ref() }.unwrap().try_write().unwrap()}).await;
1782                assert_eq!(*curr, "someString");
1783                *curr = "someOtherString";
1784                curr
1785            };
1786            assert_eq!(*result, "someOtherString");
1787        }
1788    }
1789
1790    mod owning_ref_mut {
1791        use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut};
1792        use super::super::BoxRef;
1793        use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1794        use std::hash::{Hash, Hasher};
1795        use std::collections::hash_map::DefaultHasher;
1796        use std::collections::HashMap;
1797
1798        #[derive(Debug, PartialEq)]
1799        struct Example(u32, String, [u8; 3]);
1800        fn example() -> Example {
1801            Example(42, "hello world".to_string(), [1, 2, 3])
1802        }
1803
1804        #[test]
1805        fn new_deref() {
1806            let or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1807            assert_eq!(&*or, &());
1808        }
1809
1810        #[test]
1811        fn new_deref_mut() {
1812            let mut or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1813            assert_eq!(&mut *or, &mut ());
1814        }
1815
1816        #[test]
1817        fn mutate() {
1818            let mut or: OwningRefMut<Box<usize>, usize> = OwningRefMut::new(Box::new(0));
1819            assert_eq!(&*or, &0);
1820            *or = 1;
1821            assert_eq!(&*or, &1);
1822        }
1823
1824        #[test]
1825        fn into() {
1826            let or: OwningRefMut<Box<()>, ()> = Box::new(()).into();
1827            assert_eq!(&*or, &());
1828        }
1829
1830        #[test]
1831        fn map_offset_ref() {
1832            let or: BoxRefMut<Example> = Box::new(example()).into();
1833            let or: BoxRef<_, u32> = or.map(|x| &mut x.0);
1834            assert_eq!(&*or, &42);
1835
1836            let or: BoxRefMut<Example> = Box::new(example()).into();
1837            let or: BoxRef<_, u8> = or.map(|x| &mut x.2[1]);
1838            assert_eq!(&*or, &2);
1839        }
1840
1841        #[test]
1842        fn map_heap_ref() {
1843            let or: BoxRefMut<Example> = Box::new(example()).into();
1844            let or: BoxRef<_, str> = or.map(|x| &mut x.1[..5]);
1845            assert_eq!(&*or, "hello");
1846        }
1847
1848        #[test]
1849        fn map_static_ref() {
1850            let or: BoxRefMut<()> = Box::new(()).into();
1851            let or: BoxRef<_, str> = or.map(|_| "hello");
1852            assert_eq!(&*or, "hello");
1853        }
1854
1855        #[test]
1856        fn map_mut_offset_ref() {
1857            let or: BoxRefMut<Example> = Box::new(example()).into();
1858            let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0);
1859            assert_eq!(&*or, &42);
1860
1861            let or: BoxRefMut<Example> = Box::new(example()).into();
1862            let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]);
1863            assert_eq!(&*or, &2);
1864        }
1865
1866        #[test]
1867        fn map_mut_heap_ref() {
1868            let or: BoxRefMut<Example> = Box::new(example()).into();
1869            let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]);
1870            assert_eq!(&*or, "hello");
1871        }
1872
1873        #[test]
1874        fn map_mut_static_ref() {
1875            static mut MUT_S: [u8; 5] = *b"hello";
1876
1877            let mut_s: &'static mut [u8] = unsafe { &mut MUT_S };
1878
1879            let or: BoxRefMut<()> = Box::new(()).into();
1880            let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s);
1881            assert_eq!(&*or, b"hello");
1882        }
1883
1884        #[test]
1885        fn map_mut_chained() {
1886            let or: BoxRefMut<String> = Box::new(example().1).into();
1887            let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]);
1888            let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]);
1889            assert_eq!(&*or, "el");
1890        }
1891
1892        #[test]
1893        fn map_chained_inference() {
1894            let or = BoxRefMut::new(Box::new(example().1))
1895                .map_mut(|x| &mut x[..5])
1896                .map_mut(|x| &mut x[1..3]);
1897            assert_eq!(&*or, "el");
1898        }
1899
1900        #[test]
1901        fn try_map_mut() {
1902            let or: BoxRefMut<String> = Box::new(example().1).into();
1903            let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|x| Ok(&mut x[1..5]));
1904            assert_eq!(&*or.unwrap(), "ello");
1905
1906            let or: BoxRefMut<String> = Box::new(example().1).into();
1907            let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|_| Err(()));
1908            assert!(or.is_err());
1909        }
1910
1911        #[test]
1912        fn as_owner() {
1913            let or: BoxRefMut<String> = Box::new(example().1).into();
1914            let or = or.map_mut(|x| &mut x[..5]);
1915            assert_eq!(&*or, "hello");
1916            assert_eq!(&**or.as_owner(), "hello world");
1917        }
1918
1919        #[test]
1920        fn into_owner() {
1921            let or: BoxRefMut<String> = Box::new(example().1).into();
1922            let or = or.map_mut(|x| &mut x[..5]);
1923            assert_eq!(&*or, "hello");
1924            let s = *or.into_owner();
1925            assert_eq!(&s, "hello world");
1926        }
1927
1928        #[test]
1929        fn fmt_debug() {
1930            let or: BoxRefMut<String> = Box::new(example().1).into();
1931            let or = or.map_mut(|x| &mut x[..5]);
1932            let s = format!("{:?}", or);
1933            assert_eq!(&s,
1934                       "OwningRefMut { owner: \"hello world\", reference: \"hello\" }");
1935        }
1936
1937        #[test]
1938        fn erased_owner() {
1939            let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example()))
1940                .map_mut(|x| &mut x.1[..]);
1941
1942            let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1))
1943                .map_mut(|x| &mut x[..]);
1944
1945            let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1946            assert!(os.iter().all(|e| &e[..] == "hello world"));
1947        }
1948
1949        #[test]
1950        fn non_static_erased_owner() {
1951            let mut foo = [413, 612];
1952            let bar = &mut foo;
1953
1954            // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure
1955            // (see https://github.com/rust-lang/rust/issues/22340)
1956            // So we use a function to identify the lifetimes instead.
1957            fn borrow<'a>(a: &'a mut &mut [i32; 2]) -> &'a mut i32 {
1958                &mut a[0]
1959            }
1960
1961            let o: BoxRefMut<&mut [i32; 2]> = Box::new(bar).into();
1962            let o: BoxRefMut<&mut [i32; 2], i32> = o.map_mut(borrow);
1963            let o: BoxRefMut<dyn Erased, i32> = o.erase_owner();
1964
1965            assert_eq!(*o, 413);
1966        }
1967
1968        #[test]
1969        fn raii_locks() {
1970            use super::super::RefMutRefMut;
1971            use std::cell::RefCell;
1972            use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut};
1973            use std::sync::{Mutex, RwLock};
1974
1975            {
1976                let a = RefCell::new(1);
1977                let a = {
1978                    let a = RefMutRefMut::new(a.borrow_mut());
1979                    assert_eq!(*a, 1);
1980                    a
1981                };
1982                assert_eq!(*a, 1);
1983                drop(a);
1984            }
1985            {
1986                let a = Mutex::new(1);
1987                let a = {
1988                    let a = MutexGuardRefMut::new(a.lock().unwrap());
1989                    assert_eq!(*a, 1);
1990                    a
1991                };
1992                assert_eq!(*a, 1);
1993                drop(a);
1994            }
1995            {
1996                let a = RwLock::new(1);
1997                let a = {
1998                    let a = RwLockWriteGuardRefMut::new(a.write().unwrap());
1999                    assert_eq!(*a, 1);
2000                    a
2001                };
2002                assert_eq!(*a, 1);
2003                drop(a);
2004            }
2005        }
2006
2007        #[test]
2008        fn eq() {
2009            let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2010            let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2011            assert_eq!(or1.eq(&or2), true);
2012        }
2013
2014        #[test]
2015        fn cmp() {
2016            let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2017            let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
2018            assert_eq!(or1.cmp(&or2), Ordering::Less);
2019        }
2020
2021        #[test]
2022        fn partial_cmp() {
2023            let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
2024            let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2025            assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
2026        }
2027
2028        #[test]
2029        fn hash() {
2030            let mut h1 = DefaultHasher::new();
2031            let mut h2 = DefaultHasher::new();
2032
2033            let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2034            let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2035
2036            or1.hash(&mut h1);
2037            or2.hash(&mut h2);
2038
2039            assert_eq!(h1.finish(), h2.finish());
2040        }
2041
2042        #[test]
2043        fn borrow() {
2044            let mut hash = HashMap::new();
2045            let     key1 = BoxRefMut::<String>::new(Box::new("foo".to_string())).map(|s| &s[..]);
2046            let     key2 = BoxRefMut::<String>::new(Box::new("bar".to_string())).map(|s| &s[..]);
2047
2048            hash.insert(key1, 42);
2049            hash.insert(key2, 23);
2050
2051            assert_eq!(hash.get("foo"), Some(&42));
2052            assert_eq!(hash.get("bar"), Some(&23));
2053        }
2054
2055        #[test]
2056        fn total_erase() {
2057            let a: OwningRefMut<Vec<u8>, [u8]>
2058                = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
2059            let b: OwningRefMut<Box<[u8]>, [u8]>
2060                = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
2061
2062            let c: OwningRefMut<Box<Vec<u8>>, [u8]> = unsafe {a.map_owner(Box::new)};
2063            let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Box::new)};
2064
2065            let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
2066            let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
2067        }
2068
2069        #[test]
2070        fn total_erase_box() {
2071            let a: OwningRefMut<Vec<u8>, [u8]>
2072                = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
2073            let b: OwningRefMut<Box<[u8]>, [u8]>
2074                = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
2075
2076            let c: OwningRefMut<Box<Vec<u8>>, [u8]> = a.map_owner_box();
2077            let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
2078
2079            let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
2080            let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
2081        }
2082
2083        #[test]
2084        fn try_map1() {
2085            use std::any::Any;
2086
2087            let x = Box::new(123_i32);
2088            let y: Box<dyn Any> = x;
2089
2090            OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap();
2091        }
2092
2093        #[test]
2094        fn try_map2() {
2095            use std::any::Any;
2096
2097            let x = Box::new(123_u32);
2098            let y: Box<dyn Any> = x;
2099
2100            OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap_err();
2101        }
2102
2103        #[test]
2104        fn try_map3() {
2105            use std::any::Any;
2106
2107            let x = Box::new(123_i32);
2108            let y: Box<dyn Any> = x;
2109
2110            OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap();
2111        }
2112
2113        #[test]
2114        fn try_map4() {
2115            use std::any::Any;
2116
2117            let x = Box::new(123_u32);
2118            let y: Box<dyn Any> = x;
2119
2120            OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap_err();
2121        }
2122
2123        #[test]
2124        fn into_owning_ref() {
2125            use super::super::BoxRef;
2126
2127            let or: BoxRefMut<()> = Box::new(()).into();
2128            let or: BoxRef<()> = or.into();
2129            assert_eq!(&*or, &());
2130        }
2131
2132        struct Foo {
2133            u: u32,
2134        }
2135        struct Bar {
2136            f: Foo,
2137        }
2138
2139        #[test]
2140        fn ref_mut() {
2141            use std::cell::RefCell;
2142
2143            let a = RefCell::new(Bar { f: Foo { u: 42 } });
2144            let mut b = OwningRefMut::new(a.borrow_mut());
2145            assert_eq!(b.f.u, 42);
2146            b.f.u = 43;
2147            let mut c = b.map_mut(|x| &mut x.f);
2148            assert_eq!(c.u, 43);
2149            c.u = 44;
2150            let mut d = c.map_mut(|x| &mut x.u);
2151            assert_eq!(*d, 44);
2152            *d = 45;
2153            assert_eq!(*d, 45);
2154        }
2155    }
2156}