]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/owning_ref/mod.rs
Rollup merge of #63416 - RalfJung:apfloat, r=eddyb
[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 ```compile_fail,E0515
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.
47 For example, `BoxRef<T>` instead of `OwningRef<Box<T>, T>`.
48
49 The crate also provides the more advanced `OwningHandle` type,
50 which allows more freedom in bundling a dependent handle object
51 along with the data it depends on, at the cost of some unsafe needed in the API.
52 See the documentation around `OwningHandle` for more details.
53
54 # Examples
55
56 ## Basics
57
58 ```
59 extern crate owning_ref;
60 use owning_ref::BoxRef;
61
62 fn main() {
63     // Create an array owned by a Box.
64     let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;
65
66     // Transfer into a BoxRef.
67     let arr: BoxRef<[i32]> = BoxRef::new(arr);
68     assert_eq!(&*arr, &[1, 2, 3, 4]);
69
70     // We can slice the array without losing ownership or changing type.
71     let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]);
72     assert_eq!(&*arr, &[2, 3]);
73
74     // Also works for Arc, Rc, String and Vec!
75 }
76 ```
77
78 ## Caching a reference to a struct field
79
80 ```
81 extern crate owning_ref;
82 use owning_ref::BoxRef;
83
84 fn main() {
85     struct Foo {
86         tag: u32,
87         x: u16,
88         y: u16,
89         z: u16,
90     }
91     let foo = Foo { tag: 1, x: 100, y: 200, z: 300 };
92
93     let or = BoxRef::new(Box::new(foo)).map(|foo| {
94         match foo.tag {
95             0 => &foo.x,
96             1 => &foo.y,
97             2 => &foo.z,
98             _ => panic!(),
99         }
100     });
101
102     assert_eq!(*or, 200);
103 }
104 ```
105
106 ## Caching a reference to an entry in a vector
107
108 ```
109 extern crate owning_ref;
110 use owning_ref::VecRef;
111
112 fn main() {
113     let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]);
114     assert_eq!(*v, 4);
115 }
116 ```
117
118 ## Caching a subslice of a String
119
120 ```
121 extern crate owning_ref;
122 use owning_ref::StringRef;
123
124 fn main() {
125     let s = StringRef::new("hello world".to_owned())
126         .map(|s| s.split(' ').nth(1).unwrap());
127
128     assert_eq!(&*s, "world");
129 }
130 ```
131
132 ## Reference counted slices that share ownership of the backing storage
133
134 ```
135 extern crate owning_ref;
136 use owning_ref::RcRef;
137 use std::rc::Rc;
138
139 fn main() {
140     let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>);
141     assert_eq!(&*rc, &[1, 2, 3, 4]);
142
143     let rc_a: RcRef<[i32]> = rc.clone().map(|s| &s[0..2]);
144     let rc_b = rc.clone().map(|s| &s[1..3]);
145     let rc_c = rc.clone().map(|s| &s[2..4]);
146     assert_eq!(&*rc_a, &[1, 2]);
147     assert_eq!(&*rc_b, &[2, 3]);
148     assert_eq!(&*rc_c, &[3, 4]);
149
150     let rc_c_a = rc_c.clone().map(|s| &s[1]);
151     assert_eq!(&*rc_c_a, &4);
152 }
153 ```
154
155 ## Atomic reference counted slices that share ownership of the backing storage
156
157 ```
158 extern crate owning_ref;
159 use owning_ref::ArcRef;
160 use std::sync::Arc;
161
162 fn main() {
163     use std::thread;
164
165     fn par_sum(rc: ArcRef<[i32]>) -> i32 {
166         if rc.len() == 0 {
167             return 0;
168         } else if rc.len() == 1 {
169             return rc[0];
170         }
171         let mid = rc.len() / 2;
172         let left = rc.clone().map(|s| &s[..mid]);
173         let right = rc.map(|s| &s[mid..]);
174
175         let left = thread::spawn(move || par_sum(left));
176         let right = thread::spawn(move || par_sum(right));
177
178         left.join().unwrap() + right.join().unwrap()
179     }
180
181     let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]);
182     let rc: ArcRef<[i32]> = rc.into();
183
184     assert_eq!(par_sum(rc), 10);
185 }
186 ```
187
188 ## References into RAII locks
189
190 ```
191 extern crate owning_ref;
192 use owning_ref::RefRef;
193 use std::cell::{RefCell, Ref};
194
195 fn main() {
196     let refcell = RefCell::new((1, 2, 3, 4));
197     // Also works with Mutex and RwLock
198
199     let refref = {
200         let refref = RefRef::new(refcell.borrow()).map(|x| &x.3);
201         assert_eq!(*refref, 4);
202
203         // We move the RAII lock and the reference to one of
204         // the subfields in the data it guards here:
205         refref
206     };
207
208     assert_eq!(*refref, 4);
209
210     drop(refref);
211
212     assert_eq!(*refcell.borrow(), (1, 2, 3, 4));
213 }
214 ```
215
216 ## Mutable reference
217
218 When the owned container implements `DerefMut`, it is also possible to make
219 a _mutable owning reference_. (e.g., with `Box`, `RefMut`, `MutexGuard`)
220
221 ```
222 extern crate owning_ref;
223 use owning_ref::RefMutRefMut;
224 use std::cell::{RefCell, RefMut};
225
226 fn main() {
227     let refcell = RefCell::new((1, 2, 3, 4));
228
229     let mut refmut_refmut = {
230         let mut refmut_refmut = RefMutRefMut::new(refcell.borrow_mut()).map_mut(|x| &mut x.3);
231         assert_eq!(*refmut_refmut, 4);
232         *refmut_refmut *= 2;
233
234         refmut_refmut
235     };
236
237     assert_eq!(*refmut_refmut, 8);
238     *refmut_refmut *= 2;
239
240     drop(refmut_refmut);
241
242     assert_eq!(*refcell.borrow(), (1, 2, 3, 16));
243 }
244 ```
245 */
246
247 use std::mem;
248 pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
249
250 /// An owning reference.
251 ///
252 /// This wraps an owner `O` and a reference `&T` pointing
253 /// at something reachable from `O::Target` while keeping
254 /// the ability to move `self` around.
255 ///
256 /// The owner is usually a pointer that points at some base type.
257 ///
258 /// For more details and examples, see the module and method docs.
259 pub struct OwningRef<O, T: ?Sized> {
260     owner: O,
261     reference: *const T,
262 }
263
264 /// An mutable owning reference.
265 ///
266 /// This wraps an owner `O` and a reference `&mut T` pointing
267 /// at something reachable from `O::Target` while keeping
268 /// the ability to move `self` around.
269 ///
270 /// The owner is usually a pointer that points at some base type.
271 ///
272 /// For more details and examples, see the module and method docs.
273 pub struct OwningRefMut<O, T: ?Sized> {
274     owner: O,
275     reference: *mut T,
276 }
277
278 /// Helper trait for an erased concrete type an owner dereferences to.
279 /// This is used in form of a trait object for keeping
280 /// something around to (virtually) call the destructor.
281 pub trait Erased {}
282 impl<T> Erased for T {}
283
284 /// Helper trait for erasing the concrete type of what an owner dereferences to,
285 /// for example `Box<T> -> Box<Erased>`. This would be unneeded with
286 /// higher kinded types support in the language.
287 #[allow(unused_lifetimes)]
288 pub unsafe trait IntoErased<'a> {
289     /// Owner with the dereference type substituted to `Erased`.
290     type Erased;
291     /// Performs the type erasure.
292     fn into_erased(self) -> Self::Erased;
293 }
294
295 /// Helper trait for erasing the concrete type of what an owner dereferences to,
296 /// for example `Box<T> -> Box<Erased + Send>`. This would be unneeded with
297 /// higher kinded types support in the language.
298 #[allow(unused_lifetimes)]
299 pub unsafe trait IntoErasedSend<'a> {
300     /// Owner with the dereference type substituted to `Erased + Send`.
301     type Erased: Send;
302     /// Performs the type erasure.
303     fn into_erased_send(self) -> Self::Erased;
304 }
305
306 /// Helper trait for erasing the concrete type of what an owner dereferences to,
307 /// for example `Box<T> -> Box<Erased + Send + Sync>`. This would be unneeded with
308 /// higher kinded types support in the language.
309 #[allow(unused_lifetimes)]
310 pub unsafe trait IntoErasedSendSync<'a> {
311     /// Owner with the dereference type substituted to `Erased + Send + Sync`.
312     type Erased: Send + Sync;
313     /// Performs the type erasure.
314     fn into_erased_send_sync(self) -> Self::Erased;
315 }
316
317 /////////////////////////////////////////////////////////////////////////////
318 // OwningRef
319 /////////////////////////////////////////////////////////////////////////////
320
321 impl<O, T: ?Sized> OwningRef<O, T> {
322     /// Creates a new owning reference from a owner
323     /// initialized to the direct dereference of it.
324     ///
325     /// # Example
326     /// ```
327     /// extern crate owning_ref;
328     /// use owning_ref::OwningRef;
329     ///
330     /// fn main() {
331     ///     let owning_ref = OwningRef::new(Box::new(42));
332     ///     assert_eq!(*owning_ref, 42);
333     /// }
334     /// ```
335     pub fn new(o: O) -> Self
336         where O: StableAddress,
337               O: Deref<Target = T>,
338     {
339         OwningRef {
340             reference: &*o,
341             owner: o,
342         }
343     }
344
345     /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
346     /// Instead, the caller is responsible to make the same promises as implementing the trait.
347     ///
348     /// This is useful for cases where coherence rules prevents implementing the trait
349     /// without adding a dependency to this crate in a third-party library.
350     pub unsafe fn new_assert_stable_address(o: O) -> Self
351         where O: Deref<Target = T>,
352     {
353         OwningRef {
354             reference: &*o,
355             owner: o,
356         }
357     }
358
359     /// Converts `self` into a new owning reference that points at something reachable
360     /// from the previous one.
361     ///
362     /// This can be a reference to a field of `U`, something reachable from a field of
363     /// `U`, or even something unrelated with a `'static` lifetime.
364     ///
365     /// # Example
366     /// ```
367     /// extern crate owning_ref;
368     /// use owning_ref::OwningRef;
369     ///
370     /// fn main() {
371     ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
372     ///
373     ///     // create a owning reference that points at the
374     ///     // third element of the array.
375     ///     let owning_ref = owning_ref.map(|array| &array[2]);
376     ///     assert_eq!(*owning_ref, 3);
377     /// }
378     /// ```
379     pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
380         where O: StableAddress,
381               F: FnOnce(&T) -> &U
382     {
383         OwningRef {
384             reference: f(&self),
385             owner: self.owner,
386         }
387     }
388
389     /// Tries to convert `self` into a new owning reference that points
390     /// at something reachable from the previous one.
391     ///
392     /// This can be a reference to a field of `U`, something reachable from a field of
393     /// `U`, or even something unrelated with a `'static` lifetime.
394     ///
395     /// # Example
396     /// ```
397     /// extern crate owning_ref;
398     /// use owning_ref::OwningRef;
399     ///
400     /// fn main() {
401     ///     let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
402     ///
403     ///     // create a owning reference that points at the
404     ///     // third element of the array.
405     ///     let owning_ref = owning_ref.try_map(|array| {
406     ///         if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
407     ///     });
408     ///     assert_eq!(*owning_ref.unwrap(), 3);
409     /// }
410     /// ```
411     pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
412         where O: StableAddress,
413               F: FnOnce(&T) -> Result<&U, E>
414     {
415         Ok(OwningRef {
416             reference: f(&self)?,
417             owner: self.owner,
418         })
419     }
420
421     /// Converts `self` into a new owning reference with a different owner type.
422     ///
423     /// The new owner type needs to still contain the original owner in some way
424     /// so that the reference into it remains valid. This function is marked unsafe
425     /// because the user needs to manually uphold this guarantee.
426     pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<P, T>
427         where O: StableAddress,
428               P: StableAddress,
429               F: FnOnce(O) -> P
430     {
431         OwningRef {
432             reference: self.reference,
433             owner: f(self.owner),
434         }
435     }
436
437     /// Converts `self` into a new owning reference where the owner is wrapped
438     /// in an additional `Box<O>`.
439     ///
440     /// This can be used to safely erase the owner of any `OwningRef<O, T>`
441     /// to a `OwningRef<Box<Erased>, T>`.
442     pub fn map_owner_box(self) -> OwningRef<Box<O>, T> {
443         OwningRef {
444             reference: self.reference,
445             owner: Box::new(self.owner),
446         }
447     }
448
449     /// Erases the concrete base type of the owner with a trait object.
450     ///
451     /// This allows mixing of owned references with different owner base types.
452     ///
453     /// # Example
454     /// ```
455     /// extern crate owning_ref;
456     /// use owning_ref::{OwningRef, Erased};
457     ///
458     /// fn main() {
459     ///     // N.B., using the concrete types here for explicitness.
460     ///     // For less verbose code type aliases like `BoxRef` are provided.
461     ///
462     ///     let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]>
463     ///         = OwningRef::new(Box::new([1, 2, 3, 4]));
464     ///
465     ///     let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
466     ///         = OwningRef::new(Box::new(vec![(0, false), (1, true)]));
467     ///
468     ///     let owning_ref_a: OwningRef<Box<[i32; 4]>, i32>
469     ///         = owning_ref_a.map(|a| &a[0]);
470     ///
471     ///     let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, i32>
472     ///         = owning_ref_b.map(|a| &a[1].0);
473     ///
474     ///     let owning_refs: [OwningRef<Box<Erased>, i32>; 2]
475     ///         = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()];
476     ///
477     ///     assert_eq!(*owning_refs[0], 1);
478     ///     assert_eq!(*owning_refs[1], 1);
479     /// }
480     /// ```
481     pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T>
482         where O: IntoErased<'a>,
483     {
484         OwningRef {
485             reference: self.reference,
486             owner: self.owner.into_erased(),
487         }
488     }
489
490     /// Erases the concrete base type of the owner with a trait object which implements `Send`.
491     ///
492     /// This allows mixing of owned references with different owner base types.
493     pub fn erase_send_owner<'a>(self) -> OwningRef<O::Erased, T>
494         where O: IntoErasedSend<'a>,
495     {
496         OwningRef {
497             reference: self.reference,
498             owner: self.owner.into_erased_send(),
499         }
500     }
501
502     /// Erases the concrete base type of the owner with a trait object
503     /// which implements `Send` and `Sync`.
504     ///
505     /// This allows mixing of owned references with different owner base types.
506     pub fn erase_send_sync_owner<'a>(self) -> OwningRef<O::Erased, T>
507         where O: IntoErasedSendSync<'a>,
508     {
509         OwningRef {
510             reference: self.reference,
511             owner: self.owner.into_erased_send_sync(),
512         }
513     }
514
515     // UNIMPLEMENTED: wrap_owner
516
517     // FIXME: Naming convention?
518     /// A getter for the underlying owner.
519     pub fn owner(&self) -> &O {
520         &self.owner
521     }
522
523     // FIXME: Naming convention?
524     /// Discards the reference and retrieves the owner.
525     pub fn into_inner(self) -> O {
526         self.owner
527     }
528 }
529
530 impl<O, T: ?Sized> OwningRefMut<O, T> {
531     /// Creates a new owning reference from a owner
532     /// initialized to the direct dereference of it.
533     ///
534     /// # Example
535     /// ```
536     /// extern crate owning_ref;
537     /// use owning_ref::OwningRefMut;
538     ///
539     /// fn main() {
540     ///     let owning_ref_mut = OwningRefMut::new(Box::new(42));
541     ///     assert_eq!(*owning_ref_mut, 42);
542     /// }
543     /// ```
544     pub fn new(mut o: O) -> Self
545         where O: StableAddress,
546               O: DerefMut<Target = T>,
547     {
548         OwningRefMut {
549             reference: &mut *o,
550             owner: o,
551         }
552     }
553
554     /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait.
555     /// Instead, the caller is responsible to make the same promises as implementing the trait.
556     ///
557     /// This is useful for cases where coherence rules prevents implementing the trait
558     /// without adding a dependency to this crate in a third-party library.
559     pub unsafe fn new_assert_stable_address(mut o: O) -> Self
560         where O: DerefMut<Target = T>,
561     {
562         OwningRefMut {
563             reference: &mut *o,
564             owner: o,
565         }
566     }
567
568     /// Converts `self` into a new _shared_ owning reference that points at
569     /// something reachable from the previous one.
570     ///
571     /// This can be a reference to a field of `U`, something reachable from a field of
572     /// `U`, or even something unrelated with a `'static` lifetime.
573     ///
574     /// # Example
575     /// ```
576     /// extern crate owning_ref;
577     /// use owning_ref::OwningRefMut;
578     ///
579     /// fn main() {
580     ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
581     ///
582     ///     // create a owning reference that points at the
583     ///     // third element of the array.
584     ///     let owning_ref = owning_ref_mut.map(|array| &array[2]);
585     ///     assert_eq!(*owning_ref, 3);
586     /// }
587     /// ```
588     pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U>
589         where O: StableAddress,
590               F: FnOnce(&mut T) -> &U
591     {
592         OwningRef {
593             reference: f(&mut self),
594             owner: self.owner,
595         }
596     }
597
598     /// Converts `self` into a new _mutable_ owning reference that points at
599     /// something reachable from the previous one.
600     ///
601     /// This can be a reference to a field of `U`, something reachable from a field of
602     /// `U`, or even something unrelated with a `'static` lifetime.
603     ///
604     /// # Example
605     /// ```
606     /// extern crate owning_ref;
607     /// use owning_ref::OwningRefMut;
608     ///
609     /// fn main() {
610     ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
611     ///
612     ///     // create a owning reference that points at the
613     ///     // third element of the array.
614     ///     let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]);
615     ///     assert_eq!(*owning_ref_mut, 3);
616     /// }
617     /// ```
618     pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U>
619         where O: StableAddress,
620               F: FnOnce(&mut T) -> &mut U
621     {
622         OwningRefMut {
623             reference: f(&mut self),
624             owner: self.owner,
625         }
626     }
627
628     /// Tries to convert `self` into a new _shared_ owning reference that points
629     /// at something reachable from the previous one.
630     ///
631     /// This can be a reference to a field of `U`, something reachable from a field of
632     /// `U`, or even something unrelated with a `'static` lifetime.
633     ///
634     /// # Example
635     /// ```
636     /// extern crate owning_ref;
637     /// use owning_ref::OwningRefMut;
638     ///
639     /// fn main() {
640     ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
641     ///
642     ///     // create a owning reference that points at the
643     ///     // third element of the array.
644     ///     let owning_ref = owning_ref_mut.try_map(|array| {
645     ///         if array[2] == 3 { Ok(&array[2]) } else { Err(()) }
646     ///     });
647     ///     assert_eq!(*owning_ref.unwrap(), 3);
648     /// }
649     /// ```
650     pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E>
651         where O: StableAddress,
652               F: FnOnce(&mut T) -> Result<&U, E>
653     {
654         Ok(OwningRef {
655             reference: f(&mut self)?,
656             owner: self.owner,
657         })
658     }
659
660     /// Tries to convert `self` into a new _mutable_ owning reference that points
661     /// at something reachable from the previous one.
662     ///
663     /// This can be a reference to a field of `U`, something reachable from a field of
664     /// `U`, or even something unrelated with a `'static` lifetime.
665     ///
666     /// # Example
667     /// ```
668     /// extern crate owning_ref;
669     /// use owning_ref::OwningRefMut;
670     ///
671     /// fn main() {
672     ///     let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
673     ///
674     ///     // create a owning reference that points at the
675     ///     // third element of the array.
676     ///     let owning_ref_mut = owning_ref_mut.try_map_mut(|array| {
677     ///         if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) }
678     ///     });
679     ///     assert_eq!(*owning_ref_mut.unwrap(), 3);
680     /// }
681     /// ```
682     pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E>
683         where O: StableAddress,
684               F: FnOnce(&mut T) -> Result<&mut U, E>
685     {
686         Ok(OwningRefMut {
687             reference: f(&mut self)?,
688             owner: self.owner,
689         })
690     }
691
692     /// Converts `self` into a new owning reference with a different owner type.
693     ///
694     /// The new owner type needs to still contain the original owner in some way
695     /// so that the reference into it remains valid. This function is marked unsafe
696     /// because the user needs to manually uphold this guarantee.
697     pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T>
698         where O: StableAddress,
699               P: StableAddress,
700               F: FnOnce(O) -> P
701     {
702         OwningRefMut {
703             reference: self.reference,
704             owner: f(self.owner),
705         }
706     }
707
708     /// Converts `self` into a new owning reference where the owner is wrapped
709     /// in an additional `Box<O>`.
710     ///
711     /// This can be used to safely erase the owner of any `OwningRefMut<O, T>`
712     /// to a `OwningRefMut<Box<Erased>, T>`.
713     pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> {
714         OwningRefMut {
715             reference: self.reference,
716             owner: Box::new(self.owner),
717         }
718     }
719
720     /// Erases the concrete base type of the owner with a trait object.
721     ///
722     /// This allows mixing of owned references with different owner base types.
723     ///
724     /// # Example
725     /// ```
726     /// extern crate owning_ref;
727     /// use owning_ref::{OwningRefMut, Erased};
728     ///
729     /// fn main() {
730     ///     // N.B., using the concrete types here for explicitness.
731     ///     // For less verbose code type aliases like `BoxRef` are provided.
732     ///
733     ///     let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]>
734     ///         = OwningRefMut::new(Box::new([1, 2, 3, 4]));
735     ///
736     ///     let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
737     ///         = OwningRefMut::new(Box::new(vec![(0, false), (1, true)]));
738     ///
739     ///     let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32>
740     ///         = owning_ref_mut_a.map_mut(|a| &mut a[0]);
741     ///
742     ///     let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32>
743     ///         = owning_ref_mut_b.map_mut(|a| &mut a[1].0);
744     ///
745     ///     let owning_refs_mut: [OwningRefMut<Box<Erased>, i32>; 2]
746     ///         = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()];
747     ///
748     ///     assert_eq!(*owning_refs_mut[0], 1);
749     ///     assert_eq!(*owning_refs_mut[1], 1);
750     /// }
751     /// ```
752     pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T>
753         where O: IntoErased<'a>,
754     {
755         OwningRefMut {
756             reference: self.reference,
757             owner: self.owner.into_erased(),
758         }
759     }
760
761     // UNIMPLEMENTED: wrap_owner
762
763     // FIXME: Naming convention?
764     /// A getter for the underlying owner.
765     pub fn owner(&self) -> &O {
766         &self.owner
767     }
768
769     // FIXME: Naming convention?
770     /// Discards the reference and retrieves the owner.
771     pub fn into_inner(self) -> O {
772         self.owner
773     }
774 }
775
776 /////////////////////////////////////////////////////////////////////////////
777 // OwningHandle
778 /////////////////////////////////////////////////////////////////////////////
779
780 use std::ops::{Deref, DerefMut};
781
782 /// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows
783 /// consumers to pass around an owned object and a dependent reference,
784 /// `OwningHandle` contains an owned object and a dependent _object_.
785 ///
786 /// `OwningHandle` can encapsulate a `RefMut` along with its associated
787 /// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`.
788 /// However, the API is completely generic and there are no restrictions on
789 /// what types of owning and dependent objects may be used.
790 ///
791 /// `OwningHandle` is created by passing an owner object (which dereferences
792 /// to a stable address) along with a callback which receives a pointer to
793 /// that stable location. The callback may then dereference the pointer and
794 /// mint a dependent object, with the guarantee that the returned object will
795 /// not outlive the referent of the pointer.
796 ///
797 /// Since the callback needs to dereference a raw pointer, it requires `unsafe`
798 /// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is
799 /// implemented for common data structures. Types that implement `ToHandle` can
800 /// be wrapped into an `OwningHandle` without passing a callback.
801 pub struct OwningHandle<O, H>
802     where O: StableAddress, H: Deref,
803 {
804     handle: H,
805     _owner: O,
806 }
807
808 impl<O, H> Deref for OwningHandle<O, H>
809     where O: StableAddress, H: Deref,
810 {
811     type Target = H::Target;
812     fn deref(&self) -> &H::Target {
813         self.handle.deref()
814     }
815 }
816
817 unsafe impl<O, H> StableAddress for OwningHandle<O, H>
818     where O: StableAddress, H: StableAddress,
819 {}
820
821 impl<O, H> DerefMut for OwningHandle<O, H>
822     where O: StableAddress, H: DerefMut,
823 {
824     fn deref_mut(&mut self) -> &mut H::Target {
825         self.handle.deref_mut()
826     }
827 }
828
829 /// Trait to implement the conversion of owner to handle for common types.
830 pub trait ToHandle {
831     /// The type of handle to be encapsulated by the OwningHandle.
832     type Handle: Deref;
833
834     /// Given an appropriately-long-lived pointer to ourselves, create a
835     /// handle to be encapsulated by the `OwningHandle`.
836     unsafe fn to_handle(x: *const Self) -> Self::Handle;
837 }
838
839 /// Trait to implement the conversion of owner to mutable handle for common types.
840 pub trait ToHandleMut {
841     /// The type of handle to be encapsulated by the OwningHandle.
842     type HandleMut: DerefMut;
843
844     /// Given an appropriately-long-lived pointer to ourselves, create a
845     /// mutable handle to be encapsulated by the `OwningHandle`.
846     unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut;
847 }
848
849 impl<O, H> OwningHandle<O, H>
850 where
851     O: StableAddress<Target: ToHandle<Handle = H>>,
852     H: Deref,
853 {
854     /// Creates a new `OwningHandle` for a type that implements `ToHandle`. For types
855     /// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts
856     /// a callback to perform the conversion.
857     pub fn new(o: O) -> Self {
858         OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) })
859     }
860 }
861
862 impl<O, H> OwningHandle<O, H>
863 where
864     O: StableAddress<Target: ToHandleMut<HandleMut = H>>,
865     H: DerefMut,
866 {
867     /// Creates a new mutable `OwningHandle` for a type that implements `ToHandleMut`.
868     pub fn new_mut(o: O) -> Self {
869         OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) })
870     }
871 }
872
873 impl<O, H> OwningHandle<O, H>
874     where O: StableAddress, H: Deref,
875 {
876     /// Creates a new OwningHandle. The provided callback will be invoked with
877     /// a pointer to the object owned by `o`, and the returned value is stored
878     /// as the object to which this `OwningHandle` will forward `Deref` and
879     /// `DerefMut`.
880     pub fn new_with_fn<F>(o: O, f: F) -> Self
881         where F: FnOnce(*const O::Target) -> H
882     {
883         let h: H;
884         {
885             h = f(o.deref() as *const O::Target);
886         }
887
888         OwningHandle {
889           handle: h,
890           _owner: o,
891         }
892     }
893
894     /// Creates a new OwningHandle. The provided callback will be invoked with
895     /// a pointer to the object owned by `o`, and the returned value is stored
896     /// as the object to which this `OwningHandle` will forward `Deref` and
897     /// `DerefMut`.
898     pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
899         where F: FnOnce(*const O::Target) -> Result<H, E>
900     {
901         let h: H;
902         {
903             h = f(o.deref() as *const O::Target)?;
904         }
905
906         Ok(OwningHandle {
907           handle: h,
908           _owner: o,
909         })
910     }
911 }
912
913 /////////////////////////////////////////////////////////////////////////////
914 // std traits
915 /////////////////////////////////////////////////////////////////////////////
916
917 use std::convert::From;
918 use std::fmt::{self, Debug};
919 use std::marker::{Send, Sync};
920 use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
921 use std::hash::{Hash, Hasher};
922 use std::borrow::Borrow;
923
924 impl<O, T: ?Sized> Deref for OwningRef<O, T> {
925     type Target = T;
926
927     fn deref(&self) -> &T {
928         unsafe {
929             &*self.reference
930         }
931     }
932 }
933
934 impl<O, T: ?Sized> Deref for OwningRefMut<O, T> {
935     type Target = T;
936
937     fn deref(&self) -> &T {
938         unsafe {
939             &*self.reference
940         }
941     }
942 }
943
944 impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> {
945     fn deref_mut(&mut self) -> &mut T {
946         unsafe {
947             &mut *self.reference
948         }
949     }
950 }
951
952 unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {}
953
954 impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> {
955     fn as_ref(&self) -> &T {
956         &*self
957     }
958 }
959
960 impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> {
961     fn as_ref(&self) -> &T {
962         &*self
963     }
964 }
965
966 impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> {
967     fn as_mut(&mut self) -> &mut T {
968         &mut *self
969     }
970 }
971
972 impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> {
973     fn borrow(&self) -> &T {
974         &*self
975     }
976 }
977
978 impl<O, T: ?Sized> From<O> for OwningRef<O, T>
979     where O: StableAddress,
980           O: Deref<Target = T>,
981 {
982     fn from(owner: O) -> Self {
983         OwningRef::new(owner)
984     }
985 }
986
987 impl<O, T: ?Sized> From<O> for OwningRefMut<O, T>
988     where O: StableAddress,
989           O: DerefMut<Target = T>
990 {
991     fn from(owner: O) -> Self {
992         OwningRefMut::new(owner)
993     }
994 }
995
996 impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T>
997     where O: StableAddress,
998           O: DerefMut<Target = T>
999 {
1000     fn from(other: OwningRefMut<O, T>) -> Self {
1001         OwningRef {
1002             owner: other.owner,
1003             reference: other.reference,
1004         }
1005     }
1006 }
1007
1008 // ^ FIXME: Is a Into impl for calling into_inner() possible as well?
1009
1010 impl<O, T: ?Sized> Debug for OwningRef<O, T>
1011     where O: Debug,
1012           T: Debug,
1013 {
1014     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1015         write!(f,
1016                "OwningRef {{ owner: {:?}, reference: {:?} }}",
1017                self.owner(),
1018                &**self)
1019     }
1020 }
1021
1022 impl<O, T: ?Sized> Debug for OwningRefMut<O, T>
1023     where O: Debug,
1024           T: Debug,
1025 {
1026     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027         write!(f,
1028                "OwningRefMut {{ owner: {:?}, reference: {:?} }}",
1029                self.owner(),
1030                &**self)
1031     }
1032 }
1033
1034 impl<O, T: ?Sized> Clone for OwningRef<O, T>
1035     where O: CloneStableAddress,
1036 {
1037     fn clone(&self) -> Self {
1038         OwningRef {
1039             owner: self.owner.clone(),
1040             reference: self.reference,
1041         }
1042     }
1043 }
1044
1045 unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
1046     where O: CloneStableAddress {}
1047
1048 unsafe impl<O, T: ?Sized> Send for OwningRef<O, T>
1049     where O: Send, for<'a> (&'a T): Send {}
1050 unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T>
1051     where O: Sync, for<'a> (&'a T): Sync {}
1052
1053 unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T>
1054     where O: Send, for<'a> (&'a mut T): Send {}
1055 unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T>
1056     where O: Sync, for<'a> (&'a mut T): Sync {}
1057
1058 impl Debug for dyn Erased {
1059     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1060         write!(f, "<Erased>",)
1061     }
1062 }
1063
1064 impl<O, T: ?Sized> PartialEq for OwningRef<O, T> where T: PartialEq {
1065     fn eq(&self, other: &Self) -> bool {
1066         (&*self as &T).eq(&*other as &T)
1067      }
1068 }
1069
1070 impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {}
1071
1072 impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> where T: PartialOrd {
1073     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1074         (&*self as &T).partial_cmp(&*other as &T)
1075     }
1076 }
1077
1078 impl<O, T: ?Sized> Ord for OwningRef<O, T> where T: Ord {
1079     fn cmp(&self, other: &Self) -> Ordering {
1080         (&*self as &T).cmp(&*other as &T)
1081     }
1082 }
1083
1084 impl<O, T: ?Sized> Hash for OwningRef<O, T> where T: Hash {
1085     fn hash<H: Hasher>(&self, state: &mut H) {
1086         (&*self as &T).hash(state);
1087     }
1088 }
1089
1090 impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> where T: PartialEq {
1091     fn eq(&self, other: &Self) -> bool {
1092         (&*self as &T).eq(&*other as &T)
1093      }
1094 }
1095
1096 impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {}
1097
1098 impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> where T: PartialOrd {
1099     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1100         (&*self as &T).partial_cmp(&*other as &T)
1101     }
1102 }
1103
1104 impl<O, T: ?Sized> Ord for OwningRefMut<O, T> where T: Ord {
1105     fn cmp(&self, other: &Self) -> Ordering {
1106         (&*self as &T).cmp(&*other as &T)
1107     }
1108 }
1109
1110 impl<O, T: ?Sized> Hash for OwningRefMut<O, T> where T: Hash {
1111     fn hash<H: Hasher>(&self, state: &mut H) {
1112         (&*self as &T).hash(state);
1113     }
1114 }
1115
1116 /////////////////////////////////////////////////////////////////////////////
1117 // std types integration and convenience type defs
1118 /////////////////////////////////////////////////////////////////////////////
1119
1120 use std::boxed::Box;
1121 use std::rc::Rc;
1122 use std::sync::Arc;
1123 use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
1124 use std::cell::{Ref, RefCell, RefMut};
1125
1126 impl<T: 'static> ToHandle for RefCell<T> {
1127     type Handle = Ref<'static, T>;
1128     unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() }
1129 }
1130
1131 impl<T: 'static> ToHandleMut for RefCell<T> {
1132     type HandleMut = RefMut<'static, T>;
1133     unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
1134 }
1135
1136 // N.B., implementing ToHandle{,Mut} for Mutex and RwLock requires a decision
1137 // about which handle creation to use (i.e., read() vs try_read()) as well as
1138 // what to do with error results.
1139
1140 /// Typedef of a owning reference that uses a `Box` as the owner.
1141 pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>;
1142 /// Typedef of a owning reference that uses a `Vec` as the owner.
1143 pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>;
1144 /// Typedef of a owning reference that uses a `String` as the owner.
1145 pub type StringRef = OwningRef<String, str>;
1146
1147 /// Typedef of a owning reference that uses a `Rc` as the owner.
1148 pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>;
1149 /// Typedef of a owning reference that uses a `Arc` as the owner.
1150 pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>;
1151
1152 /// Typedef of a owning reference that uses a `Ref` as the owner.
1153 pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>;
1154 /// Typedef of a owning reference that uses a `RefMut` as the owner.
1155 pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>;
1156 /// Typedef of a owning reference that uses a `MutexGuard` as the owner.
1157 pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>;
1158 /// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner.
1159 pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>;
1160 /// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner.
1161 pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
1162
1163 /// Typedef of a mutable owning reference that uses a `Box` as the owner.
1164 pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>;
1165 /// Typedef of a mutable owning reference that uses a `Vec` as the owner.
1166 pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>;
1167 /// Typedef of a mutable owning reference that uses a `String` as the owner.
1168 pub type StringRefMut = OwningRefMut<String, str>;
1169
1170 /// Typedef of a mutable owning reference that uses a `RefMut` as the owner.
1171 pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>;
1172 /// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner.
1173 pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>;
1174 /// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner.
1175 pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
1176
1177 unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> {
1178     type Erased = Box<dyn Erased + 'a>;
1179     fn into_erased(self) -> Self::Erased {
1180         self
1181     }
1182 }
1183 unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> {
1184     type Erased = Rc<dyn Erased + 'a>;
1185     fn into_erased(self) -> Self::Erased {
1186         self
1187     }
1188 }
1189 unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> {
1190     type Erased = Arc<dyn Erased + 'a>;
1191     fn into_erased(self) -> Self::Erased {
1192         self
1193     }
1194 }
1195
1196 unsafe impl<'a, T: Send + 'a> IntoErasedSend<'a> for Box<T> {
1197     type Erased = Box<dyn Erased + Send + 'a>;
1198     fn into_erased_send(self) -> Self::Erased {
1199         self
1200     }
1201 }
1202
1203 unsafe impl<'a, T: Send + 'a> IntoErasedSendSync<'a> for Box<T> {
1204     type Erased = Box<dyn Erased + Sync + Send + 'a>;
1205     fn into_erased_send_sync(self) -> Self::Erased {
1206         let result: Box<dyn Erased + Send + 'a> = self;
1207         // This is safe since Erased can always implement Sync
1208         // Only the destructor is available and it takes &mut self
1209         unsafe {
1210             mem::transmute(result)
1211         }
1212     }
1213 }
1214
1215 unsafe impl<'a, T: Send + Sync + 'a> IntoErasedSendSync<'a> for Arc<T> {
1216     type Erased = Arc<dyn Erased + Send + Sync + 'a>;
1217     fn into_erased_send_sync(self) -> Self::Erased {
1218         self
1219     }
1220 }
1221
1222 /// Typedef of a owning reference that uses an erased `Box` as the owner.
1223 pub type ErasedBoxRef<U> = OwningRef<Box<dyn Erased>, U>;
1224 /// Typedef of a owning reference that uses an erased `Rc` as the owner.
1225 pub type ErasedRcRef<U> = OwningRef<Rc<dyn Erased>, U>;
1226 /// Typedef of a owning reference that uses an erased `Arc` as the owner.
1227 pub type ErasedArcRef<U> = OwningRef<Arc<dyn Erased>, U>;
1228
1229 /// Typedef of a mutable owning reference that uses an erased `Box` as the owner.
1230 pub type ErasedBoxRefMut<U> = OwningRefMut<Box<dyn Erased>, U>;
1231
1232 #[cfg(test)]
1233 mod tests;