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