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 /// Perform 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 /// Perform 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 /// Perform 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 /// // NB: 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 /// // NB: 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 /// 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) })
855 impl<O, H> OwningHandle<O, H>
856 where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
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) })
864 impl<O, H> OwningHandle<O, H>
865 where O: StableAddress, H: Deref,
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
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 /// 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
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 // 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.
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>;
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;
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])
1242 let or: OwningRef<Box<()>, ()> = OwningRef::new(Box::new(()));
1243 assert_eq!(&*or, &());
1248 let or: OwningRef<Box<()>, ()> = Box::new(()).into();
1249 assert_eq!(&*or, &());
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);
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);
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");
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");
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");
1286 fn map_chained_inference() {
1287 let or = BoxRef::new(Box::new(example().1))
1290 assert_eq!(&*or, "el");
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");
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");
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\" }");
1320 let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example()))
1323 let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1))
1326 let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1327 assert!(os.iter().all(|e| &e[..] == "hello world"));
1332 use super::super::{RefRef, RefMutRef};
1333 use std::cell::RefCell;
1334 use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef};
1335 use std::sync::{Mutex, RwLock};
1338 let a = RefCell::new(1);
1340 let a = RefRef::new(a.borrow());
1348 let a = RefCell::new(1);
1350 let a = RefMutRef::new(a.borrow_mut());
1358 let a = Mutex::new(1);
1360 let a = MutexGuardRef::new(a.lock().unwrap());
1368 let a = RwLock::new(1);
1370 let a = RwLockReadGuardRef::new(a.read().unwrap());
1378 let a = RwLock::new(1);
1380 let a = RwLockWriteGuardRef::new(a.write().unwrap());
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);
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);
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));
1412 let mut h1 = DefaultHasher::new();
1413 let mut h2 = DefaultHasher::new();
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());
1421 assert_eq!(h1.finish(), h2.finish());
1426 let mut hash = HashMap::new();
1427 let key = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]);
1429 hash.insert(key.clone().map(|s| &s[..3]), 42);
1430 hash.insert(key.clone().map(|s| &s[4..]), 23);
1432 assert_eq!(hash.get("foo"), Some(&42));
1433 assert_eq!(hash.get("bar"), Some(&23));
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[..]);
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)};
1446 let e: OwningRef<Rc<dyn Erased>, [u8]> = c.erase_owner();
1447 let f: OwningRef<Rc<dyn Erased>, [u8]> = d.erase_owner();
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[..]);
1460 let c: OwningRef<Box<Vec<u8>>, [u8]> = a.map_owner_box();
1461 let d: OwningRef<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
1463 let _e: OwningRef<Box<dyn Erased>, [u8]> = c.erase_owner();
1464 let _f: OwningRef<Box<dyn Erased>, [u8]> = d.erase_owner();
1471 let x = Box::new(123_i32);
1472 let y: Box<dyn Any> = x;
1474 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok();
1481 let x = Box::new(123_i32);
1482 let y: Box<dyn Any> = x;
1484 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err();
1489 use super::super::OwningHandle;
1490 use super::super::RcRef;
1492 use std::cell::RefCell;
1494 use std::sync::RwLock;
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);
1504 assert_eq!(*handle, 3);
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| {
1515 }.unwrap().borrow_mut())
1517 assert_eq!(*handle, 2);
1519 assert_eq!(*handle, 3);
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| {
1531 }.unwrap().borrow_mut())
1535 assert!(handle.is_err());
1540 use std::cell::RefCell;
1541 use std::sync::{Arc, RwLock};
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";
1552 assert_eq!(*result, "someOtherString");
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);
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);
1572 assert_eq!(*handle, 3);
1576 fn owning_handle_safe_2() {
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";
1586 assert_eq!(*result, "someOtherString");
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;
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])
1606 let or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1607 assert_eq!(&*or, &());
1611 fn new_deref_mut() {
1612 let mut or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1613 assert_eq!(&mut *or, &mut ());
1618 let mut or: OwningRefMut<Box<usize>, usize> = OwningRefMut::new(Box::new(0));
1619 assert_eq!(&*or, &0);
1621 assert_eq!(&*or, &1);
1626 let or: OwningRefMut<Box<()>, ()> = Box::new(()).into();
1627 assert_eq!(&*or, &());
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);
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);
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");
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");
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);
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);
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");
1674 fn map_mut_static_ref() {
1675 static mut MUT_S: [u8; 5] = *b"hello";
1677 let mut_s: &'static mut [u8] = unsafe { &mut MUT_S };
1679 let or: BoxRefMut<()> = Box::new(()).into();
1680 let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s);
1681 assert_eq!(&*or, b"hello");
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");
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");
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");
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());
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");
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");
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);
1734 "OwningRefMut { owner: \"hello world\", reference: \"hello\" }");
1739 let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example()))
1740 .map_mut(|x| &mut x.1[..]);
1742 let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1))
1743 .map_mut(|x| &mut x[..]);
1745 let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1746 assert!(os.iter().all(|e| &e[..] == "hello world"));
1751 use super::super::RefMutRefMut;
1752 use std::cell::RefCell;
1753 use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut};
1754 use std::sync::{Mutex, RwLock};
1757 let a = RefCell::new(1);
1759 let a = RefMutRefMut::new(a.borrow_mut());
1767 let a = Mutex::new(1);
1769 let a = MutexGuardRefMut::new(a.lock().unwrap());
1777 let a = RwLock::new(1);
1779 let a = RwLockWriteGuardRefMut::new(a.write().unwrap());
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);
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);
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));
1811 let mut h1 = DefaultHasher::new();
1812 let mut h2 = DefaultHasher::new();
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());
1820 assert_eq!(h1.finish(), h2.finish());
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[..]);
1829 hash.insert(key1, 42);
1830 hash.insert(key2, 23);
1832 assert_eq!(hash.get("foo"), Some(&42));
1833 assert_eq!(hash.get("bar"), Some(&23));
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[..]);
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)};
1846 let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
1847 let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
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[..]);
1857 let c: OwningRefMut<Box<Vec<u8>>, [u8]> = a.map_owner_box();
1858 let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
1860 let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
1861 let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
1868 let x = Box::new(123_i32);
1869 let y: Box<dyn Any> = x;
1871 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_ok();
1878 let x = Box::new(123_i32);
1879 let y: Box<dyn Any> = x;
1881 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_err();
1888 let x = Box::new(123_i32);
1889 let y: Box<dyn Any> = x;
1891 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok();
1898 let x = Box::new(123_i32);
1899 let y: Box<dyn Any> = x;
1901 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err();
1905 fn into_owning_ref() {
1906 use super::super::BoxRef;
1908 let or: BoxRefMut<()> = Box::new(()).into();
1909 let or: BoxRef<()> = or.into();
1910 assert_eq!(&*or, &());
1922 use std::cell::RefCell;
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);
1928 let mut c = b.map_mut(|x| &mut x.f);
1929 assert_eq!(c.u, 43);
1931 let mut d = c.map_mut(|x| &mut x.u);