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 {
297 /// Get the number of strong references to this value.
299 #[unstable(feature = "rc_counts", reason = "not clearly useful",
301 pub fn strong_count(this: &Self) -> usize {
305 /// Returns true if there are no other `Rc` or `Weak<T>` values that share
306 /// the same inner value.
311 /// #![feature(rc_counts)]
315 /// let five = Rc::new(5);
317 /// assert!(Rc::is_unique(&five));
320 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
322 pub fn is_unique(this: &Self) -> bool {
323 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
326 /// Returns a mutable reference to the contained value if the `Rc<T>` has
327 /// one strong reference and no weak references.
329 /// Returns `None` if the `Rc<T>` is not unique.
336 /// let mut x = Rc::new(3);
337 /// *Rc::get_mut(&mut x).unwrap() = 4;
338 /// assert_eq!(*x, 4);
340 /// let _y = x.clone();
341 /// assert!(Rc::get_mut(&mut x).is_none());
344 #[stable(feature = "rc_unique", since = "1.4.0")]
345 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
346 if Rc::is_unique(this) {
347 let inner = unsafe { &mut **this._ptr };
348 Some(&mut inner.value)
355 impl<T: Clone> Rc<T> {
357 #[unstable(feature = "rc_make_unique", reason = "renamed to Rc::make_mut",
359 #[deprecated(since = "1.4.0", reason = "renamed to Rc::make_mut")]
360 pub fn make_unique(&mut self) -> &mut T {
364 /// Make a mutable reference into the given `Rc<T>` by cloning the inner
365 /// data if the `Rc<T>` doesn't have one strong reference and no weak
368 /// This is also referred to as a copy-on-write.
373 /// #![feature(rc_unique)]
376 /// let mut data = Rc::new(5);
378 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
379 /// let mut other_data = data.clone(); // Won't clone inner data
380 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
381 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
382 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
384 /// // Note: data and other_data now point to different numbers
385 /// assert_eq!(*data, 8);
386 /// assert_eq!(*other_data, 12);
390 #[stable(feature = "rc_unique", since = "1.4.0")]
391 pub fn make_mut(this: &mut Self) -> &mut T {
392 if Rc::strong_count(this) != 1 {
393 // Gotta clone the data, there are other Rcs
394 *this = Rc::new((**this).clone())
395 } else if Rc::weak_count(this) != 0 {
396 // Can just steal the data, all that's left is Weaks
398 let mut swap = Rc::new(ptr::read(&(**this._ptr).value));
399 mem::swap(this, &mut swap);
401 // Remove implicit strong-weak ref (no need to craft a fake
402 // Weak here -- we know other Weaks can clean up for us)
407 // This unsafety is ok because we're guaranteed that the pointer
408 // returned is the *only* pointer that will ever be returned to T. Our
409 // reference count is guaranteed to be 1 at this point, and we required
410 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
411 // reference to the inner value.
412 let inner = unsafe { &mut **this._ptr };
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<T: ?Sized> Deref for Rc<T> {
422 fn deref(&self) -> &T {
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl<T: ?Sized> Drop for Rc<T> {
429 /// Drops the `Rc<T>`.
431 /// This will decrement the strong reference count. If the strong reference
432 /// count becomes zero and the only other references are `Weak<T>` ones,
433 /// `drop`s the inner value.
441 /// let five = Rc::new(5);
445 /// drop(five); // explicit drop
448 /// let five = Rc::new(5);
452 /// } // implicit drop
456 let ptr = *self._ptr;
457 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
458 ptr as *const () as usize != mem::POST_DROP_USIZE {
460 if self.strong() == 0 {
461 // destroy the contained object
462 drop_in_place(&mut (*ptr).value);
464 // remove the implicit "strong weak" pointer now that we've
465 // destroyed the contents.
468 if self.weak() == 0 {
469 deallocate(ptr as *mut u8,
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl<T: ?Sized> Clone for Rc<T> {
482 /// Makes a clone of the `Rc<T>`.
484 /// When you clone an `Rc<T>`, it will create another pointer to the data and
485 /// increase the strong reference counter.
492 /// let five = Rc::new(5);
497 fn clone(&self) -> Rc<T> {
499 Rc { _ptr: self._ptr }
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl<T: Default> Default for Rc<T> {
505 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
512 /// let x: Rc<i32> = Default::default();
515 #[stable(feature = "rust1", since = "1.0.0")]
516 fn default() -> Rc<T> {
517 Rc::new(Default::default())
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
523 /// Equality for two `Rc<T>`s.
525 /// Two `Rc<T>`s are equal if their inner value are equal.
532 /// let five = Rc::new(5);
534 /// five == Rc::new(5);
537 fn eq(&self, other: &Rc<T>) -> bool {
541 /// Inequality for two `Rc<T>`s.
543 /// Two `Rc<T>`s are unequal if their inner value are unequal.
550 /// let five = Rc::new(5);
552 /// five != Rc::new(5);
555 fn ne(&self, other: &Rc<T>) -> bool {
560 #[stable(feature = "rust1", since = "1.0.0")]
561 impl<T: ?Sized + Eq> Eq for Rc<T> {}
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
565 /// Partial comparison for two `Rc<T>`s.
567 /// The two are compared by calling `partial_cmp()` on their inner values.
574 /// let five = Rc::new(5);
576 /// five.partial_cmp(&Rc::new(5));
579 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
580 (**self).partial_cmp(&**other)
583 /// Less-than comparison for two `Rc<T>`s.
585 /// The two are compared by calling `<` on their inner values.
592 /// let five = Rc::new(5);
594 /// five < Rc::new(5);
597 fn lt(&self, other: &Rc<T>) -> bool {
601 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
603 /// The two are compared by calling `<=` on their inner values.
610 /// let five = Rc::new(5);
612 /// five <= Rc::new(5);
615 fn le(&self, other: &Rc<T>) -> bool {
619 /// Greater-than comparison for two `Rc<T>`s.
621 /// The two are compared by calling `>` on their inner values.
628 /// let five = Rc::new(5);
630 /// five > Rc::new(5);
633 fn gt(&self, other: &Rc<T>) -> bool {
637 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
639 /// The two are compared by calling `>=` on their inner values.
646 /// let five = Rc::new(5);
648 /// five >= Rc::new(5);
651 fn ge(&self, other: &Rc<T>) -> bool {
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<T: ?Sized + Ord> Ord for Rc<T> {
658 /// Comparison for two `Rc<T>`s.
660 /// The two are compared by calling `cmp()` on their inner values.
667 /// let five = Rc::new(5);
669 /// five.partial_cmp(&Rc::new(5));
672 fn cmp(&self, other: &Rc<T>) -> Ordering {
673 (**self).cmp(&**other)
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<T: ?Sized+Hash> Hash for Rc<T> {
679 fn hash<H: Hasher>(&self, state: &mut H) {
680 (**self).hash(state);
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
686 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687 fmt::Display::fmt(&**self, f)
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694 fmt::Debug::fmt(&**self, f)
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T> fmt::Pointer for Rc<T> {
700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701 fmt::Pointer::fmt(&*self._ptr, f)
705 /// A weak version of `Rc<T>`.
707 /// Weak references do not count when determining if the inner value should be
710 /// See the [module level documentation](./index.html) for more.
711 #[unsafe_no_drop_flag]
712 #[stable(feature = "rc_weak", since = "1.4.0")]
713 pub struct Weak<T: ?Sized> {
714 // FIXME #12808: strange names to try to avoid interfering with
715 // field accesses of the contained type via Deref
716 _ptr: NonZero<*mut RcBox<T>>,
719 impl<T: ?Sized> !marker::Send for Weak<T> {}
720 impl<T: ?Sized> !marker::Sync for Weak<T> {}
722 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
724 impl<T: ?Sized> Weak<T> {
725 /// Upgrades a weak reference to a strong reference.
727 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
729 /// Returns `None` if there were no strong references and the data was
737 /// let five = Rc::new(5);
739 /// let weak_five = Rc::downgrade(&five);
741 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
743 #[stable(feature = "rc_weak", since = "1.4.0")]
744 pub fn upgrade(&self) -> Option<Rc<T>> {
745 if self.strong() == 0 {
749 Some(Rc { _ptr: self._ptr })
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl<T: ?Sized> Drop for Weak<T> {
756 /// Drops the `Weak<T>`.
758 /// This will decrement the weak reference count.
766 /// let five = Rc::new(5);
767 /// let weak_five = Rc::downgrade(&five);
771 /// drop(weak_five); // explicit drop
774 /// let five = Rc::new(5);
775 /// let weak_five = Rc::downgrade(&five);
779 /// } // implicit drop
783 let ptr = *self._ptr;
784 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
785 ptr as *const () as usize != mem::POST_DROP_USIZE {
787 // the weak count starts at 1, and will only go to zero if all
788 // the strong pointers have disappeared.
789 if self.weak() == 0 {
790 deallocate(ptr as *mut u8,
799 #[stable(feature = "rc_weak", since = "1.4.0")]
800 impl<T: ?Sized> Clone for Weak<T> {
802 /// Makes a clone of the `Weak<T>`.
804 /// This increases the weak reference count.
811 /// let weak_five = Rc::downgrade(&Rc::new(5));
813 /// weak_five.clone();
816 fn clone(&self) -> Weak<T> {
818 Weak { _ptr: self._ptr }
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
829 // NOTE: We checked_add here to deal with mem::forget safety. In particular
830 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
831 // you can free the allocation while outstanding Rcs (or Weaks) exist.
832 // We abort because this is such a degenerate scenario that we don't care about
833 // what happens -- no real program should ever experience this.
835 // This should have negligible overhead since you don't actually need to
836 // clone these much in Rust thanks to ownership and move-semantics.
839 trait RcBoxPtr<T: ?Sized> {
840 fn inner(&self) -> &RcBox<T>;
843 fn strong(&self) -> usize {
844 self.inner().strong.get()
848 fn inc_strong(&self) {
849 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
853 fn dec_strong(&self) {
854 self.inner().strong.set(self.strong() - 1);
858 fn weak(&self) -> usize {
859 self.inner().weak.get()
864 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
869 self.inner().weak.set(self.weak() - 1);
873 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
875 fn inner(&self) -> &RcBox<T> {
877 // Safe to assume this here, as if it weren't true, we'd be breaking
878 // the contract anyway.
879 // This allows the null check to be elided in the destructor if we
880 // manipulated the reference count in the same function.
881 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
887 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
889 fn inner(&self) -> &RcBox<T> {
891 // Safe to assume this here, as if it weren't true, we'd be breaking
892 // the contract anyway.
893 // This allows the null check to be elided in the destructor if we
894 // manipulated the reference count in the same function.
895 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
903 use super::{Rc, Weak};
905 use std::cell::RefCell;
906 use std::option::Option;
907 use std::option::Option::{Some, None};
908 use std::result::Result::{Err, Ok};
910 use std::clone::Clone;
914 let x = Rc::new(RefCell::new(5));
916 *x.borrow_mut() = 20;
917 assert_eq!(*y.borrow(), 20);
927 fn test_simple_clone() {
935 fn test_destructor() {
936 let x: Rc<Box<_>> = Rc::new(box 5);
943 let y = Rc::downgrade(&x);
944 assert!(y.upgrade().is_some());
950 let y = Rc::downgrade(&x);
952 assert!(y.upgrade().is_none());
956 fn weak_self_cyclic() {
958 x: RefCell<Option<Weak<Cycle>>>,
961 let a = Rc::new(Cycle { x: RefCell::new(None) });
962 let b = Rc::downgrade(&a.clone());
963 *a.x.borrow_mut() = Some(b);
965 // hopefully we don't double-free (or leak)...
971 assert!(Rc::is_unique(&x));
973 assert!(!Rc::is_unique(&x));
975 assert!(Rc::is_unique(&x));
976 let w = Rc::downgrade(&x);
977 assert!(!Rc::is_unique(&x));
979 assert!(Rc::is_unique(&x));
983 fn test_strong_count() {
984 let a = Rc::new(0u32);
985 assert!(Rc::strong_count(&a) == 1);
986 let w = Rc::downgrade(&a);
987 assert!(Rc::strong_count(&a) == 1);
988 let b = w.upgrade().expect("upgrade of live rc failed");
989 assert!(Rc::strong_count(&b) == 2);
990 assert!(Rc::strong_count(&a) == 2);
993 assert!(Rc::strong_count(&b) == 1);
995 assert!(Rc::strong_count(&b) == 2);
996 assert!(Rc::strong_count(&c) == 2);
1000 fn test_weak_count() {
1001 let a = Rc::new(0u32);
1002 assert!(Rc::strong_count(&a) == 1);
1003 assert!(Rc::weak_count(&a) == 0);
1004 let w = Rc::downgrade(&a);
1005 assert!(Rc::strong_count(&a) == 1);
1006 assert!(Rc::weak_count(&a) == 1);
1008 assert!(Rc::strong_count(&a) == 1);
1009 assert!(Rc::weak_count(&a) == 0);
1011 assert!(Rc::strong_count(&a) == 2);
1012 assert!(Rc::weak_count(&a) == 0);
1019 assert_eq!(Rc::try_unwrap(x), Ok(3));
1022 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1024 let _w = Rc::downgrade(&x);
1025 assert_eq!(Rc::try_unwrap(x), Ok(5));
1030 let mut x = Rc::new(3);
1031 *Rc::get_mut(&mut x).unwrap() = 4;
1034 assert!(Rc::get_mut(&mut x).is_none());
1036 assert!(Rc::get_mut(&mut x).is_some());
1037 let _w = Rc::downgrade(&x);
1038 assert!(Rc::get_mut(&mut x).is_none());
1042 fn test_cowrc_clone_make_unique() {
1043 let mut cow0 = Rc::new(75);
1044 let mut cow1 = cow0.clone();
1045 let mut cow2 = cow1.clone();
1047 assert!(75 == *Rc::make_mut(&mut cow0));
1048 assert!(75 == *Rc::make_mut(&mut cow1));
1049 assert!(75 == *Rc::make_mut(&mut cow2));
1051 *Rc::make_mut(&mut cow0) += 1;
1052 *Rc::make_mut(&mut cow1) += 2;
1053 *Rc::make_mut(&mut cow2) += 3;
1055 assert!(76 == *cow0);
1056 assert!(77 == *cow1);
1057 assert!(78 == *cow2);
1059 // none should point to the same backing memory
1060 assert!(*cow0 != *cow1);
1061 assert!(*cow0 != *cow2);
1062 assert!(*cow1 != *cow2);
1066 fn test_cowrc_clone_unique2() {
1067 let mut cow0 = Rc::new(75);
1068 let cow1 = cow0.clone();
1069 let cow2 = cow1.clone();
1071 assert!(75 == *cow0);
1072 assert!(75 == *cow1);
1073 assert!(75 == *cow2);
1075 *Rc::make_mut(&mut cow0) += 1;
1077 assert!(76 == *cow0);
1078 assert!(75 == *cow1);
1079 assert!(75 == *cow2);
1081 // cow1 and cow2 should share the same contents
1082 // cow0 should have a unique reference
1083 assert!(*cow0 != *cow1);
1084 assert!(*cow0 != *cow2);
1085 assert!(*cow1 == *cow2);
1089 fn test_cowrc_clone_weak() {
1090 let mut cow0 = Rc::new(75);
1091 let cow1_weak = Rc::downgrade(&cow0);
1093 assert!(75 == *cow0);
1094 assert!(75 == *cow1_weak.upgrade().unwrap());
1096 *Rc::make_mut(&mut cow0) += 1;
1098 assert!(76 == *cow0);
1099 assert!(cow1_weak.upgrade().is_none());
1104 let foo = Rc::new(75);
1105 assert_eq!(format!("{:?}", foo), "75");
1110 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1111 assert_eq!(foo, foo.clone());
1115 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1116 fn borrow(&self) -> &T {