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