1 #![warn(missing_docs)] 2 3 /*! 4 # An owning reference. 5 6 This crate provides the _owning reference_ types `OwningRef` and `OwningRefMut` 7 that enables it to bundle a reference together with the owner of the data it points to. 8 This allows moving and dropping of a `OwningRef` without needing to recreate the reference. 9 10 This can sometimes be useful because Rust borrowing rules normally prevent 11 moving a type that has been moved from. For example, this kind of code gets rejected: 12 13 ```rust,ignore 14 fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) { 15 let v = vec![1, 2, 3, 4]; 16 let s = &v[1..3]; 17 (v, s) 18 } 19 ``` 20 21 Even though, from a memory-layout point of view, this can be entirely safe 22 if the new location of the vector still lives longer than the lifetime `'a` 23 of the reference because the backing allocation of the vector does not change. 24 25 This library enables this safe usage by keeping the owner and the reference 26 bundled together in a wrapper type that ensure that lifetime constraint: 27 28 ```rust 29 # extern crate owning_ref; 30 # use owning_ref::OwningRef; 31 # fn main() { 32 fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> { 33 let v = vec![1, 2, 3, 4]; 34 let or = OwningRef::new(v); 35 let or = or.map(|v| &v[1..3]); 36 or 37 } 38 # } 39 ``` 40 41 It works by requiring owner types to dereference to stable memory locations 42 and preventing mutable access to root containers, which in practice requires heap allocation 43 as provided by `Box<T>`, `Rc<T>`, etc. 44 45 Also provided are typedefs for common owner type combinations, 46 which allow for less verbose type signatures. For example, `BoxRef<T>` instead of `OwningRef<Box<T>, T>`. 47 48 The crate also provides the more advanced `OwningHandle` type, 49 which allows more freedom in bundling a dependent handle object 50 along with the data it depends on, at the cost of some unsafe needed in the API. 51 See the documentation around `OwningHandle` for more details. 52 53 # Examples 54 55 ## Basics 56 57 ``` 58 extern crate owning_ref; 59 use owning_ref::BoxRef; 60 61 fn 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 ``` 80 extern crate owning_ref; 81 use owning_ref::BoxRef; 82 83 fn 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 ``` 108 extern crate owning_ref; 109 use owning_ref::VecRef; 110 111 fn 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 ``` 120 extern crate owning_ref; 121 use owning_ref::StringRef; 122 123 fn 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 ``` 134 extern crate owning_ref; 135 use owning_ref::RcRef; 136 use std::rc::Rc; 137 138 fn 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 ``` 157 extern crate owning_ref; 158 use owning_ref::ArcRef; 159 use std::sync::Arc; 160 161 fn 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 ``` 190 extern crate owning_ref; 191 use owning_ref::RefRef; 192 use std::cell::{RefCell, Ref}; 193 194 fn 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 217 When the owned container implements `DerefMut`, it is also possible to make 218 a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`) 219 220 ``` 221 extern crate owning_ref; 222 use owning_ref::RefMutRefMut; 223 use std::cell::{RefCell, RefMut}; 224 225 fn 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 246 extern crate stable_deref_trait; 247 pub 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. 258 pub 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. 272 pub 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. 280 pub trait Erased {} 281 impl<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. 286 pub unsafe trait IntoErased<'a> { 287 /// Owner with the dereference type substituted to `Erased`. 288 type Erased; 289 /// Perform the type erasure. into_erased(self) -> Self::Erased290 fn into_erased(self) -> Self::Erased; 291 } 292 293 ///////////////////////////////////////////////////////////////////////////// 294 // OwningRef 295 ///////////////////////////////////////////////////////////////////////////// 296 297 impl<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 /// ``` new(o: O) -> Self where O: StableAddress, O: Deref<Target = T>,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. new_assert_stable_address(o: O) -> Self where O: Deref<Target = T>,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 /// ``` map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U> where O: StableAddress, F: FnOnce(&T) -> &U355 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 /// ``` try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E> where O: StableAddress, F: FnOnce(&T) -> Result<&U, E>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. map_owner<F, P>(self, f: F) -> OwningRef<P, T> where O: StableAddress, P: StableAddress, F: FnOnce(O) -> P402 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>`. map_owner_box(self) -> OwningRef<Box<O>, 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 /// ``` erase_owner<'a>(self) -> OwningRef<O::Erased, T> where O: IntoErased<'a>,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 /// A reference to the underlying owner. as_owner(&self) -> &O469 pub fn as_owner(&self) -> &O { 470 &self.owner 471 } 472 473 /// Discards the reference and retrieves the owner. into_owner(self) -> O474 pub fn into_owner(self) -> O { 475 self.owner 476 } 477 } 478 479 impl<O, T: ?Sized> OwningRefMut<O, T> { 480 /// Creates a new owning reference from a owner 481 /// initialized to the direct dereference of it. 482 /// 483 /// # Example 484 /// ``` 485 /// extern crate owning_ref; 486 /// use owning_ref::OwningRefMut; 487 /// 488 /// fn main() { 489 /// let owning_ref_mut = OwningRefMut::new(Box::new(42)); 490 /// assert_eq!(*owning_ref_mut, 42); 491 /// } 492 /// ``` new(mut o: O) -> Self where O: StableAddress, O: DerefMut<Target = T>,493 pub fn new(mut o: O) -> Self 494 where O: StableAddress, 495 O: DerefMut<Target = T>, 496 { 497 OwningRefMut { 498 reference: &mut *o, 499 owner: o, 500 } 501 } 502 503 /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait. 504 /// Instead, the caller is responsible to make the same promises as implementing the trait. 505 /// 506 /// This is useful for cases where coherence rules prevents implementing the trait 507 /// without adding a dependency to this crate in a third-party library. new_assert_stable_address(mut o: O) -> Self where O: DerefMut<Target = T>,508 pub unsafe fn new_assert_stable_address(mut o: O) -> Self 509 where O: DerefMut<Target = T>, 510 { 511 OwningRefMut { 512 reference: &mut *o, 513 owner: o, 514 } 515 } 516 517 /// Converts `self` into a new _shared_ owning reference that points at 518 /// something reachable from the previous one. 519 /// 520 /// This can be a reference to a field of `U`, something reachable from a field of 521 /// `U`, or even something unrelated with a `'static` lifetime. 522 /// 523 /// # Example 524 /// ``` 525 /// extern crate owning_ref; 526 /// use owning_ref::OwningRefMut; 527 /// 528 /// fn main() { 529 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); 530 /// 531 /// // create a owning reference that points at the 532 /// // third element of the array. 533 /// let owning_ref = owning_ref_mut.map(|array| &array[2]); 534 /// assert_eq!(*owning_ref, 3); 535 /// } 536 /// ``` map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U> where O: StableAddress, F: FnOnce(&mut T) -> &U537 pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U> 538 where O: StableAddress, 539 F: FnOnce(&mut T) -> &U 540 { 541 OwningRef { 542 reference: f(&mut self), 543 owner: self.owner, 544 } 545 } 546 547 /// Converts `self` into a new _mutable_ owning reference that points at 548 /// something reachable from the previous one. 549 /// 550 /// This can be a reference to a field of `U`, something reachable from a field of 551 /// `U`, or even something unrelated with a `'static` lifetime. 552 /// 553 /// # Example 554 /// ``` 555 /// extern crate owning_ref; 556 /// use owning_ref::OwningRefMut; 557 /// 558 /// fn main() { 559 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); 560 /// 561 /// // create a owning reference that points at the 562 /// // third element of the array. 563 /// let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]); 564 /// assert_eq!(*owning_ref_mut, 3); 565 /// } 566 /// ``` map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U> where O: StableAddress, F: FnOnce(&mut T) -> &mut U567 pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U> 568 where O: StableAddress, 569 F: FnOnce(&mut T) -> &mut U 570 { 571 OwningRefMut { 572 reference: f(&mut self), 573 owner: self.owner, 574 } 575 } 576 577 /// Tries to convert `self` into a new _shared_ owning reference that points 578 /// at something reachable from the previous one. 579 /// 580 /// This can be a reference to a field of `U`, something reachable from a field of 581 /// `U`, or even something unrelated with a `'static` lifetime. 582 /// 583 /// # Example 584 /// ``` 585 /// extern crate owning_ref; 586 /// use owning_ref::OwningRefMut; 587 /// 588 /// fn main() { 589 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); 590 /// 591 /// // create a owning reference that points at the 592 /// // third element of the array. 593 /// let owning_ref = owning_ref_mut.try_map(|array| { 594 /// if array[2] == 3 { Ok(&array[2]) } else { Err(()) } 595 /// }); 596 /// assert_eq!(*owning_ref.unwrap(), 3); 597 /// } 598 /// ``` try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E> where O: StableAddress, F: FnOnce(&mut T) -> Result<&U, E>599 pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E> 600 where O: StableAddress, 601 F: FnOnce(&mut T) -> Result<&U, E> 602 { 603 Ok(OwningRef { 604 reference: f(&mut self)?, 605 owner: self.owner, 606 }) 607 } 608 609 /// Tries to convert `self` into a new _mutable_ owning reference that points 610 /// at something reachable from the previous one. 611 /// 612 /// This can be a reference to a field of `U`, something reachable from a field of 613 /// `U`, or even something unrelated with a `'static` lifetime. 614 /// 615 /// # Example 616 /// ``` 617 /// extern crate owning_ref; 618 /// use owning_ref::OwningRefMut; 619 /// 620 /// fn main() { 621 /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); 622 /// 623 /// // create a owning reference that points at the 624 /// // third element of the array. 625 /// let owning_ref_mut = owning_ref_mut.try_map_mut(|array| { 626 /// if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) } 627 /// }); 628 /// assert_eq!(*owning_ref_mut.unwrap(), 3); 629 /// } 630 /// ``` try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E> where O: StableAddress, F: FnOnce(&mut T) -> Result<&mut U, E>631 pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E> 632 where O: StableAddress, 633 F: FnOnce(&mut T) -> Result<&mut U, E> 634 { 635 Ok(OwningRefMut { 636 reference: f(&mut self)?, 637 owner: self.owner, 638 }) 639 } 640 641 /// Converts `self` into a new owning reference with a different owner type. 642 /// 643 /// The new owner type needs to still contain the original owner in some way 644 /// so that the reference into it remains valid. This function is marked unsafe 645 /// because the user needs to manually uphold this guarantee. map_owner<F, P>(self, f: F) -> OwningRefMut<P, T> where O: StableAddress, P: StableAddress, F: FnOnce(O) -> P646 pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T> 647 where O: StableAddress, 648 P: StableAddress, 649 F: FnOnce(O) -> P 650 { 651 OwningRefMut { 652 reference: self.reference, 653 owner: f(self.owner), 654 } 655 } 656 657 /// Converts `self` into a new owning reference where the owner is wrapped 658 /// in an additional `Box<O>`. 659 /// 660 /// This can be used to safely erase the owner of any `OwningRefMut<O, T>` 661 /// to a `OwningRefMut<Box<Erased>, T>`. map_owner_box(self) -> OwningRefMut<Box<O>, T>662 pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> { 663 OwningRefMut { 664 reference: self.reference, 665 owner: Box::new(self.owner), 666 } 667 } 668 669 /// Erases the concrete base type of the owner with a trait object. 670 /// 671 /// This allows mixing of owned references with different owner base types. 672 /// 673 /// # Example 674 /// ``` 675 /// extern crate owning_ref; 676 /// use owning_ref::{OwningRefMut, Erased}; 677 /// 678 /// fn main() { 679 /// // NB: Using the concrete types here for explicitnes. 680 /// // For less verbose code type aliases like `BoxRef` are provided. 681 /// 682 /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]> 683 /// = OwningRefMut::new(Box::new([1, 2, 3, 4])); 684 /// 685 /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>> 686 /// = OwningRefMut::new(Box::new(vec![(0, false), (1, true)])); 687 /// 688 /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32> 689 /// = owning_ref_mut_a.map_mut(|a| &mut a[0]); 690 /// 691 /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32> 692 /// = owning_ref_mut_b.map_mut(|a| &mut a[1].0); 693 /// 694 /// let owning_refs_mut: [OwningRefMut<Box<Erased>, i32>; 2] 695 /// = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()]; 696 /// 697 /// assert_eq!(*owning_refs_mut[0], 1); 698 /// assert_eq!(*owning_refs_mut[1], 1); 699 /// } 700 /// ``` erase_owner<'a>(self) -> OwningRefMut<O::Erased, T> where O: IntoErased<'a>,701 pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T> 702 where O: IntoErased<'a>, 703 { 704 OwningRefMut { 705 reference: self.reference, 706 owner: self.owner.into_erased(), 707 } 708 } 709 710 // TODO: wrap_owner 711 712 /// A reference to the underlying owner. as_owner(&self) -> &O713 pub fn as_owner(&self) -> &O { 714 &self.owner 715 } 716 717 /// A mutable reference to the underlying owner. as_owner_mut(&mut self) -> &mut O718 pub fn as_owner_mut(&mut self) -> &mut O { 719 &mut self.owner 720 } 721 722 /// Discards the reference and retrieves the owner. into_owner(self) -> O723 pub fn into_owner(self) -> O { 724 self.owner 725 } 726 } 727 728 ///////////////////////////////////////////////////////////////////////////// 729 // OwningHandle 730 ///////////////////////////////////////////////////////////////////////////// 731 732 use std::ops::{Deref, DerefMut}; 733 734 /// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows 735 /// consumers to pass around an owned object and a dependent reference, 736 /// `OwningHandle` contains an owned object and a dependent _object_. 737 /// 738 /// `OwningHandle` can encapsulate a `RefMut` along with its associated 739 /// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`. 740 /// However, the API is completely generic and there are no restrictions on 741 /// what types of owning and dependent objects may be used. 742 /// 743 /// `OwningHandle` is created by passing an owner object (which dereferences 744 /// to a stable address) along with a callback which receives a pointer to 745 /// that stable location. The callback may then dereference the pointer and 746 /// mint a dependent object, with the guarantee that the returned object will 747 /// not outlive the referent of the pointer. 748 /// 749 /// Since the callback needs to dereference a raw pointer, it requires `unsafe` 750 /// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is 751 /// implemented for common data structures. Types that implement `ToHandle` can 752 /// be wrapped into an `OwningHandle` without passing a callback. 753 pub struct OwningHandle<O, H> 754 where O: StableAddress, H: Deref, 755 { 756 handle: H, 757 _owner: O, 758 } 759 760 impl<O, H> Deref for OwningHandle<O, H> 761 where O: StableAddress, H: Deref, 762 { 763 type Target = H::Target; deref(&self) -> &H::Target764 fn deref(&self) -> &H::Target { 765 self.handle.deref() 766 } 767 } 768 769 unsafe impl<O, H> StableAddress for OwningHandle<O, H> 770 where O: StableAddress, H: StableAddress, 771 {} 772 773 impl<O, H> DerefMut for OwningHandle<O, H> 774 where O: StableAddress, H: DerefMut, 775 { deref_mut(&mut self) -> &mut H::Target776 fn deref_mut(&mut self) -> &mut H::Target { 777 self.handle.deref_mut() 778 } 779 } 780 781 /// Trait to implement the conversion of owner to handle for common types. 782 pub trait ToHandle { 783 /// The type of handle to be encapsulated by the OwningHandle. 784 type Handle: Deref; 785 786 /// Given an appropriately-long-lived pointer to ourselves, create a 787 /// handle to be encapsulated by the `OwningHandle`. to_handle(x: *const Self) -> Self::Handle788 unsafe fn to_handle(x: *const Self) -> Self::Handle; 789 } 790 791 /// Trait to implement the conversion of owner to mutable handle for common types. 792 pub trait ToHandleMut { 793 /// The type of handle to be encapsulated by the OwningHandle. 794 type HandleMut: DerefMut; 795 796 /// Given an appropriately-long-lived pointer to ourselves, create a 797 /// mutable handle to be encapsulated by the `OwningHandle`. to_handle_mut(x: *const Self) -> Self::HandleMut798 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut; 799 } 800 801 impl<O, H> OwningHandle<O, H> 802 where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref, 803 { 804 /// Create a new `OwningHandle` for a type that implements `ToHandle`. For types 805 /// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts 806 /// a callback to perform the conversion. new(o: O) -> Self807 pub fn new(o: O) -> Self { 808 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) }) 809 } 810 } 811 812 impl<O, H> OwningHandle<O, H> 813 where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut, 814 { 815 /// Create a new mutable `OwningHandle` for a type that implements `ToHandleMut`. new_mut(o: O) -> Self816 pub fn new_mut(o: O) -> Self { 817 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) }) 818 } 819 } 820 821 impl<O, H> OwningHandle<O, H> 822 where O: StableAddress, H: Deref, 823 { 824 /// Create a new OwningHandle. The provided callback will be invoked with 825 /// a pointer to the object owned by `o`, and the returned value is stored 826 /// as the object to which this `OwningHandle` will forward `Deref` and 827 /// `DerefMut`. new_with_fn<F>(o: O, f: F) -> Self where F: FnOnce(*const O::Target) -> H828 pub fn new_with_fn<F>(o: O, f: F) -> Self 829 where F: FnOnce(*const O::Target) -> H 830 { 831 let h: H; 832 { 833 h = f(o.deref() as *const O::Target); 834 } 835 836 OwningHandle { 837 handle: h, 838 _owner: o, 839 } 840 } 841 842 /// Create a new OwningHandle. The provided callback will be invoked with 843 /// a pointer to the object owned by `o`, and the returned value is stored 844 /// as the object to which this `OwningHandle` will forward `Deref` and 845 /// `DerefMut`. try_new<F, E>(o: O, f: F) -> Result<Self, E> where F: FnOnce(*const O::Target) -> Result<H, E>846 pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E> 847 where F: FnOnce(*const O::Target) -> Result<H, E> 848 { 849 let h: H; 850 { 851 h = f(o.deref() as *const O::Target)?; 852 } 853 854 Ok(OwningHandle { 855 handle: h, 856 _owner: o, 857 }) 858 } 859 860 /// A getter for the underlying owner. as_owner(&self) -> &O861 pub fn as_owner(&self) -> &O { 862 &self._owner 863 } 864 865 /// Discards the dependent object and returns the owner. into_owner(self) -> O866 pub fn into_owner(self) -> O { 867 self._owner 868 } 869 } 870 871 ///////////////////////////////////////////////////////////////////////////// 872 // std traits 873 ///////////////////////////////////////////////////////////////////////////// 874 875 use std::convert::From; 876 use std::fmt::{self, Debug}; 877 use std::marker::{Send, Sync}; 878 use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering}; 879 use std::hash::{Hash, Hasher}; 880 use std::borrow::Borrow; 881 882 impl<O, T: ?Sized> Deref for OwningRef<O, T> { 883 type Target = T; 884 deref(&self) -> &T885 fn deref(&self) -> &T { 886 unsafe { 887 &*self.reference 888 } 889 } 890 } 891 892 impl<O, T: ?Sized> Deref for OwningRefMut<O, T> { 893 type Target = T; 894 deref(&self) -> &T895 fn deref(&self) -> &T { 896 unsafe { 897 &*self.reference 898 } 899 } 900 } 901 902 impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> { deref_mut(&mut self) -> &mut T903 fn deref_mut(&mut self) -> &mut T { 904 unsafe { 905 &mut *self.reference 906 } 907 } 908 } 909 910 unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {} 911 912 unsafe impl<O, T: ?Sized> StableAddress for OwningRefMut<O, T> {} 913 914 impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> { as_ref(&self) -> &T915 fn as_ref(&self) -> &T { 916 &*self 917 } 918 } 919 920 impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> { as_ref(&self) -> &T921 fn as_ref(&self) -> &T { 922 &*self 923 } 924 } 925 926 impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> { as_mut(&mut self) -> &mut T927 fn as_mut(&mut self) -> &mut T { 928 &mut *self 929 } 930 } 931 932 impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> { borrow(&self) -> &T933 fn borrow(&self) -> &T { 934 &*self 935 } 936 } 937 938 impl<O, T: ?Sized> From<O> for OwningRef<O, T> 939 where O: StableAddress, 940 O: Deref<Target = T>, 941 { from(owner: O) -> Self942 fn from(owner: O) -> Self { 943 OwningRef::new(owner) 944 } 945 } 946 947 impl<O, T: ?Sized> From<O> for OwningRefMut<O, T> 948 where O: StableAddress, 949 O: DerefMut<Target = T> 950 { from(owner: O) -> Self951 fn from(owner: O) -> Self { 952 OwningRefMut::new(owner) 953 } 954 } 955 956 impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T> 957 where O: StableAddress, 958 O: DerefMut<Target = T> 959 { from(other: OwningRefMut<O, T>) -> Self960 fn from(other: OwningRefMut<O, T>) -> Self { 961 OwningRef { 962 owner: other.owner, 963 reference: other.reference, 964 } 965 } 966 } 967 968 // ^ FIXME: Is a Into impl for calling into_owner() possible as well? 969 970 impl<O, T: ?Sized> Debug for OwningRef<O, T> 971 where O: Debug, 972 T: Debug, 973 { fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>974 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 975 write!(f, 976 "OwningRef {{ owner: {:?}, reference: {:?} }}", 977 self.as_owner(), 978 &**self) 979 } 980 } 981 982 impl<O, T: ?Sized> Debug for OwningRefMut<O, T> 983 where O: Debug, 984 T: Debug, 985 { fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>986 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 987 write!(f, 988 "OwningRefMut {{ owner: {:?}, reference: {:?} }}", 989 self.as_owner(), 990 &**self) 991 } 992 } 993 994 impl<O, T: ?Sized> Clone for OwningRef<O, T> 995 where O: CloneStableAddress, 996 { clone(&self) -> Self997 fn clone(&self) -> Self { 998 OwningRef { 999 owner: self.owner.clone(), 1000 reference: self.reference, 1001 } 1002 } 1003 } 1004 1005 unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T> 1006 where O: CloneStableAddress {} 1007 1008 unsafe impl<O, T: ?Sized> Send for OwningRef<O, T> 1009 where O: Send, for<'a> (&'a T): Send {} 1010 unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T> 1011 where O: Sync, for<'a> (&'a T): Sync {} 1012 1013 unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T> 1014 where O: Send, for<'a> (&'a mut T): Send {} 1015 unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T> 1016 where O: Sync, for<'a> (&'a mut T): Sync {} 1017 1018 impl Debug for Erased { fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>1019 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 1020 write!(f, "<Erased>",) 1021 } 1022 } 1023 1024 impl<O, T: ?Sized> PartialEq for OwningRef<O, T> where T: PartialEq { eq(&self, other: &Self) -> bool1025 fn eq(&self, other: &Self) -> bool { 1026 (&*self as &T).eq(&*other as &T) 1027 } 1028 } 1029 1030 impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {} 1031 1032 impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> where T: PartialOrd { partial_cmp(&self, other: &Self) -> Option<Ordering>1033 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 1034 (&*self as &T).partial_cmp(&*other as &T) 1035 } 1036 } 1037 1038 impl<O, T: ?Sized> Ord for OwningRef<O, T> where T: Ord { cmp(&self, other: &Self) -> Ordering1039 fn cmp(&self, other: &Self) -> Ordering { 1040 (&*self as &T).cmp(&*other as &T) 1041 } 1042 } 1043 1044 impl<O, T: ?Sized> Hash for OwningRef<O, T> where T: Hash { hash<H: Hasher>(&self, state: &mut H)1045 fn hash<H: Hasher>(&self, state: &mut H) { 1046 (&*self as &T).hash(state); 1047 } 1048 } 1049 1050 impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> where T: PartialEq { eq(&self, other: &Self) -> bool1051 fn eq(&self, other: &Self) -> bool { 1052 (&*self as &T).eq(&*other as &T) 1053 } 1054 } 1055 1056 impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {} 1057 1058 impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> where T: PartialOrd { partial_cmp(&self, other: &Self) -> Option<Ordering>1059 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 1060 (&*self as &T).partial_cmp(&*other as &T) 1061 } 1062 } 1063 1064 impl<O, T: ?Sized> Ord for OwningRefMut<O, T> where T: Ord { cmp(&self, other: &Self) -> Ordering1065 fn cmp(&self, other: &Self) -> Ordering { 1066 (&*self as &T).cmp(&*other as &T) 1067 } 1068 } 1069 1070 impl<O, T: ?Sized> Hash for OwningRefMut<O, T> where T: Hash { hash<H: Hasher>(&self, state: &mut H)1071 fn hash<H: Hasher>(&self, state: &mut H) { 1072 (&*self as &T).hash(state); 1073 } 1074 } 1075 1076 ///////////////////////////////////////////////////////////////////////////// 1077 // std types integration and convenience type defs 1078 ///////////////////////////////////////////////////////////////////////////// 1079 1080 use std::boxed::Box; 1081 use std::rc::Rc; 1082 use std::sync::Arc; 1083 use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; 1084 use std::cell::{Ref, RefCell, RefMut}; 1085 1086 impl<T: 'static> ToHandle for RefCell<T> { 1087 type Handle = Ref<'static, T>; to_handle(x: *const Self) -> Self::Handle1088 unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() } 1089 } 1090 1091 impl<T: 'static> ToHandleMut for RefCell<T> { 1092 type HandleMut = RefMut<'static, T>; to_handle_mut(x: *const Self) -> Self::HandleMut1093 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() } 1094 } 1095 1096 // NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision 1097 // about which handle creation to use (i.e. read() vs try_read()) as well as 1098 // what to do with error results. 1099 1100 /// Typedef of a owning reference that uses a `Box` as the owner. 1101 pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>; 1102 /// Typedef of a owning reference that uses a `Vec` as the owner. 1103 pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>; 1104 /// Typedef of a owning reference that uses a `String` as the owner. 1105 pub type StringRef = OwningRef<String, str>; 1106 1107 /// Typedef of a owning reference that uses a `Rc` as the owner. 1108 pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>; 1109 /// Typedef of a owning reference that uses a `Arc` as the owner. 1110 pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>; 1111 1112 /// Typedef of a owning reference that uses a `Ref` as the owner. 1113 pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>; 1114 /// Typedef of a owning reference that uses a `RefMut` as the owner. 1115 pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>; 1116 /// Typedef of a owning reference that uses a `MutexGuard` as the owner. 1117 pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>; 1118 /// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner. 1119 pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>; 1120 /// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner. 1121 pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>; 1122 1123 /// Typedef of a mutable owning reference that uses a `Box` as the owner. 1124 pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>; 1125 /// Typedef of a mutable owning reference that uses a `Vec` as the owner. 1126 pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>; 1127 /// Typedef of a mutable owning reference that uses a `String` as the owner. 1128 pub type StringRefMut = OwningRefMut<String, str>; 1129 1130 /// Typedef of a mutable owning reference that uses a `RefMut` as the owner. 1131 pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>; 1132 /// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner. 1133 pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>; 1134 /// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner. 1135 pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRefMut<RwLockWriteGuard<'a, T>, U>; 1136 1137 unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> { 1138 type Erased = Box<Erased + 'a>; into_erased(self) -> Self::Erased1139 fn into_erased(self) -> Self::Erased { 1140 self 1141 } 1142 } 1143 unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> { 1144 type Erased = Rc<Erased + 'a>; into_erased(self) -> Self::Erased1145 fn into_erased(self) -> Self::Erased { 1146 self 1147 } 1148 } 1149 unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> { 1150 type Erased = Arc<Erased + 'a>; into_erased(self) -> Self::Erased1151 fn into_erased(self) -> Self::Erased { 1152 self 1153 } 1154 } 1155 1156 /// Typedef of a owning reference that uses an erased `Box` as the owner. 1157 pub type ErasedBoxRef<U> = OwningRef<Box<Erased>, U>; 1158 /// Typedef of a owning reference that uses an erased `Rc` as the owner. 1159 pub type ErasedRcRef<U> = OwningRef<Rc<Erased>, U>; 1160 /// Typedef of a owning reference that uses an erased `Arc` as the owner. 1161 pub type ErasedArcRef<U> = OwningRef<Arc<Erased>, U>; 1162 1163 /// Typedef of a mutable owning reference that uses an erased `Box` as the owner. 1164 pub type ErasedBoxRefMut<U> = OwningRefMut<Box<Erased>, U>; 1165 1166 #[cfg(test)] 1167 mod tests { 1168 mod owning_ref { 1169 use super::super::OwningRef; 1170 use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef}; 1171 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering}; 1172 use std::hash::{Hash, Hasher}; 1173 use std::collections::hash_map::DefaultHasher; 1174 use std::collections::HashMap; 1175 use std::rc::Rc; 1176 1177 #[derive(Debug, PartialEq)] 1178 struct Example(u32, String, [u8; 3]); example() -> Example1179 fn example() -> Example { 1180 Example(42, "hello world".to_string(), [1, 2, 3]) 1181 } 1182 1183 #[test] new_deref()1184 fn new_deref() { 1185 let or: OwningRef<Box<()>, ()> = OwningRef::new(Box::new(())); 1186 assert_eq!(&*or, &()); 1187 } 1188 1189 #[test] into()1190 fn into() { 1191 let or: OwningRef<Box<()>, ()> = Box::new(()).into(); 1192 assert_eq!(&*or, &()); 1193 } 1194 1195 #[test] map_offset_ref()1196 fn map_offset_ref() { 1197 let or: BoxRef<Example> = Box::new(example()).into(); 1198 let or: BoxRef<_, u32> = or.map(|x| &x.0); 1199 assert_eq!(&*or, &42); 1200 1201 let or: BoxRef<Example> = Box::new(example()).into(); 1202 let or: BoxRef<_, u8> = or.map(|x| &x.2[1]); 1203 assert_eq!(&*or, &2); 1204 } 1205 1206 #[test] map_heap_ref()1207 fn map_heap_ref() { 1208 let or: BoxRef<Example> = Box::new(example()).into(); 1209 let or: BoxRef<_, str> = or.map(|x| &x.1[..5]); 1210 assert_eq!(&*or, "hello"); 1211 } 1212 1213 #[test] map_static_ref()1214 fn map_static_ref() { 1215 let or: BoxRef<()> = Box::new(()).into(); 1216 let or: BoxRef<_, str> = or.map(|_| "hello"); 1217 assert_eq!(&*or, "hello"); 1218 } 1219 1220 #[test] map_chained()1221 fn map_chained() { 1222 let or: BoxRef<String> = Box::new(example().1).into(); 1223 let or: BoxRef<_, str> = or.map(|x| &x[1..5]); 1224 let or: BoxRef<_, str> = or.map(|x| &x[..2]); 1225 assert_eq!(&*or, "el"); 1226 } 1227 1228 #[test] map_chained_inference()1229 fn map_chained_inference() { 1230 let or = BoxRef::new(Box::new(example().1)) 1231 .map(|x| &x[..5]) 1232 .map(|x| &x[1..3]); 1233 assert_eq!(&*or, "el"); 1234 } 1235 1236 #[test] as_owner()1237 fn as_owner() { 1238 let or: BoxRef<String> = Box::new(example().1).into(); 1239 let or = or.map(|x| &x[..5]); 1240 assert_eq!(&*or, "hello"); 1241 assert_eq!(&**or.as_owner(), "hello world"); 1242 } 1243 1244 #[test] into_owner()1245 fn into_owner() { 1246 let or: BoxRef<String> = Box::new(example().1).into(); 1247 let or = or.map(|x| &x[..5]); 1248 assert_eq!(&*or, "hello"); 1249 let s = *or.into_owner(); 1250 assert_eq!(&s, "hello world"); 1251 } 1252 1253 #[test] fmt_debug()1254 fn fmt_debug() { 1255 let or: BoxRef<String> = Box::new(example().1).into(); 1256 let or = or.map(|x| &x[..5]); 1257 let s = format!("{:?}", or); 1258 assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }"); 1259 } 1260 1261 #[test] erased_owner()1262 fn erased_owner() { 1263 let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example())) 1264 .map(|x| &x.1[..]); 1265 1266 let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1)) 1267 .map(|x| &x[..]); 1268 1269 let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()]; 1270 assert!(os.iter().all(|e| &e[..] == "hello world")); 1271 } 1272 1273 #[test] non_static_erased_owner()1274 fn non_static_erased_owner() { 1275 let foo = [413, 612]; 1276 let bar = &foo; 1277 1278 // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure 1279 // (see https://github.com/rust-lang/rust/issues/22340) 1280 // So we use a function to identify the lifetimes instead. 1281 fn borrow<'a>(a: &'a &[i32; 2]) -> &'a i32 { 1282 &a[0] 1283 } 1284 1285 let o: BoxRef<&[i32; 2]> = Box::new(bar).into(); 1286 let o: BoxRef<&[i32; 2], i32> = o.map(borrow); 1287 let o: BoxRef<Erased, i32> = o.erase_owner(); 1288 1289 assert_eq!(*o, 413); 1290 } 1291 1292 #[test] raii_locks()1293 fn raii_locks() { 1294 use super::super::{RefRef, RefMutRef}; 1295 use std::cell::RefCell; 1296 use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef}; 1297 use std::sync::{Mutex, RwLock}; 1298 1299 { 1300 let a = RefCell::new(1); 1301 let a = { 1302 let a = RefRef::new(a.borrow()); 1303 assert_eq!(*a, 1); 1304 a 1305 }; 1306 assert_eq!(*a, 1); 1307 drop(a); 1308 } 1309 { 1310 let a = RefCell::new(1); 1311 let a = { 1312 let a = RefMutRef::new(a.borrow_mut()); 1313 assert_eq!(*a, 1); 1314 a 1315 }; 1316 assert_eq!(*a, 1); 1317 drop(a); 1318 } 1319 { 1320 let a = Mutex::new(1); 1321 let a = { 1322 let a = MutexGuardRef::new(a.lock().unwrap()); 1323 assert_eq!(*a, 1); 1324 a 1325 }; 1326 assert_eq!(*a, 1); 1327 drop(a); 1328 } 1329 { 1330 let a = RwLock::new(1); 1331 let a = { 1332 let a = RwLockReadGuardRef::new(a.read().unwrap()); 1333 assert_eq!(*a, 1); 1334 a 1335 }; 1336 assert_eq!(*a, 1); 1337 drop(a); 1338 } 1339 { 1340 let a = RwLock::new(1); 1341 let a = { 1342 let a = RwLockWriteGuardRef::new(a.write().unwrap()); 1343 assert_eq!(*a, 1); 1344 a 1345 }; 1346 assert_eq!(*a, 1); 1347 drop(a); 1348 } 1349 } 1350 1351 #[test] eq()1352 fn eq() { 1353 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1354 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1355 assert_eq!(or1.eq(&or2), true); 1356 } 1357 1358 #[test] cmp()1359 fn cmp() { 1360 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1361 let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice()); 1362 assert_eq!(or1.cmp(&or2), Ordering::Less); 1363 } 1364 1365 #[test] partial_cmp()1366 fn partial_cmp() { 1367 let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice()); 1368 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1369 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater)); 1370 } 1371 1372 #[test] hash()1373 fn hash() { 1374 let mut h1 = DefaultHasher::new(); 1375 let mut h2 = DefaultHasher::new(); 1376 1377 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1378 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); 1379 1380 or1.hash(&mut h1); 1381 or2.hash(&mut h2); 1382 1383 assert_eq!(h1.finish(), h2.finish()); 1384 } 1385 1386 #[test] borrow()1387 fn borrow() { 1388 let mut hash = HashMap::new(); 1389 let key = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]); 1390 1391 hash.insert(key.clone().map(|s| &s[..3]), 42); 1392 hash.insert(key.clone().map(|s| &s[4..]), 23); 1393 1394 assert_eq!(hash.get("foo"), Some(&42)); 1395 assert_eq!(hash.get("bar"), Some(&23)); 1396 } 1397 1398 #[test] total_erase()1399 fn total_erase() { 1400 let a: OwningRef<Vec<u8>, [u8]> 1401 = OwningRef::new(vec![]).map(|x| &x[..]); 1402 let b: OwningRef<Box<[u8]>, [u8]> 1403 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]); 1404 1405 let c: OwningRef<Rc<Vec<u8>>, [u8]> = unsafe {a.map_owner(Rc::new)}; 1406 let d: OwningRef<Rc<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Rc::new)}; 1407 1408 let e: OwningRef<Rc<Erased>, [u8]> = c.erase_owner(); 1409 let f: OwningRef<Rc<Erased>, [u8]> = d.erase_owner(); 1410 1411 let _g = e.clone(); 1412 let _h = f.clone(); 1413 } 1414 1415 #[test] total_erase_box()1416 fn total_erase_box() { 1417 let a: OwningRef<Vec<u8>, [u8]> 1418 = OwningRef::new(vec![]).map(|x| &x[..]); 1419 let b: OwningRef<Box<[u8]>, [u8]> 1420 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]); 1421 1422 let c: OwningRef<Box<Vec<u8>>, [u8]> = a.map_owner_box(); 1423 let d: OwningRef<Box<Box<[u8]>>, [u8]> = b.map_owner_box(); 1424 1425 let _e: OwningRef<Box<Erased>, [u8]> = c.erase_owner(); 1426 let _f: OwningRef<Box<Erased>, [u8]> = d.erase_owner(); 1427 } 1428 1429 #[test] try_map1()1430 fn try_map1() { 1431 use std::any::Any; 1432 1433 let x = Box::new(123_i32); 1434 let y: Box<Any> = x; 1435 1436 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok(); 1437 } 1438 1439 #[test] try_map2()1440 fn try_map2() { 1441 use std::any::Any; 1442 1443 let x = Box::new(123_i32); 1444 let y: Box<Any> = x; 1445 1446 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err(); 1447 } 1448 } 1449 1450 mod owning_handle { 1451 use super::super::OwningHandle; 1452 use super::super::RcRef; 1453 use std::rc::Rc; 1454 use std::cell::RefCell; 1455 use std::sync::Arc; 1456 use std::sync::RwLock; 1457 1458 #[test] owning_handle()1459 fn owning_handle() { 1460 use std::cell::RefCell; 1461 let cell = Rc::new(RefCell::new(2)); 1462 let cell_ref = RcRef::new(cell); 1463 let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); 1464 assert_eq!(*handle, 2); 1465 *handle = 3; 1466 assert_eq!(*handle, 3); 1467 } 1468 1469 #[test] try_owning_handle_ok()1470 fn try_owning_handle_ok() { 1471 use std::cell::RefCell; 1472 let cell = Rc::new(RefCell::new(2)); 1473 let cell_ref = RcRef::new(cell); 1474 let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| { 1475 Ok(unsafe { 1476 x.as_ref() 1477 }.unwrap().borrow_mut()) 1478 }).unwrap(); 1479 assert_eq!(*handle, 2); 1480 *handle = 3; 1481 assert_eq!(*handle, 3); 1482 } 1483 1484 #[test] try_owning_handle_err()1485 fn try_owning_handle_err() { 1486 use std::cell::RefCell; 1487 let cell = Rc::new(RefCell::new(2)); 1488 let cell_ref = RcRef::new(cell); 1489 let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| { 1490 if false { 1491 return Ok(unsafe { 1492 x.as_ref() 1493 }.unwrap().borrow_mut()) 1494 } 1495 Err(()) 1496 }); 1497 assert!(handle.is_err()); 1498 } 1499 1500 #[test] nested()1501 fn nested() { 1502 use std::cell::RefCell; 1503 use std::sync::{Arc, RwLock}; 1504 1505 let result = { 1506 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString")))); 1507 let curr = RcRef::new(complex); 1508 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); 1509 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap()); 1510 assert_eq!(*curr, "someString"); 1511 *curr = "someOtherString"; 1512 curr 1513 }; 1514 assert_eq!(*result, "someOtherString"); 1515 } 1516 1517 #[test] owning_handle_safe()1518 fn owning_handle_safe() { 1519 use std::cell::RefCell; 1520 let cell = Rc::new(RefCell::new(2)); 1521 let cell_ref = RcRef::new(cell); 1522 let handle = OwningHandle::new(cell_ref); 1523 assert_eq!(*handle, 2); 1524 } 1525 1526 #[test] owning_handle_mut_safe()1527 fn owning_handle_mut_safe() { 1528 use std::cell::RefCell; 1529 let cell = Rc::new(RefCell::new(2)); 1530 let cell_ref = RcRef::new(cell); 1531 let mut handle = OwningHandle::new_mut(cell_ref); 1532 assert_eq!(*handle, 2); 1533 *handle = 3; 1534 assert_eq!(*handle, 3); 1535 } 1536 1537 #[test] owning_handle_safe_2()1538 fn owning_handle_safe_2() { 1539 let result = { 1540 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString")))); 1541 let curr = RcRef::new(complex); 1542 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); 1543 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap()); 1544 assert_eq!(*curr, "someString"); 1545 *curr = "someOtherString"; 1546 curr 1547 }; 1548 assert_eq!(*result, "someOtherString"); 1549 } 1550 } 1551 1552 mod owning_ref_mut { 1553 use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut}; 1554 use super::super::BoxRef; 1555 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering}; 1556 use std::hash::{Hash, Hasher}; 1557 use std::collections::hash_map::DefaultHasher; 1558 use std::collections::HashMap; 1559 1560 #[derive(Debug, PartialEq)] 1561 struct Example(u32, String, [u8; 3]); example() -> Example1562 fn example() -> Example { 1563 Example(42, "hello world".to_string(), [1, 2, 3]) 1564 } 1565 1566 #[test] new_deref()1567 fn new_deref() { 1568 let or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(())); 1569 assert_eq!(&*or, &()); 1570 } 1571 1572 #[test] new_deref_mut()1573 fn new_deref_mut() { 1574 let mut or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(())); 1575 assert_eq!(&mut *or, &mut ()); 1576 } 1577 1578 #[test] mutate()1579 fn mutate() { 1580 let mut or: OwningRefMut<Box<usize>, usize> = OwningRefMut::new(Box::new(0)); 1581 assert_eq!(&*or, &0); 1582 *or = 1; 1583 assert_eq!(&*or, &1); 1584 } 1585 1586 #[test] into()1587 fn into() { 1588 let or: OwningRefMut<Box<()>, ()> = Box::new(()).into(); 1589 assert_eq!(&*or, &()); 1590 } 1591 1592 #[test] map_offset_ref()1593 fn map_offset_ref() { 1594 let or: BoxRefMut<Example> = Box::new(example()).into(); 1595 let or: BoxRef<_, u32> = or.map(|x| &mut x.0); 1596 assert_eq!(&*or, &42); 1597 1598 let or: BoxRefMut<Example> = Box::new(example()).into(); 1599 let or: BoxRef<_, u8> = or.map(|x| &mut x.2[1]); 1600 assert_eq!(&*or, &2); 1601 } 1602 1603 #[test] map_heap_ref()1604 fn map_heap_ref() { 1605 let or: BoxRefMut<Example> = Box::new(example()).into(); 1606 let or: BoxRef<_, str> = or.map(|x| &mut x.1[..5]); 1607 assert_eq!(&*or, "hello"); 1608 } 1609 1610 #[test] map_static_ref()1611 fn map_static_ref() { 1612 let or: BoxRefMut<()> = Box::new(()).into(); 1613 let or: BoxRef<_, str> = or.map(|_| "hello"); 1614 assert_eq!(&*or, "hello"); 1615 } 1616 1617 #[test] map_mut_offset_ref()1618 fn map_mut_offset_ref() { 1619 let or: BoxRefMut<Example> = Box::new(example()).into(); 1620 let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0); 1621 assert_eq!(&*or, &42); 1622 1623 let or: BoxRefMut<Example> = Box::new(example()).into(); 1624 let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]); 1625 assert_eq!(&*or, &2); 1626 } 1627 1628 #[test] map_mut_heap_ref()1629 fn map_mut_heap_ref() { 1630 let or: BoxRefMut<Example> = Box::new(example()).into(); 1631 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]); 1632 assert_eq!(&*or, "hello"); 1633 } 1634 1635 #[test] map_mut_static_ref()1636 fn map_mut_static_ref() { 1637 static mut MUT_S: [u8; 5] = *b"hello"; 1638 1639 let mut_s: &'static mut [u8] = unsafe { &mut MUT_S }; 1640 1641 let or: BoxRefMut<()> = Box::new(()).into(); 1642 let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s); 1643 assert_eq!(&*or, b"hello"); 1644 } 1645 1646 #[test] map_mut_chained()1647 fn map_mut_chained() { 1648 let or: BoxRefMut<String> = Box::new(example().1).into(); 1649 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]); 1650 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]); 1651 assert_eq!(&*or, "el"); 1652 } 1653 1654 #[test] map_chained_inference()1655 fn map_chained_inference() { 1656 let or = BoxRefMut::new(Box::new(example().1)) 1657 .map_mut(|x| &mut x[..5]) 1658 .map_mut(|x| &mut x[1..3]); 1659 assert_eq!(&*or, "el"); 1660 } 1661 1662 #[test] try_map_mut()1663 fn try_map_mut() { 1664 let or: BoxRefMut<String> = Box::new(example().1).into(); 1665 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|x| Ok(&mut x[1..5])); 1666 assert_eq!(&*or.unwrap(), "ello"); 1667 1668 let or: BoxRefMut<String> = Box::new(example().1).into(); 1669 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|_| Err(())); 1670 assert!(or.is_err()); 1671 } 1672 1673 #[test] as_owner()1674 fn as_owner() { 1675 let or: BoxRefMut<String> = Box::new(example().1).into(); 1676 let or = or.map_mut(|x| &mut x[..5]); 1677 assert_eq!(&*or, "hello"); 1678 assert_eq!(&**or.as_owner(), "hello world"); 1679 } 1680 1681 #[test] into_owner()1682 fn into_owner() { 1683 let or: BoxRefMut<String> = Box::new(example().1).into(); 1684 let or = or.map_mut(|x| &mut x[..5]); 1685 assert_eq!(&*or, "hello"); 1686 let s = *or.into_owner(); 1687 assert_eq!(&s, "hello world"); 1688 } 1689 1690 #[test] fmt_debug()1691 fn fmt_debug() { 1692 let or: BoxRefMut<String> = Box::new(example().1).into(); 1693 let or = or.map_mut(|x| &mut x[..5]); 1694 let s = format!("{:?}", or); 1695 assert_eq!(&s, 1696 "OwningRefMut { owner: \"hello world\", reference: \"hello\" }"); 1697 } 1698 1699 #[test] erased_owner()1700 fn erased_owner() { 1701 let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example())) 1702 .map_mut(|x| &mut x.1[..]); 1703 1704 let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1)) 1705 .map_mut(|x| &mut x[..]); 1706 1707 let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()]; 1708 assert!(os.iter().all(|e| &e[..] == "hello world")); 1709 } 1710 1711 #[test] non_static_erased_owner()1712 fn non_static_erased_owner() { 1713 let mut foo = [413, 612]; 1714 let bar = &mut foo; 1715 1716 // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure 1717 // (see https://github.com/rust-lang/rust/issues/22340) 1718 // So we use a function to identify the lifetimes instead. 1719 fn borrow<'a>(a: &'a mut &mut [i32; 2]) -> &'a mut i32 { 1720 &mut a[0] 1721 } 1722 1723 let o: BoxRefMut<&mut [i32; 2]> = Box::new(bar).into(); 1724 let o: BoxRefMut<&mut [i32; 2], i32> = o.map_mut(borrow); 1725 let o: BoxRefMut<Erased, i32> = o.erase_owner(); 1726 1727 assert_eq!(*o, 413); 1728 } 1729 1730 #[test] raii_locks()1731 fn raii_locks() { 1732 use super::super::RefMutRefMut; 1733 use std::cell::RefCell; 1734 use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut}; 1735 use std::sync::{Mutex, RwLock}; 1736 1737 { 1738 let a = RefCell::new(1); 1739 let a = { 1740 let a = RefMutRefMut::new(a.borrow_mut()); 1741 assert_eq!(*a, 1); 1742 a 1743 }; 1744 assert_eq!(*a, 1); 1745 drop(a); 1746 } 1747 { 1748 let a = Mutex::new(1); 1749 let a = { 1750 let a = MutexGuardRefMut::new(a.lock().unwrap()); 1751 assert_eq!(*a, 1); 1752 a 1753 }; 1754 assert_eq!(*a, 1); 1755 drop(a); 1756 } 1757 { 1758 let a = RwLock::new(1); 1759 let a = { 1760 let a = RwLockWriteGuardRefMut::new(a.write().unwrap()); 1761 assert_eq!(*a, 1); 1762 a 1763 }; 1764 assert_eq!(*a, 1); 1765 drop(a); 1766 } 1767 } 1768 1769 #[test] eq()1770 fn eq() { 1771 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1772 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1773 assert_eq!(or1.eq(&or2), true); 1774 } 1775 1776 #[test] cmp()1777 fn cmp() { 1778 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1779 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice()); 1780 assert_eq!(or1.cmp(&or2), Ordering::Less); 1781 } 1782 1783 #[test] partial_cmp()1784 fn partial_cmp() { 1785 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice()); 1786 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1787 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater)); 1788 } 1789 1790 #[test] hash()1791 fn hash() { 1792 let mut h1 = DefaultHasher::new(); 1793 let mut h2 = DefaultHasher::new(); 1794 1795 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1796 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); 1797 1798 or1.hash(&mut h1); 1799 or2.hash(&mut h2); 1800 1801 assert_eq!(h1.finish(), h2.finish()); 1802 } 1803 1804 #[test] borrow()1805 fn borrow() { 1806 let mut hash = HashMap::new(); 1807 let key1 = BoxRefMut::<String>::new(Box::new("foo".to_string())).map(|s| &s[..]); 1808 let key2 = BoxRefMut::<String>::new(Box::new("bar".to_string())).map(|s| &s[..]); 1809 1810 hash.insert(key1, 42); 1811 hash.insert(key2, 23); 1812 1813 assert_eq!(hash.get("foo"), Some(&42)); 1814 assert_eq!(hash.get("bar"), Some(&23)); 1815 } 1816 1817 #[test] total_erase()1818 fn total_erase() { 1819 let a: OwningRefMut<Vec<u8>, [u8]> 1820 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]); 1821 let b: OwningRefMut<Box<[u8]>, [u8]> 1822 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]); 1823 1824 let c: OwningRefMut<Box<Vec<u8>>, [u8]> = unsafe {a.map_owner(Box::new)}; 1825 let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Box::new)}; 1826 1827 let _e: OwningRefMut<Box<Erased>, [u8]> = c.erase_owner(); 1828 let _f: OwningRefMut<Box<Erased>, [u8]> = d.erase_owner(); 1829 } 1830 1831 #[test] total_erase_box()1832 fn total_erase_box() { 1833 let a: OwningRefMut<Vec<u8>, [u8]> 1834 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]); 1835 let b: OwningRefMut<Box<[u8]>, [u8]> 1836 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]); 1837 1838 let c: OwningRefMut<Box<Vec<u8>>, [u8]> = a.map_owner_box(); 1839 let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = b.map_owner_box(); 1840 1841 let _e: OwningRefMut<Box<Erased>, [u8]> = c.erase_owner(); 1842 let _f: OwningRefMut<Box<Erased>, [u8]> = d.erase_owner(); 1843 } 1844 1845 #[test] try_map1()1846 fn try_map1() { 1847 use std::any::Any; 1848 1849 let x = Box::new(123_i32); 1850 let y: Box<Any> = x; 1851 1852 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_ok(); 1853 } 1854 1855 #[test] try_map2()1856 fn try_map2() { 1857 use std::any::Any; 1858 1859 let x = Box::new(123_i32); 1860 let y: Box<Any> = x; 1861 1862 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).is_err(); 1863 } 1864 1865 #[test] try_map3()1866 fn try_map3() { 1867 use std::any::Any; 1868 1869 let x = Box::new(123_i32); 1870 let y: Box<Any> = x; 1871 1872 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_ok(); 1873 } 1874 1875 #[test] try_map4()1876 fn try_map4() { 1877 use std::any::Any; 1878 1879 let x = Box::new(123_i32); 1880 let y: Box<Any> = x; 1881 1882 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).is_err(); 1883 } 1884 1885 #[test] into_owning_ref()1886 fn into_owning_ref() { 1887 use super::super::BoxRef; 1888 1889 let or: BoxRefMut<()> = Box::new(()).into(); 1890 let or: BoxRef<()> = or.into(); 1891 assert_eq!(&*or, &()); 1892 } 1893 1894 struct Foo { 1895 u: u32, 1896 } 1897 struct Bar { 1898 f: Foo, 1899 } 1900 1901 #[test] ref_mut()1902 fn ref_mut() { 1903 use std::cell::RefCell; 1904 1905 let a = RefCell::new(Bar { f: Foo { u: 42 } }); 1906 let mut b = OwningRefMut::new(a.borrow_mut()); 1907 assert_eq!(b.f.u, 42); 1908 b.f.u = 43; 1909 let mut c = b.map_mut(|x| &mut x.f); 1910 assert_eq!(c.u, 43); 1911 c.u = 44; 1912 let mut d = c.map_mut(|x| &mut x.u); 1913 assert_eq!(*d, 44); 1914 *d = 45; 1915 assert_eq!(*d, 45); 1916 } 1917 } 1918 } 1919