owning_ref/
lib.rs

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