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.
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:
14 fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) {
15 let v = vec![1, 2, 3, 4];
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.
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:
29 # extern crate owning_ref;
30 # use owning_ref::OwningRef;
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]);
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.
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>`.
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.
58 extern crate owning_ref;
59 use owning_ref::BoxRef;
62 // Create an array owned by a Box.
63 let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>;
65 // Transfer into a BoxRef.
66 let arr: BoxRef<[i32]> = BoxRef::new(arr);
67 assert_eq!(&*arr, &[1, 2, 3, 4]);
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]);
73 // Also works for Arc, Rc, String and Vec!
77 ## Caching a reference to a struct field
80 extern crate owning_ref;
81 use owning_ref::BoxRef;
90 let foo = Foo { tag: 1, x: 100, y: 200, z: 300 };
92 let or = BoxRef::new(Box::new(foo)).map(|foo| {
101 assert_eq!(*or, 200);
105 ## Caching a reference to an entry in a vector
108 extern crate owning_ref;
109 use owning_ref::VecRef;
112 let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]);
117 ## Caching a subslice of a String
120 extern crate owning_ref;
121 use owning_ref::StringRef;
124 let s = StringRef::new("hello world".to_owned())
125 .map(|s| s.split(' ').nth(1).unwrap());
127 assert_eq!(&*s, "world");
131 ## Reference counted slices that share ownership of the backing storage
134 extern crate owning_ref;
135 use owning_ref::RcRef;
139 let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>);
140 assert_eq!(&*rc, &[1, 2, 3, 4]);
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]);
149 let rc_c_a = rc_c.clone().map(|s| &s[1]);
150 assert_eq!(&*rc_c_a, &4);
154 ## Atomic reference counted slices that share ownership of the backing storage
157 extern crate owning_ref;
158 use owning_ref::ArcRef;
164 fn par_sum(rc: ArcRef<[i32]>) -> i32 {
167 } else if rc.len() == 1 {
170 let mid = rc.len() / 2;
171 let left = rc.clone().map(|s| &s[..mid]);
172 let right = rc.map(|s| &s[mid..]);
174 let left = thread::spawn(move || par_sum(left));
175 let right = thread::spawn(move || par_sum(right));
177 left.join().unwrap() + right.join().unwrap()
180 let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]);
181 let rc: ArcRef<[i32]> = rc.into();
183 assert_eq!(par_sum(rc), 10);
187 ## References into RAII locks
190 extern crate owning_ref;
191 use owning_ref::RefRef;
192 use std::cell::{RefCell, Ref};
195 let refcell = RefCell::new((1, 2, 3, 4));
196 // Also works with Mutex and RwLock
199 let refref = RefRef::new(refcell.borrow()).map(|x| &x.3);
200 assert_eq!(*refref, 4);
202 // We move the RAII lock and the reference to one of
203 // the subfields in the data it guards here:
207 assert_eq!(*refref, 4);
211 assert_eq!(*refcell.borrow(), (1, 2, 3, 4));
217 When the owned container implements `DerefMut`, it is also possible to make
218 a _mutable owning reference_. (e.g., with `Box`, `RefMut`, `MutexGuard`)
221 extern crate owning_ref;
222 use owning_ref::RefMutRefMut;
223 use std::cell::{RefCell, RefMut};
226 let refcell = RefCell::new((1, 2, 3, 4));
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);
236 assert_eq!(*refmut_refmut, 8);
241 assert_eq!(*refcell.borrow(), (1, 2, 3, 16));
247 pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
249 /// An owning reference.
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.
255 /// The owner is usually a pointer that points at some base type.
257 /// For more details and examples, see the module and method docs.
258 pub struct OwningRef<O, T: ?Sized> {
263 /// An mutable owning reference.
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.
269 /// The owner is usually a pointer that points at some base type.
271 /// For more details and examples, see the module and method docs.
272 pub struct OwningRefMut<O, T: ?Sized> {
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.
281 impl<T> Erased for T {}
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`.
289 /// Performs the type erasure.
290 fn into_erased(self) -> Self::Erased;
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`.
299 /// Performs the type erasure.
300 fn into_erased_send(self) -> Self::Erased;
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 /// Performs the type erasure.
310 fn into_erased_send_sync(self) -> Self::Erased;
313 /////////////////////////////////////////////////////////////////////////////
315 /////////////////////////////////////////////////////////////////////////////
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.
323 /// extern crate owning_ref;
324 /// use owning_ref::OwningRef;
327 /// let owning_ref = OwningRef::new(Box::new(42));
328 /// assert_eq!(*owning_ref, 42);
331 pub fn new(o: O) -> Self
332 where O: StableAddress,
333 O: Deref<Target = T>,
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.
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>,
355 /// Converts `self` into a new owning reference that points at something reachable
356 /// from the previous one.
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.
363 /// extern crate owning_ref;
364 /// use owning_ref::OwningRef;
367 /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
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);
375 pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
376 where O: StableAddress,
385 /// Tries to convert `self` into a new owning reference that points
386 /// at something reachable from the previous one.
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.
393 /// extern crate owning_ref;
394 /// use owning_ref::OwningRef;
397 /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4]));
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(()) }
404 /// assert_eq!(*owning_ref.unwrap(), 3);
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>
412 reference: f(&self)?,
417 /// Converts `self` into a new owning reference with a different owner type.
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,
428 reference: self.reference,
429 owner: f(self.owner),
433 /// Converts `self` into a new owning reference where the owner is wrapped
434 /// in an additional `Box<O>`.
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> {
440 reference: self.reference,
441 owner: Box::new(self.owner),
445 /// Erases the concrete base type of the owner with a trait object.
447 /// This allows mixing of owned references with different owner base types.
451 /// extern crate owning_ref;
452 /// use owning_ref::{OwningRef, Erased};
455 /// // N.B., using the concrete types here for explicitness.
456 /// // For less verbose code type aliases like `BoxRef` are provided.
458 /// let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]>
459 /// = OwningRef::new(Box::new([1, 2, 3, 4]));
461 /// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
462 /// = OwningRef::new(Box::new(vec![(0, false), (1, true)]));
464 /// let owning_ref_a: OwningRef<Box<[i32; 4]>, i32>
465 /// = owning_ref_a.map(|a| &a[0]);
467 /// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, i32>
468 /// = owning_ref_b.map(|a| &a[1].0);
470 /// let owning_refs: [OwningRef<Box<Erased>, i32>; 2]
471 /// = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()];
473 /// assert_eq!(*owning_refs[0], 1);
474 /// assert_eq!(*owning_refs[1], 1);
477 pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T>
478 where O: IntoErased<'a>,
481 reference: self.reference,
482 owner: self.owner.into_erased(),
486 /// Erases the concrete base type of the owner with a trait object which implements `Send`.
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>,
493 reference: self.reference,
494 owner: self.owner.into_erased_send(),
498 /// Erases the concrete base type of the owner with a trait object which implements `Send` and `Sync`.
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>,
505 reference: self.reference,
506 owner: self.owner.into_erased_send_sync(),
512 // FIXME: Naming convention?
513 /// A getter for the underlying owner.
514 pub fn owner(&self) -> &O {
518 // FIXME: Naming convention?
519 /// Discards the reference and retrieves the owner.
520 pub fn into_inner(self) -> O {
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.
531 /// extern crate owning_ref;
532 /// use owning_ref::OwningRefMut;
535 /// let owning_ref_mut = OwningRefMut::new(Box::new(42));
536 /// assert_eq!(*owning_ref_mut, 42);
539 pub fn new(mut o: O) -> Self
540 where O: StableAddress,
541 O: DerefMut<Target = T>,
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.
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>,
563 /// Converts `self` into a new _shared_ owning reference that points at
564 /// something reachable from the previous one.
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.
571 /// extern crate owning_ref;
572 /// use owning_ref::OwningRefMut;
575 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
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);
583 pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U>
584 where O: StableAddress,
585 F: FnOnce(&mut T) -> &U
588 reference: f(&mut self),
593 /// Converts `self` into a new _mutable_ owning reference that points at
594 /// something reachable from the previous one.
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.
601 /// extern crate owning_ref;
602 /// use owning_ref::OwningRefMut;
605 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
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);
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
618 reference: f(&mut self),
623 /// Tries to convert `self` into a new _shared_ owning reference that points
624 /// at something reachable from the previous one.
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.
631 /// extern crate owning_ref;
632 /// use owning_ref::OwningRefMut;
635 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
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(()) }
642 /// assert_eq!(*owning_ref.unwrap(), 3);
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>
650 reference: f(&mut self)?,
655 /// Tries to convert `self` into a new _mutable_ owning reference that points
656 /// at something reachable from the previous one.
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.
663 /// extern crate owning_ref;
664 /// use owning_ref::OwningRefMut;
667 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4]));
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(()) }
674 /// assert_eq!(*owning_ref_mut.unwrap(), 3);
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>
682 reference: f(&mut self)?,
687 /// Converts `self` into a new owning reference with a different owner type.
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,
698 reference: self.reference,
699 owner: f(self.owner),
703 /// Converts `self` into a new owning reference where the owner is wrapped
704 /// in an additional `Box<O>`.
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> {
710 reference: self.reference,
711 owner: Box::new(self.owner),
715 /// Erases the concrete base type of the owner with a trait object.
717 /// This allows mixing of owned references with different owner base types.
721 /// extern crate owning_ref;
722 /// use owning_ref::{OwningRefMut, Erased};
725 /// // N.B., using the concrete types here for explicitness.
726 /// // For less verbose code type aliases like `BoxRef` are provided.
728 /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]>
729 /// = OwningRefMut::new(Box::new([1, 2, 3, 4]));
731 /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>>
732 /// = OwningRefMut::new(Box::new(vec![(0, false), (1, true)]));
734 /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32>
735 /// = owning_ref_mut_a.map_mut(|a| &mut a[0]);
737 /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32>
738 /// = owning_ref_mut_b.map_mut(|a| &mut a[1].0);
740 /// let owning_refs_mut: [OwningRefMut<Box<Erased>, i32>; 2]
741 /// = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()];
743 /// assert_eq!(*owning_refs_mut[0], 1);
744 /// assert_eq!(*owning_refs_mut[1], 1);
747 pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T>
748 where O: IntoErased<'a>,
751 reference: self.reference,
752 owner: self.owner.into_erased(),
758 // FIXME: Naming convention?
759 /// A getter for the underlying owner.
760 pub fn owner(&self) -> &O {
764 // FIXME: Naming convention?
765 /// Discards the reference and retrieves the owner.
766 pub fn into_inner(self) -> O {
771 /////////////////////////////////////////////////////////////////////////////
773 /////////////////////////////////////////////////////////////////////////////
775 use std::ops::{Deref, DerefMut};
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_.
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.
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.
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,
803 impl<O, H> Deref for OwningHandle<O, H>
804 where O: StableAddress, H: Deref,
806 type Target = H::Target;
807 fn deref(&self) -> &H::Target {
812 unsafe impl<O, H> StableAddress for OwningHandle<O, H>
813 where O: StableAddress, H: StableAddress,
816 impl<O, H> DerefMut for OwningHandle<O, H>
817 where O: StableAddress, H: DerefMut,
819 fn deref_mut(&mut self) -> &mut H::Target {
820 self.handle.deref_mut()
824 /// Trait to implement the conversion of owner to handle for common types.
826 /// The type of handle to be encapsulated by the OwningHandle.
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;
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;
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;
844 impl<O, H> OwningHandle<O, H>
845 where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref,
847 /// Creates 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) })
855 impl<O, H> OwningHandle<O, H>
856 where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
858 /// Creates 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) })
864 impl<O, H> OwningHandle<O, H>
865 where O: StableAddress, H: Deref,
867 /// Creates 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
871 pub fn new_with_fn<F>(o: O, f: F) -> Self
872 where F: FnOnce(*const O::Target) -> H
876 h = f(o.deref() as *const O::Target);
885 /// Creates 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
889 pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
890 where F: FnOnce(*const O::Target) -> Result<H, E>
894 h = f(o.deref() as *const O::Target)?;
904 /////////////////////////////////////////////////////////////////////////////
906 /////////////////////////////////////////////////////////////////////////////
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;
915 impl<O, T: ?Sized> Deref for OwningRef<O, T> {
918 fn deref(&self) -> &T {
925 impl<O, T: ?Sized> Deref for OwningRefMut<O, T> {
928 fn deref(&self) -> &T {
935 impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> {
936 fn deref_mut(&mut self) -> &mut T {
943 unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {}
945 impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> {
946 fn as_ref(&self) -> &T {
951 impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> {
952 fn as_ref(&self) -> &T {
957 impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> {
958 fn as_mut(&mut self) -> &mut T {
963 impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> {
964 fn borrow(&self) -> &T {
969 impl<O, T: ?Sized> From<O> for OwningRef<O, T>
970 where O: StableAddress,
971 O: Deref<Target = T>,
973 fn from(owner: O) -> Self {
974 OwningRef::new(owner)
978 impl<O, T: ?Sized> From<O> for OwningRefMut<O, T>
979 where O: StableAddress,
980 O: DerefMut<Target = T>
982 fn from(owner: O) -> Self {
983 OwningRefMut::new(owner)
987 impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T>
988 where O: StableAddress,
989 O: DerefMut<Target = T>
991 fn from(other: OwningRefMut<O, T>) -> Self {
994 reference: other.reference,
999 // ^ FIXME: Is a Into impl for calling into_inner() possible as well?
1001 impl<O, T: ?Sized> Debug for OwningRef<O, T>
1005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007 "OwningRef {{ owner: {:?}, reference: {:?} }}",
1013 impl<O, T: ?Sized> Debug for OwningRefMut<O, T>
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 "OwningRefMut {{ owner: {:?}, reference: {:?} }}",
1025 impl<O, T: ?Sized> Clone for OwningRef<O, T>
1026 where O: CloneStableAddress,
1028 fn clone(&self) -> Self {
1030 owner: self.owner.clone(),
1031 reference: self.reference,
1036 unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
1037 where O: CloneStableAddress {}
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 {}
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 {}
1049 impl Debug for dyn Erased {
1050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051 write!(f, "<Erased>",)
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)
1061 impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {}
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)
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)
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);
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)
1087 impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {}
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)
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)
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);
1107 /////////////////////////////////////////////////////////////////////////////
1108 // std types integration and convenience type defs
1109 /////////////////////////////////////////////////////////////////////////////
1111 use std::boxed::Box;
1114 use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
1115 use std::cell::{Ref, RefCell, RefMut};
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() }
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() }
1127 // N.B., 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.
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>;
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>;
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>;
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>;
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>;
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 {
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 {
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 {
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 {
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
1201 mem::transmute(result)
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 {
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>;
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>;