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 //! Unsynchronized reference-counted boxes (the `Rc<T>` type) which are usable
14 //! only within a single thread.
16 //! The `Rc<T>` type provides shared ownership of an immutable value.
17 //! Destruction is deterministic, and will occur as soon as the last owner is
18 //! gone. It is marked as non-sendable because it avoids the overhead of atomic
19 //! reference counting.
21 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
22 //! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but
23 //! will return `None` if the value has already been dropped.
25 //! For example, a tree with parent pointers can be represented by putting the
26 //! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers
27 //! as `Weak<T>` pointers.
31 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
32 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
33 //! unique ownership, because more than one gadget may belong to the same
34 //! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s,
35 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
42 //! // ...other fields
48 //! // ...other fields
52 //! // Create a reference counted Owner.
53 //! let gadget_owner : Rc<Owner> = Rc::new(
54 //! Owner { name: String::from("Gadget Man") }
57 //! // Create Gadgets belonging to gadget_owner. To increment the reference
58 //! // count we clone the `Rc<T>` object.
59 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
60 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
62 //! drop(gadget_owner);
64 //! // Despite dropping gadget_owner, we're still able to print out the name
65 //! // of the Owner of the Gadgets. This is because we've only dropped the
66 //! // reference count object, not the Owner it wraps. As long as there are
67 //! // other `Rc<T>` objects pointing at the same Owner, it will remain
68 //! // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
69 //! // automatically dereferenced for us.
70 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
71 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
73 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
74 //! // them the last counted references to our Owner. Gadget Man now gets
75 //! // destroyed as well.
79 //! If our requirements change, and we also need to be able to traverse from
80 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
81 //! → Gadget introduces a cycle between the objects. This means that their
82 //! reference counts can never reach 0, and the objects will remain allocated: a
83 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
84 //! These pointers don't contribute to the total count.
86 //! Rust actually makes it somewhat difficult to produce this loop in the first
87 //! place: in order to end up with two objects that point at each other, one of
88 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
89 //! memory safety by only giving out shared references to the object it wraps,
90 //! and these don't allow direct mutation. We need to wrap the part of the
91 //! object we wish to mutate in a `RefCell`, which provides *interior
92 //! mutability*: a method to achieve mutability through a shared reference.
93 //! `RefCell` enforces Rust's borrowing rules at runtime. Read the `Cell`
94 //! documentation for more details on interior mutability.
98 //! use std::rc::Weak;
99 //! use std::cell::RefCell;
103 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
104 //! // ...other fields
109 //! owner: Rc<Owner>,
110 //! // ...other fields
114 //! // Create a reference counted Owner. Note the fact that we've put the
115 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
116 //! // through a shared reference.
117 //! let gadget_owner : Rc<Owner> = Rc::new(
119 //! name: "Gadget Man".to_string(),
120 //! gadgets: RefCell::new(Vec::new()),
124 //! // Create Gadgets belonging to gadget_owner as before.
125 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
126 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
128 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
129 //! // the RefCell holding the Owner's Gadgets.
130 //! gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget1));
131 //! gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget2));
133 //! // Iterate over our Gadgets, printing their details out
134 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
136 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
137 //! // that their object is still allocated, we need to call upgrade()
138 //! // on them to turn them into a strong reference. This returns an
139 //! // Option, which contains a reference to our object if it still
141 //! let gadget = gadget_opt.upgrade().unwrap();
142 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
145 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
146 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
147 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
148 //! // reference count on Gadget Man, they get destroyed as well.
152 #![stable(feature = "rust1", since = "1.0.0")]
160 use core::cell::Cell;
161 use core::cmp::Ordering;
163 use core::hash::{Hash, Hasher};
164 use core::intrinsics::{abort, assume};
166 use core::marker::Unsize;
167 use core::mem::{self, align_of_val, forget, size_of_val, uninitialized};
168 use core::ops::Deref;
169 use core::ops::CoerceUnsized;
170 use core::ptr::{self, Shared};
171 use core::convert::From;
173 use heap::deallocate;
175 struct RcBox<T: ?Sized> {
182 /// A reference-counted pointer type over an immutable value.
184 /// See the [module level documentation](./index.html) for more details.
186 /// Note: the inherent methods defined on `Rc<T>` are all associated functions,
187 /// which means that you have to call them as e.g. `Rc::get_mut(&value)` instead
188 /// of `value.get_mut()`. This is so that there are no conflicts with methods
189 /// on the inner type `T`, which are what you want to call in the majority of
191 #[cfg_attr(stage0, unsafe_no_drop_flag)]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub struct Rc<T: ?Sized> {
194 ptr: Shared<RcBox<T>>,
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T: ?Sized> !marker::Send for Rc<T> {}
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl<T: ?Sized> !marker::Sync for Rc<T> {}
202 #[unstable(feature = "coerce_unsized", issue = "27732")]
203 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
206 /// Constructs a new `Rc<T>`.
213 /// let five = Rc::new(5);
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn new(value: T) -> Rc<T> {
219 // there is an implicit weak pointer owned by all the strong
220 // pointers, which ensures that the weak destructor never frees
221 // the allocation while the strong destructor is running, even
222 // if the weak pointer is stored inside the strong one.
223 ptr: Shared::new(Box::into_raw(box RcBox {
224 strong: Cell::new(1),
232 /// Unwraps the contained value if the `Rc<T>` has exactly one strong reference.
234 /// Otherwise, an `Err` is returned with the same `Rc<T>`.
236 /// This will succeed even if there are outstanding weak references.
243 /// let x = Rc::new(3);
244 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
246 /// let x = Rc::new(4);
247 /// let _y = x.clone();
248 /// assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
251 #[stable(feature = "rc_unique", since = "1.4.0")]
252 pub fn try_unwrap(this: Self) -> Result<T, Self> {
253 if Rc::would_unwrap(&this) {
255 let val = ptr::read(&*this); // copy the contained object
257 // Indicate to Weaks that they can't be promoted by decrememting
258 // the strong count, and then remove the implicit "strong weak"
259 // pointer while also handling drop logic by just crafting a
262 let _weak = Weak { ptr: this.ptr };
271 /// Checks if `Rc::try_unwrap` would return `Ok`.
276 /// #![feature(rc_would_unwrap)]
280 /// let x = Rc::new(3);
281 /// assert!(Rc::would_unwrap(&x));
282 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
284 /// let x = Rc::new(4);
285 /// let _y = x.clone();
286 /// assert!(!Rc::would_unwrap(&x));
287 /// assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
289 #[unstable(feature = "rc_would_unwrap",
290 reason = "just added for niche usecase",
292 pub fn would_unwrap(this: &Self) -> bool {
293 Rc::strong_count(&this) == 1
297 impl<T: ?Sized> Rc<T> {
298 /// Creates a new `Weak<T>` reference from this value.
305 /// let five = Rc::new(5);
307 /// let weak_five = Rc::downgrade(&five);
309 #[stable(feature = "rc_weak", since = "1.4.0")]
310 pub fn downgrade(this: &Self) -> Weak<T> {
312 Weak { ptr: this.ptr }
315 /// Get the number of weak references to this value.
317 #[unstable(feature = "rc_counts", reason = "not clearly useful",
319 pub fn weak_count(this: &Self) -> usize {
323 /// Get the number of strong references to this value.
325 #[unstable(feature = "rc_counts", reason = "not clearly useful",
327 pub fn strong_count(this: &Self) -> usize {
331 /// Returns true if there are no other `Rc` or `Weak<T>` values that share
332 /// the same inner value.
337 /// #![feature(rc_counts)]
341 /// let five = Rc::new(5);
343 /// assert!(Rc::is_unique(&five));
346 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
348 pub fn is_unique(this: &Self) -> bool {
349 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
352 /// Returns a mutable reference to the contained value if the `Rc<T>` has
353 /// one strong reference and no weak references.
355 /// Returns `None` if the `Rc<T>` is not unique.
362 /// let mut x = Rc::new(3);
363 /// *Rc::get_mut(&mut x).unwrap() = 4;
364 /// assert_eq!(*x, 4);
366 /// let _y = x.clone();
367 /// assert!(Rc::get_mut(&mut x).is_none());
370 #[stable(feature = "rc_unique", since = "1.4.0")]
371 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
372 if Rc::is_unique(this) {
373 let inner = unsafe { &mut **this.ptr };
374 Some(&mut inner.value)
381 impl<T: Clone> Rc<T> {
382 /// Make a mutable reference into the given `Rc<T>` by cloning the inner
383 /// data if the `Rc<T>` doesn't have one strong reference and no weak
386 /// This is also referred to as a copy-on-write.
393 /// let mut data = Rc::new(5);
395 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
396 /// let mut other_data = data.clone(); // Won't clone inner data
397 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
398 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
399 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
401 /// // Note: data and other_data now point to different numbers
402 /// assert_eq!(*data, 8);
403 /// assert_eq!(*other_data, 12);
407 #[stable(feature = "rc_unique", since = "1.4.0")]
408 pub fn make_mut(this: &mut Self) -> &mut T {
409 if Rc::strong_count(this) != 1 {
410 // Gotta clone the data, there are other Rcs
411 *this = Rc::new((**this).clone())
412 } else if Rc::weak_count(this) != 0 {
413 // Can just steal the data, all that's left is Weaks
415 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
416 mem::swap(this, &mut swap);
418 // Remove implicit strong-weak ref (no need to craft a fake
419 // Weak here -- we know other Weaks can clean up for us)
424 // This unsafety is ok because we're guaranteed that the pointer
425 // returned is the *only* pointer that will ever be returned to T. Our
426 // reference count is guaranteed to be 1 at this point, and we required
427 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
428 // reference to the inner value.
429 let inner = unsafe { &mut **this.ptr };
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl<T: ?Sized> Deref for Rc<T> {
439 fn deref(&self) -> &T {
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<T: ?Sized> Drop for Rc<T> {
446 /// Drops the `Rc<T>`.
448 /// This will decrement the strong reference count. If the strong reference
449 /// count becomes zero and the only other references are `Weak<T>` ones,
450 /// `drop`s the inner value.
458 /// let five = Rc::new(5);
462 /// drop(five); // explicit drop
465 /// let five = Rc::new(5);
469 /// } // implicit drop
471 #[unsafe_destructor_blind_to_params]
477 if self.strong() == 0 {
478 // destroy the contained object
479 ptr::drop_in_place(&mut (*ptr).value);
481 // remove the implicit "strong weak" pointer now that we've
482 // destroyed the contents.
485 if self.weak() == 0 {
486 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<T: ?Sized> Clone for Rc<T> {
495 /// Makes a clone of the `Rc<T>`.
497 /// When you clone an `Rc<T>`, it will create another pointer to the data and
498 /// increase the strong reference counter.
505 /// let five = Rc::new(5);
510 fn clone(&self) -> Rc<T> {
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<T: Default> Default for Rc<T> {
518 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
525 /// let x: Rc<i32> = Default::default();
528 fn default() -> Rc<T> {
529 Rc::new(Default::default())
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
535 /// Equality for two `Rc<T>`s.
537 /// Two `Rc<T>`s are equal if their inner value are equal.
544 /// let five = Rc::new(5);
546 /// five == Rc::new(5);
549 fn eq(&self, other: &Rc<T>) -> bool {
553 /// Inequality for two `Rc<T>`s.
555 /// Two `Rc<T>`s are unequal if their inner value are unequal.
562 /// let five = Rc::new(5);
564 /// five != Rc::new(5);
567 fn ne(&self, other: &Rc<T>) -> bool {
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<T: ?Sized + Eq> Eq for Rc<T> {}
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
577 /// Partial comparison for two `Rc<T>`s.
579 /// The two are compared by calling `partial_cmp()` on their inner values.
586 /// let five = Rc::new(5);
588 /// five.partial_cmp(&Rc::new(5));
591 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
592 (**self).partial_cmp(&**other)
595 /// Less-than comparison for two `Rc<T>`s.
597 /// The two are compared by calling `<` on their inner values.
604 /// let five = Rc::new(5);
606 /// five < Rc::new(5);
609 fn lt(&self, other: &Rc<T>) -> bool {
613 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
615 /// The two are compared by calling `<=` on their inner values.
622 /// let five = Rc::new(5);
624 /// five <= Rc::new(5);
627 fn le(&self, other: &Rc<T>) -> bool {
631 /// Greater-than comparison for two `Rc<T>`s.
633 /// The two are compared by calling `>` on their inner values.
640 /// let five = Rc::new(5);
642 /// five > Rc::new(5);
645 fn gt(&self, other: &Rc<T>) -> bool {
649 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
651 /// The two are compared by calling `>=` on their inner values.
658 /// let five = Rc::new(5);
660 /// five >= Rc::new(5);
663 fn ge(&self, other: &Rc<T>) -> bool {
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<T: ?Sized + Ord> Ord for Rc<T> {
670 /// Comparison for two `Rc<T>`s.
672 /// The two are compared by calling `cmp()` on their inner values.
679 /// let five = Rc::new(5);
681 /// five.partial_cmp(&Rc::new(5));
684 fn cmp(&self, other: &Rc<T>) -> Ordering {
685 (**self).cmp(&**other)
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<T: ?Sized + Hash> Hash for Rc<T> {
691 fn hash<H: Hasher>(&self, state: &mut H) {
692 (**self).hash(state);
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
698 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699 fmt::Display::fmt(&**self, f)
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
706 fmt::Debug::fmt(&**self, f)
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T: ?Sized> fmt::Pointer for Rc<T> {
712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
713 fmt::Pointer::fmt(&*self.ptr, f)
717 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
718 impl<T> From<T> for Rc<T> {
719 fn from(t: T) -> Self {
724 /// A weak version of `Rc<T>`.
726 /// Weak references do not count when determining if the inner value should be
729 /// See the [module level documentation](./index.html) for more.
730 #[cfg_attr(stage0, unsafe_no_drop_flag)]
731 #[stable(feature = "rc_weak", since = "1.4.0")]
732 pub struct Weak<T: ?Sized> {
733 ptr: Shared<RcBox<T>>,
736 #[stable(feature = "rc_weak", since = "1.4.0")]
737 impl<T: ?Sized> !marker::Send for Weak<T> {}
738 #[stable(feature = "rc_weak", since = "1.4.0")]
739 impl<T: ?Sized> !marker::Sync for Weak<T> {}
741 #[unstable(feature = "coerce_unsized", issue = "27732")]
742 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
745 /// Constructs a new `Weak<T>` without an accompanying instance of T.
747 /// This allocates memory for T, but does not initialize it. Calling
748 /// Weak<T>::upgrade() on the return value always gives None.
753 /// use std::rc::Weak;
755 /// let empty: Weak<i64> = Weak::new();
757 #[stable(feature = "downgraded_weak", since = "1.10.0")]
758 pub fn new() -> Weak<T> {
761 ptr: Shared::new(Box::into_raw(box RcBox {
762 strong: Cell::new(0),
764 value: uninitialized(),
771 impl<T: ?Sized> Weak<T> {
772 /// Upgrades a weak reference to a strong reference.
774 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
776 /// Returns `None` if there were no strong references and the data was
784 /// let five = Rc::new(5);
786 /// let weak_five = Rc::downgrade(&five);
788 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
790 #[stable(feature = "rc_weak", since = "1.4.0")]
791 pub fn upgrade(&self) -> Option<Rc<T>> {
792 if self.strong() == 0 {
796 Some(Rc { ptr: self.ptr })
801 #[stable(feature = "rc_weak", since = "1.4.0")]
802 impl<T: ?Sized> Drop for Weak<T> {
803 /// Drops the `Weak<T>`.
805 /// This will decrement the weak reference count.
813 /// let five = Rc::new(5);
814 /// let weak_five = Rc::downgrade(&five);
818 /// drop(weak_five); // explicit drop
821 /// let five = Rc::new(5);
822 /// let weak_five = Rc::downgrade(&five);
826 /// } // implicit drop
833 // the weak count starts at 1, and will only go to zero if all
834 // the strong pointers have disappeared.
835 if self.weak() == 0 {
836 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
842 #[stable(feature = "rc_weak", since = "1.4.0")]
843 impl<T: ?Sized> Clone for Weak<T> {
844 /// Makes a clone of the `Weak<T>`.
846 /// This increases the weak reference count.
853 /// let weak_five = Rc::downgrade(&Rc::new(5));
855 /// weak_five.clone();
858 fn clone(&self) -> Weak<T> {
860 Weak { ptr: self.ptr }
864 #[stable(feature = "rc_weak", since = "1.4.0")]
865 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
871 #[stable(feature = "downgraded_weak", since = "1.10.0")]
872 impl<T> Default for Weak<T> {
873 fn default() -> Weak<T> {
878 // NOTE: We checked_add here to deal with mem::forget safety. In particular
879 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
880 // you can free the allocation while outstanding Rcs (or Weaks) exist.
881 // We abort because this is such a degenerate scenario that we don't care about
882 // what happens -- no real program should ever experience this.
884 // This should have negligible overhead since you don't actually need to
885 // clone these much in Rust thanks to ownership and move-semantics.
888 trait RcBoxPtr<T: ?Sized> {
889 fn inner(&self) -> &RcBox<T>;
892 fn strong(&self) -> usize {
893 self.inner().strong.get()
897 fn inc_strong(&self) {
898 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
902 fn dec_strong(&self) {
903 self.inner().strong.set(self.strong() - 1);
907 fn weak(&self) -> usize {
908 self.inner().weak.get()
913 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
918 self.inner().weak.set(self.weak() - 1);
922 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
924 fn inner(&self) -> &RcBox<T> {
926 // Safe to assume this here, as if it weren't true, we'd be breaking
927 // the contract anyway.
928 // This allows the null check to be elided in the destructor if we
929 // manipulated the reference count in the same function.
930 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
936 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
938 fn inner(&self) -> &RcBox<T> {
940 // Safe to assume this here, as if it weren't true, we'd be breaking
941 // the contract anyway.
942 // This allows the null check to be elided in the destructor if we
943 // manipulated the reference count in the same function.
944 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
952 use super::{Rc, Weak};
954 use std::cell::RefCell;
955 use std::option::Option;
956 use std::option::Option::{None, Some};
957 use std::result::Result::{Err, Ok};
959 use std::clone::Clone;
960 use std::convert::From;
964 let x = Rc::new(RefCell::new(5));
966 *x.borrow_mut() = 20;
967 assert_eq!(*y.borrow(), 20);
977 fn test_simple_clone() {
985 fn test_destructor() {
986 let x: Rc<Box<_>> = Rc::new(box 5);
993 let y = Rc::downgrade(&x);
994 assert!(y.upgrade().is_some());
1000 let y = Rc::downgrade(&x);
1002 assert!(y.upgrade().is_none());
1006 fn weak_self_cyclic() {
1008 x: RefCell<Option<Weak<Cycle>>>,
1011 let a = Rc::new(Cycle { x: RefCell::new(None) });
1012 let b = Rc::downgrade(&a.clone());
1013 *a.x.borrow_mut() = Some(b);
1015 // hopefully we don't double-free (or leak)...
1021 assert!(Rc::is_unique(&x));
1023 assert!(!Rc::is_unique(&x));
1025 assert!(Rc::is_unique(&x));
1026 let w = Rc::downgrade(&x);
1027 assert!(!Rc::is_unique(&x));
1029 assert!(Rc::is_unique(&x));
1033 fn test_strong_count() {
1035 assert!(Rc::strong_count(&a) == 1);
1036 let w = Rc::downgrade(&a);
1037 assert!(Rc::strong_count(&a) == 1);
1038 let b = w.upgrade().expect("upgrade of live rc failed");
1039 assert!(Rc::strong_count(&b) == 2);
1040 assert!(Rc::strong_count(&a) == 2);
1043 assert!(Rc::strong_count(&b) == 1);
1045 assert!(Rc::strong_count(&b) == 2);
1046 assert!(Rc::strong_count(&c) == 2);
1050 fn test_weak_count() {
1052 assert!(Rc::strong_count(&a) == 1);
1053 assert!(Rc::weak_count(&a) == 0);
1054 let w = Rc::downgrade(&a);
1055 assert!(Rc::strong_count(&a) == 1);
1056 assert!(Rc::weak_count(&a) == 1);
1058 assert!(Rc::strong_count(&a) == 1);
1059 assert!(Rc::weak_count(&a) == 0);
1061 assert!(Rc::strong_count(&a) == 2);
1062 assert!(Rc::weak_count(&a) == 0);
1069 assert_eq!(Rc::try_unwrap(x), Ok(3));
1072 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1074 let _w = Rc::downgrade(&x);
1075 assert_eq!(Rc::try_unwrap(x), Ok(5));
1080 let mut x = Rc::new(3);
1081 *Rc::get_mut(&mut x).unwrap() = 4;
1084 assert!(Rc::get_mut(&mut x).is_none());
1086 assert!(Rc::get_mut(&mut x).is_some());
1087 let _w = Rc::downgrade(&x);
1088 assert!(Rc::get_mut(&mut x).is_none());
1092 fn test_cowrc_clone_make_unique() {
1093 let mut cow0 = Rc::new(75);
1094 let mut cow1 = cow0.clone();
1095 let mut cow2 = cow1.clone();
1097 assert!(75 == *Rc::make_mut(&mut cow0));
1098 assert!(75 == *Rc::make_mut(&mut cow1));
1099 assert!(75 == *Rc::make_mut(&mut cow2));
1101 *Rc::make_mut(&mut cow0) += 1;
1102 *Rc::make_mut(&mut cow1) += 2;
1103 *Rc::make_mut(&mut cow2) += 3;
1105 assert!(76 == *cow0);
1106 assert!(77 == *cow1);
1107 assert!(78 == *cow2);
1109 // none should point to the same backing memory
1110 assert!(*cow0 != *cow1);
1111 assert!(*cow0 != *cow2);
1112 assert!(*cow1 != *cow2);
1116 fn test_cowrc_clone_unique2() {
1117 let mut cow0 = Rc::new(75);
1118 let cow1 = cow0.clone();
1119 let cow2 = cow1.clone();
1121 assert!(75 == *cow0);
1122 assert!(75 == *cow1);
1123 assert!(75 == *cow2);
1125 *Rc::make_mut(&mut cow0) += 1;
1127 assert!(76 == *cow0);
1128 assert!(75 == *cow1);
1129 assert!(75 == *cow2);
1131 // cow1 and cow2 should share the same contents
1132 // cow0 should have a unique reference
1133 assert!(*cow0 != *cow1);
1134 assert!(*cow0 != *cow2);
1135 assert!(*cow1 == *cow2);
1139 fn test_cowrc_clone_weak() {
1140 let mut cow0 = Rc::new(75);
1141 let cow1_weak = Rc::downgrade(&cow0);
1143 assert!(75 == *cow0);
1144 assert!(75 == *cow1_weak.upgrade().unwrap());
1146 *Rc::make_mut(&mut cow0) += 1;
1148 assert!(76 == *cow0);
1149 assert!(cow1_weak.upgrade().is_none());
1154 let foo = Rc::new(75);
1155 assert_eq!(format!("{:?}", foo), "75");
1160 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1161 assert_eq!(foo, foo.clone());
1165 fn test_from_owned() {
1167 let foo_rc = Rc::from(foo);
1168 assert!(123 == *foo_rc);
1172 fn test_new_weak() {
1173 let foo: Weak<usize> = Weak::new();
1174 assert!(foo.upgrade().is_none());
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1180 fn borrow(&self) -> &T {
1185 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1186 impl<T: ?Sized> AsRef<T> for Rc<T> {
1187 fn as_ref(&self) -> &T {