1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! Thread-local reference-counted boxes (the `Rc<T>` type).
15 //! The `Rc<T>` type provides shared ownership of an immutable value.
16 //! Destruction is deterministic, and will occur as soon as the last owner is
17 //! gone. It is marked as non-sendable because it avoids the overhead of atomic
18 //! reference counting.
20 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
21 //! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but
22 //! will return `None` if the value has already been dropped.
24 //! For example, a tree with parent pointers can be represented by putting the
25 //! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers
26 //! as `Weak<T>` pointers.
30 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
31 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
32 //! unique ownership, because more than one gadget may belong to the same
33 //! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s,
34 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
41 //! // ...other fields
47 //! // ...other fields
51 //! // Create a reference counted Owner.
52 //! let gadget_owner : Rc<Owner> = Rc::new(
53 //! Owner { name: String::from("Gadget Man") }
56 //! // Create Gadgets belonging to gadget_owner. To increment the reference
57 //! // count we clone the `Rc<T>` object.
58 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
59 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
61 //! drop(gadget_owner);
63 //! // Despite dropping gadget_owner, we're still able to print out the name
64 //! // of the Owner of the Gadgets. This is because we've only dropped the
65 //! // reference count object, not the Owner it wraps. As long as there are
66 //! // other `Rc<T>` objects pointing at the same Owner, it will remain
67 //! // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
68 //! // automatically dereferenced for us.
69 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
70 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
72 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
73 //! // them the last counted references to our Owner. Gadget Man now gets
74 //! // destroyed as well.
78 //! If our requirements change, and we also need to be able to traverse from
79 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
80 //! → Gadget introduces a cycle between the objects. This means that their
81 //! reference counts can never reach 0, and the objects will remain allocated: a
82 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
83 //! These pointers don't contribute to the total count.
85 //! Rust actually makes it somewhat difficult to produce this loop in the first
86 //! place: in order to end up with two objects that point at each other, one of
87 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
88 //! memory safety by only giving out shared references to the object it wraps,
89 //! and these don't allow direct mutation. We need to wrap the part of the
90 //! object we wish to mutate in a `RefCell`, which provides *interior
91 //! mutability*: a method to achieve mutability through a shared reference.
92 //! `RefCell` enforces Rust's borrowing rules at runtime. Read the `Cell`
93 //! documentation for more details on interior mutability.
97 //! use std::rc::Weak;
98 //! use std::cell::RefCell;
102 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
103 //! // ...other fields
108 //! owner: Rc<Owner>,
109 //! // ...other fields
113 //! // Create a reference counted Owner. Note the fact that we've put the
114 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
115 //! // through a shared reference.
116 //! let gadget_owner : Rc<Owner> = Rc::new(
118 //! name: "Gadget Man".to_string(),
119 //! gadgets: RefCell::new(Vec::new()),
123 //! // Create Gadgets belonging to gadget_owner as before.
124 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
125 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
127 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
128 //! // the RefCell holding the Owner's Gadgets.
129 //! gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget1));
130 //! gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget2));
132 //! // Iterate over our Gadgets, printing their details out
133 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
135 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
136 //! // that their object is still allocated, we need to call upgrade()
137 //! // on them to turn them into a strong reference. This returns an
138 //! // Option, which contains a reference to our object if it still
140 //! let gadget = gadget_opt.upgrade().unwrap();
141 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
144 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
145 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
146 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
147 //! // reference count on Gadget Man, they get destroyed as well.
151 #![stable(feature = "rust1", since = "1.0.0")]
159 use core::cell::Cell;
160 use core::cmp::Ordering;
162 use core::hash::{Hasher, Hash};
163 use core::intrinsics::{assume, drop_in_place, abort};
164 use core::marker::{self, Unsize};
165 use core::mem::{self, align_of_val, size_of_val, forget};
166 use core::nonzero::NonZero;
167 use core::ops::{CoerceUnsized, Deref};
170 use heap::deallocate;
172 struct RcBox<T: ?Sized> {
179 /// A reference-counted pointer type over an immutable value.
181 /// See the [module level documentation](./index.html) for more details.
182 #[unsafe_no_drop_flag]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub struct Rc<T: ?Sized> {
185 // FIXME #12808: strange names to try to avoid interfering with field
186 // accesses of the contained type via Deref
187 _ptr: NonZero<*mut RcBox<T>>,
190 impl<T: ?Sized> !marker::Send for Rc<T> {}
191 impl<T: ?Sized> !marker::Sync for Rc<T> {}
193 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
196 /// Constructs a new `Rc<T>`.
203 /// let five = Rc::new(5);
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn new(value: T) -> Rc<T> {
209 // there is an implicit weak pointer owned by all the strong
210 // pointers, which ensures that the weak destructor never frees
211 // the allocation while the strong destructor is running, even
212 // if the weak pointer is stored inside the strong one.
213 _ptr: NonZero::new(Box::into_raw(box RcBox {
214 strong: Cell::new(1),
222 /// Unwraps the contained value if the `Rc<T>` has only one strong reference.
223 /// This will succeed even if there are outstanding weak references.
225 /// Otherwise, an `Err` is returned with the same `Rc<T>`.
230 /// #![feature(rc_unique)]
234 /// let x = Rc::new(3);
235 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
237 /// let x = Rc::new(4);
238 /// let _y = x.clone();
239 /// assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
242 #[stable(feature = "rc_unique", since = "1.4.0")]
243 pub fn try_unwrap(this: Self) -> Result<T, Self> {
244 if Rc::would_unwrap(&this) {
246 let val = ptr::read(&*this); // copy the contained object
248 // Indicate to Weaks that they can't be promoted by decrememting
249 // the strong count, and then remove the implicit "strong weak"
250 // pointer while also handling drop logic by just crafting a
253 let _weak = Weak { _ptr: this._ptr };
262 /// Checks if `Rc::try_unwrap` would return `Ok`.
263 #[unstable(feature = "rc_would_unwrap",
264 reason = "just added for niche usecase",
266 pub fn would_unwrap(this: &Self) -> bool {
267 Rc::strong_count(&this) == 1
271 impl<T: ?Sized> Rc<T> {
272 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
279 /// let five = Rc::new(5);
281 /// let weak_five = Rc::downgrade(&five);
283 #[stable(feature = "rc_weak", since = "1.4.0")]
284 pub fn downgrade(this: &Self) -> Weak<T> {
286 Weak { _ptr: this._ptr }
289 /// Get the number of weak references to this value.
291 #[unstable(feature = "rc_counts", reason = "not clearly useful",
293 pub fn weak_count(this: &Self) -> usize { this.weak() - 1 }
295 /// Get the number of strong references to this value.
297 #[unstable(feature = "rc_counts", reason = "not clearly useful",
299 pub fn strong_count(this: &Self) -> usize { this.strong() }
301 /// Returns true if there are no other `Rc` or `Weak<T>` values that share
302 /// the same inner value.
307 /// #![feature(rc_counts)]
311 /// let five = Rc::new(5);
313 /// assert!(Rc::is_unique(&five));
316 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
318 pub fn is_unique(this: &Self) -> bool {
319 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
322 /// Returns a mutable reference to the contained value if the `Rc<T>` has
323 /// one strong reference and no weak references.
325 /// Returns `None` if the `Rc<T>` is not unique.
332 /// let mut x = Rc::new(3);
333 /// *Rc::get_mut(&mut x).unwrap() = 4;
334 /// assert_eq!(*x, 4);
336 /// let _y = x.clone();
337 /// assert!(Rc::get_mut(&mut x).is_none());
340 #[stable(feature = "rc_unique", since = "1.4.0")]
341 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
342 if Rc::is_unique(this) {
343 let inner = unsafe { &mut **this._ptr };
344 Some(&mut inner.value)
351 impl<T: Clone> Rc<T> {
353 #[unstable(feature = "rc_make_unique", reason = "renamed to Rc::make_mut",
355 #[deprecated(since = "1.4.0", reason = "renamed to Rc::make_mut")]
356 pub fn make_unique(&mut self) -> &mut T {
360 /// Make a mutable reference into the given `Rc<T>` by cloning the inner
361 /// data if the `Rc<T>` doesn't have one strong reference and no weak
364 /// This is also referred to as a copy-on-write.
369 /// #![feature(rc_unique)]
372 /// let mut data = Rc::new(5);
374 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
375 /// let mut other_data = data.clone(); // Won't clone inner data
376 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
377 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
378 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
380 /// // Note: data and other_data now point to different numbers
381 /// assert_eq!(*data, 8);
382 /// assert_eq!(*other_data, 12);
386 #[stable(feature = "rc_unique", since = "1.4.0")]
387 pub fn make_mut(this: &mut Self) -> &mut T {
388 if Rc::strong_count(this) != 1 {
389 // Gotta clone the data, there are other Rcs
390 *this = Rc::new((**this).clone())
391 } else if Rc::weak_count(this) != 0 {
392 // Can just steal the data, all that's left is Weaks
394 let mut swap = Rc::new(ptr::read(&(**this._ptr).value));
395 mem::swap(this, &mut swap);
397 // Remove implicit strong-weak ref (no need to craft a fake
398 // Weak here -- we know other Weaks can clean up for us)
403 // This unsafety is ok because we're guaranteed that the pointer
404 // returned is the *only* pointer that will ever be returned to T. Our
405 // reference count is guaranteed to be 1 at this point, and we required
406 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
407 // reference to the inner value.
408 let inner = unsafe { &mut **this._ptr };
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<T: ?Sized> Deref for Rc<T> {
418 fn deref(&self) -> &T {
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<T: ?Sized> Drop for Rc<T> {
425 /// Drops the `Rc<T>`.
427 /// This will decrement the strong reference count. If the strong reference
428 /// count becomes zero and the only other references are `Weak<T>` ones,
429 /// `drop`s the inner value.
437 /// let five = Rc::new(5);
441 /// drop(five); // explicit drop
444 /// let five = Rc::new(5);
448 /// } // implicit drop
452 let ptr = *self._ptr;
453 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
454 ptr as *const () as usize != mem::POST_DROP_USIZE {
456 if self.strong() == 0 {
457 // destroy the contained object
458 drop_in_place(&mut (*ptr).value);
460 // remove the implicit "strong weak" pointer now that we've
461 // destroyed the contents.
464 if self.weak() == 0 {
465 deallocate(ptr as *mut u8,
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl<T: ?Sized> Clone for Rc<T> {
478 /// Makes a clone of the `Rc<T>`.
480 /// When you clone an `Rc<T>`, it will create another pointer to the data and
481 /// increase the strong reference counter.
488 /// let five = Rc::new(5);
493 fn clone(&self) -> Rc<T> {
495 Rc { _ptr: self._ptr }
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl<T: Default> Default for Rc<T> {
501 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
508 /// let x: Rc<i32> = Default::default();
511 #[stable(feature = "rust1", since = "1.0.0")]
512 fn default() -> Rc<T> {
513 Rc::new(Default::default())
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
519 /// Equality for two `Rc<T>`s.
521 /// Two `Rc<T>`s are equal if their inner value are equal.
528 /// let five = Rc::new(5);
530 /// five == Rc::new(5);
533 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
535 /// Inequality for two `Rc<T>`s.
537 /// Two `Rc<T>`s are unequal if their inner value are unequal.
544 /// let five = Rc::new(5);
546 /// five != Rc::new(5);
549 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl<T: ?Sized + Eq> Eq for Rc<T> {}
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
557 /// Partial comparison for two `Rc<T>`s.
559 /// The two are compared by calling `partial_cmp()` on their inner values.
566 /// let five = Rc::new(5);
568 /// five.partial_cmp(&Rc::new(5));
571 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
572 (**self).partial_cmp(&**other)
575 /// Less-than comparison for two `Rc<T>`s.
577 /// The two are compared by calling `<` on their inner values.
584 /// let five = Rc::new(5);
586 /// five < Rc::new(5);
589 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
591 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
593 /// The two are compared by calling `<=` on their inner values.
600 /// let five = Rc::new(5);
602 /// five <= Rc::new(5);
605 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
607 /// Greater-than comparison for two `Rc<T>`s.
609 /// The two are compared by calling `>` on their inner values.
616 /// let five = Rc::new(5);
618 /// five > Rc::new(5);
621 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
623 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
625 /// The two are compared by calling `>=` on their inner values.
632 /// let five = Rc::new(5);
634 /// five >= Rc::new(5);
637 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T: ?Sized + Ord> Ord for Rc<T> {
642 /// Comparison for two `Rc<T>`s.
644 /// The two are compared by calling `cmp()` on their inner values.
651 /// let five = Rc::new(5);
653 /// five.partial_cmp(&Rc::new(5));
656 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
659 #[stable(feature = "rust1", since = "1.0.0")]
660 impl<T: ?Sized+Hash> Hash for Rc<T> {
661 fn hash<H: Hasher>(&self, state: &mut H) {
662 (**self).hash(state);
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
668 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
669 fmt::Display::fmt(&**self, f)
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676 fmt::Debug::fmt(&**self, f)
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl<T> fmt::Pointer for Rc<T> {
682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 fmt::Pointer::fmt(&*self._ptr, f)
687 /// A weak version of `Rc<T>`.
689 /// Weak references do not count when determining if the inner value should be
692 /// See the [module level documentation](./index.html) for more.
693 #[unsafe_no_drop_flag]
694 #[stable(feature = "rc_weak", since = "1.4.0")]
695 pub struct Weak<T: ?Sized> {
696 // FIXME #12808: strange names to try to avoid interfering with
697 // field accesses of the contained type via Deref
698 _ptr: NonZero<*mut RcBox<T>>,
701 impl<T: ?Sized> !marker::Send for Weak<T> {}
702 impl<T: ?Sized> !marker::Sync for Weak<T> {}
704 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
706 impl<T: ?Sized> Weak<T> {
707 /// Upgrades a weak reference to a strong reference.
709 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
711 /// Returns `None` if there were no strong references and the data was
719 /// let five = Rc::new(5);
721 /// let weak_five = Rc::downgrade(&five);
723 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
725 #[stable(feature = "rc_weak", since = "1.4.0")]
726 pub fn upgrade(&self) -> Option<Rc<T>> {
727 if self.strong() == 0 {
731 Some(Rc { _ptr: self._ptr })
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<T: ?Sized> Drop for Weak<T> {
738 /// Drops the `Weak<T>`.
740 /// This will decrement the weak reference count.
748 /// let five = Rc::new(5);
749 /// let weak_five = Rc::downgrade(&five);
753 /// drop(weak_five); // explicit drop
756 /// let five = Rc::new(5);
757 /// let weak_five = Rc::downgrade(&five);
761 /// } // implicit drop
765 let ptr = *self._ptr;
766 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
767 ptr as *const () as usize != mem::POST_DROP_USIZE {
769 // the weak count starts at 1, and will only go to zero if all
770 // the strong pointers have disappeared.
771 if self.weak() == 0 {
772 deallocate(ptr as *mut u8, size_of_val(&*ptr),
780 #[stable(feature = "rc_weak", since = "1.4.0")]
781 impl<T: ?Sized> Clone for Weak<T> {
783 /// Makes a clone of the `Weak<T>`.
785 /// This increases the weak reference count.
792 /// let weak_five = Rc::downgrade(&Rc::new(5));
794 /// weak_five.clone();
797 fn clone(&self) -> Weak<T> {
799 Weak { _ptr: self._ptr }
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
805 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
810 // NOTE: We checked_add here to deal with mem::forget safety. In particular
811 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
812 // you can free the allocation while outstanding Rcs (or Weaks) exist.
813 // We abort because this is such a degenerate scenario that we don't care about
814 // what happens -- no real program should ever experience this.
816 // This should have negligible overhead since you don't actually need to
817 // clone these much in Rust thanks to ownership and move-semantics.
820 trait RcBoxPtr<T: ?Sized> {
821 fn inner(&self) -> &RcBox<T>;
824 fn strong(&self) -> usize { self.inner().strong.get() }
827 fn inc_strong(&self) {
828 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
832 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
835 fn weak(&self) -> usize { self.inner().weak.get() }
839 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
843 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
846 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
848 fn inner(&self) -> &RcBox<T> {
850 // Safe to assume this here, as if it weren't true, we'd be breaking
851 // the contract anyway.
852 // This allows the null check to be elided in the destructor if we
853 // manipulated the reference count in the same function.
854 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
860 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
862 fn inner(&self) -> &RcBox<T> {
864 // Safe to assume this here, as if it weren't true, we'd be breaking
865 // the contract anyway.
866 // This allows the null check to be elided in the destructor if we
867 // manipulated the reference count in the same function.
868 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
876 use super::{Rc, Weak};
878 use std::cell::RefCell;
879 use std::option::Option;
880 use std::option::Option::{Some, None};
881 use std::result::Result::{Err, Ok};
883 use std::clone::Clone;
887 let x = Rc::new(RefCell::new(5));
889 *x.borrow_mut() = 20;
890 assert_eq!(*y.borrow(), 20);
900 fn test_simple_clone() {
908 fn test_destructor() {
909 let x: Rc<Box<_>> = Rc::new(box 5);
916 let y = Rc::downgrade(&x);
917 assert!(y.upgrade().is_some());
923 let y = Rc::downgrade(&x);
925 assert!(y.upgrade().is_none());
929 fn weak_self_cyclic() {
931 x: RefCell<Option<Weak<Cycle>>>
934 let a = Rc::new(Cycle { x: RefCell::new(None) });
935 let b = Rc::downgrade(&a.clone());
936 *a.x.borrow_mut() = Some(b);
938 // hopefully we don't double-free (or leak)...
944 assert!(Rc::is_unique(&x));
946 assert!(!Rc::is_unique(&x));
948 assert!(Rc::is_unique(&x));
949 let w = Rc::downgrade(&x);
950 assert!(!Rc::is_unique(&x));
952 assert!(Rc::is_unique(&x));
956 fn test_strong_count() {
957 let a = Rc::new(0u32);
958 assert!(Rc::strong_count(&a) == 1);
959 let w = Rc::downgrade(&a);
960 assert!(Rc::strong_count(&a) == 1);
961 let b = w.upgrade().expect("upgrade of live rc failed");
962 assert!(Rc::strong_count(&b) == 2);
963 assert!(Rc::strong_count(&a) == 2);
966 assert!(Rc::strong_count(&b) == 1);
968 assert!(Rc::strong_count(&b) == 2);
969 assert!(Rc::strong_count(&c) == 2);
973 fn test_weak_count() {
974 let a = Rc::new(0u32);
975 assert!(Rc::strong_count(&a) == 1);
976 assert!(Rc::weak_count(&a) == 0);
977 let w = Rc::downgrade(&a);
978 assert!(Rc::strong_count(&a) == 1);
979 assert!(Rc::weak_count(&a) == 1);
981 assert!(Rc::strong_count(&a) == 1);
982 assert!(Rc::weak_count(&a) == 0);
984 assert!(Rc::strong_count(&a) == 2);
985 assert!(Rc::weak_count(&a) == 0);
992 assert_eq!(Rc::try_unwrap(x), Ok(3));
995 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
997 let _w = Rc::downgrade(&x);
998 assert_eq!(Rc::try_unwrap(x), Ok(5));
1003 let mut x = Rc::new(3);
1004 *Rc::get_mut(&mut x).unwrap() = 4;
1007 assert!(Rc::get_mut(&mut x).is_none());
1009 assert!(Rc::get_mut(&mut x).is_some());
1010 let _w = Rc::downgrade(&x);
1011 assert!(Rc::get_mut(&mut x).is_none());
1015 fn test_cowrc_clone_make_unique() {
1016 let mut cow0 = Rc::new(75);
1017 let mut cow1 = cow0.clone();
1018 let mut cow2 = cow1.clone();
1020 assert!(75 == *Rc::make_mut(&mut cow0));
1021 assert!(75 == *Rc::make_mut(&mut cow1));
1022 assert!(75 == *Rc::make_mut(&mut cow2));
1024 *Rc::make_mut(&mut cow0) += 1;
1025 *Rc::make_mut(&mut cow1) += 2;
1026 *Rc::make_mut(&mut cow2) += 3;
1028 assert!(76 == *cow0);
1029 assert!(77 == *cow1);
1030 assert!(78 == *cow2);
1032 // none should point to the same backing memory
1033 assert!(*cow0 != *cow1);
1034 assert!(*cow0 != *cow2);
1035 assert!(*cow1 != *cow2);
1039 fn test_cowrc_clone_unique2() {
1040 let mut cow0 = Rc::new(75);
1041 let cow1 = cow0.clone();
1042 let cow2 = cow1.clone();
1044 assert!(75 == *cow0);
1045 assert!(75 == *cow1);
1046 assert!(75 == *cow2);
1048 *Rc::make_mut(&mut cow0) += 1;
1050 assert!(76 == *cow0);
1051 assert!(75 == *cow1);
1052 assert!(75 == *cow2);
1054 // cow1 and cow2 should share the same contents
1055 // cow0 should have a unique reference
1056 assert!(*cow0 != *cow1);
1057 assert!(*cow0 != *cow2);
1058 assert!(*cow1 == *cow2);
1062 fn test_cowrc_clone_weak() {
1063 let mut cow0 = Rc::new(75);
1064 let cow1_weak = Rc::downgrade(&cow0);
1066 assert!(75 == *cow0);
1067 assert!(75 == *cow1_weak.upgrade().unwrap());
1069 *Rc::make_mut(&mut cow0) += 1;
1071 assert!(76 == *cow0);
1072 assert!(cow1_weak.upgrade().is_none());
1077 let foo = Rc::new(75);
1078 assert_eq!(format!("{:?}", foo), "75");
1083 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1084 assert_eq!(foo, foo.clone());
1088 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1089 fn borrow(&self) -> &T { &**self }