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