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