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.
11 //! Thread-local reference-counted boxes (the `Rc<T>` type).
13 //! The `Rc<T>` type provides shared ownership of an immutable value.
14 //! Destruction is deterministic, and will occur as soon as the last owner is
15 //! gone. It is marked as non-sendable because it avoids the overhead of atomic
16 //! reference counting.
18 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
19 //! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but
20 //! will return `None` if the value has already been dropped.
22 //! For example, a tree with parent pointers can be represented by putting the
23 //! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers
24 //! as `Weak<T>` pointers.
28 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
29 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
30 //! unique ownership, because more than one gadget may belong to the same
31 //! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s,
32 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
39 //! // ...other fields
45 //! // ...other fields
49 //! // Create a reference counted Owner.
50 //! let gadget_owner : Rc<Owner> = Rc::new(
51 //! Owner { name: String::from_str("Gadget Man") }
54 //! // Create Gadgets belonging to gadget_owner. To increment the reference
55 //! // count we clone the `Rc<T>` object.
56 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
57 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
59 //! drop(gadget_owner);
61 //! // Despite dropping gadget_owner, we're still able to print out the name of
62 //! // the Owner of the Gadgets. This is because we've only dropped the
63 //! // reference count object, not the Owner it wraps. As long as there are
64 //! // other `Rc<T>` objects pointing at the same Owner, it will remain allocated. Notice
65 //! // that the `Rc<T>` wrapper around Gadget.owner gets automatically dereferenced
67 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
68 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
70 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
71 //! // them the last counted references to our Owner. Gadget Man now gets
72 //! // destroyed as well.
76 //! If our requirements change, and we also need to be able to traverse from Owner → Gadget, we
77 //! will run into problems: an `Rc<T>` pointer from Owner → Gadget introduces a cycle between the
78 //! objects. This means that their reference counts can never reach 0, and the objects will remain
79 //! allocated: a memory leak. In order to get around this, we can use `Weak<T>` pointers. These
80 //! pointers don't contribute to the total count.
82 //! Rust actually makes it somewhat difficult to produce this loop in the first place: in order to
83 //! end up with two objects that point at each other, one of them needs to be mutable. This is
84 //! problematic because `Rc<T>` enforces memory safety by only giving out shared references to the
85 //! object it wraps, and these don't allow direct mutation. We need to wrap the part of the object
86 //! we wish to mutate in a `RefCell`, which provides *interior mutability*: a method to achieve
87 //! mutability through a shared reference. `RefCell` enforces Rust's borrowing rules at runtime.
88 //! Read the `Cell` documentation for more details on interior mutability.
92 //! use std::rc::Weak;
93 //! use std::cell::RefCell;
97 //! gadgets: RefCell<Vec<Weak<Gadget>>>
98 //! // ...other fields
104 //! // ...other fields
108 //! // Create a reference counted Owner. Note the fact that we've put the
109 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
110 //! // through a shared reference.
111 //! let gadget_owner : Rc<Owner> = Rc::new(
113 //! name: "Gadget Man".to_string(),
114 //! gadgets: RefCell::new(Vec::new())
118 //! // Create Gadgets belonging to gadget_owner as before.
119 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
120 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
122 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
123 //! // the RefCell holding the Owner's Gadgets.
124 //! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
125 //! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
127 //! // Iterate over our Gadgets, printing their details out
128 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
130 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
131 //! // that their object is still allocated, we need to call upgrade() on them
132 //! // to turn them into a strong reference. This returns an Option, which
133 //! // contains a reference to our object if it still exists.
134 //! let gadget = gadget_opt.upgrade().unwrap();
135 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
138 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
139 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
140 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
141 //! // reference count on Gadget Man, so he gets destroyed as well.
147 use core::borrow::BorrowFrom;
148 use core::cell::Cell;
149 use core::clone::Clone;
150 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
151 use core::default::Default;
153 use core::hash::{self, Hash};
155 use core::mem::{transmute, min_align_of, size_of, forget};
156 use core::nonzero::NonZero;
157 use core::ops::{Deref, Drop};
158 use core::option::Option;
159 use core::option::Option::{Some, None};
160 use core::ptr::{self, PtrExt};
161 use core::result::Result;
162 use core::result::Result::{Ok, Err};
163 use core::intrinsics::assume;
165 use heap::deallocate;
173 /// An immutable reference-counted pointer type.
175 /// See the [module level documentation](../index.html) for more details.
176 #[unsafe_no_drop_flag]
179 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
181 _ptr: NonZero<*mut RcBox<T>>,
184 impl<T> !marker::Send for Rc<T> {}
186 impl<T> !marker::Sync for Rc<T> {}
190 /// Constructs a new `Rc<T>`.
197 /// let five = Rc::new(5i);
200 pub fn new(value: T) -> Rc<T> {
203 // there is an implicit weak pointer owned by all the strong pointers, which
204 // ensures that the weak destructor never frees the allocation while the strong
205 // destructor is running, even if the weak pointer is stored inside the strong one.
206 _ptr: NonZero::new(transmute(box RcBox {
208 strong: Cell::new(1),
215 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
222 /// let five = Rc::new(5i);
224 /// let weak_five = five.downgrade();
226 #[unstable = "Weak pointers may not belong in this module"]
227 pub fn downgrade(&self) -> Weak<T> {
229 Weak { _ptr: self._ptr }
233 /// Get the number of weak references to this value.
236 pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 }
238 /// Get the number of strong references to this value.
241 pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
243 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
251 /// let five = Rc::new(5i);
253 /// rc::is_unique(&five);
257 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
258 weak_count(rc) == 0 && strong_count(rc) == 1
261 /// Unwraps the contained value if the `Rc<T>` is unique.
263 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
268 /// use std::rc::{self, Rc};
270 /// let x = Rc::new(3u);
271 /// assert_eq!(rc::try_unwrap(x), Ok(3u));
273 /// let x = Rc::new(4u);
274 /// let _y = x.clone();
275 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u)));
279 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
282 let val = ptr::read(&*rc); // copy the contained object
283 // destruct the box and skip our Drop
284 // we can ignore the refcounts because we know we're unique
285 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
286 min_align_of::<RcBox<T>>());
295 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
297 /// Returns `None` if the `Rc<T>` is not unique.
302 /// use std::rc::{self, Rc};
304 /// let mut x = Rc::new(3u);
305 /// *rc::get_mut(&mut x).unwrap() = 4u;
306 /// assert_eq!(*x, 4u);
308 /// let _y = x.clone();
309 /// assert!(rc::get_mut(&mut x).is_none());
313 pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {
315 let inner = unsafe { &mut **rc._ptr };
316 Some(&mut inner.value)
322 impl<T: Clone> Rc<T> {
323 /// Make a mutable reference from the given `Rc<T>`.
325 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
326 /// the reference count is greater than one.
333 /// let mut five = Rc::new(5i);
335 /// let mut_five = five.make_unique();
339 pub fn make_unique(&mut self) -> &mut T {
340 if !is_unique(self) {
341 *self = Rc::new((**self).clone())
343 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
344 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
345 // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
346 // possible reference to the inner value.
347 let inner = unsafe { &mut **self._ptr };
352 impl<T> BorrowFrom<Rc<T>> for T {
353 fn borrow_from(owned: &Rc<T>) -> &T {
359 impl<T> Deref for Rc<T> {
363 fn deref(&self) -> &T {
370 impl<T> Drop for Rc<T> {
371 /// Drops the `Rc<T>`.
373 /// This will decrement the strong reference count. If the strong reference count becomes zero
374 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
382 /// let five = Rc::new(5i);
386 /// drop(five); // explict drop
389 /// let five = Rc::new(5i);
393 /// } // implicit drop
397 let ptr = *self._ptr;
400 if self.strong() == 0 {
401 ptr::read(&**self); // destroy the contained object
403 // remove the implicit "strong weak" pointer now that we've destroyed the
407 if self.weak() == 0 {
408 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
409 min_align_of::<RcBox<T>>())
418 impl<T> Clone for Rc<T> {
420 /// Makes a clone of the `Rc<T>`.
422 /// This increases the strong reference count.
429 /// let five = Rc::new(5i);
434 fn clone(&self) -> Rc<T> {
436 Rc { _ptr: self._ptr }
441 impl<T: Default> Default for Rc<T> {
442 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
448 /// use std::default::Default;
450 /// let x: Rc<int> = Default::default();
454 fn default() -> Rc<T> {
455 Rc::new(Default::default())
460 impl<T: PartialEq> PartialEq for Rc<T> {
461 /// Equality for two `Rc<T>`s.
463 /// Two `Rc<T>`s are equal if their inner value are equal.
470 /// let five = Rc::new(5i);
472 /// five == Rc::new(5i);
475 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
477 /// Inequality for two `Rc<T>`s.
479 /// Two `Rc<T>`s are unequal if their inner value are unequal.
486 /// let five = Rc::new(5i);
488 /// five != Rc::new(5i);
491 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
495 impl<T: Eq> Eq for Rc<T> {}
498 impl<T: PartialOrd> PartialOrd for Rc<T> {
499 /// Partial comparison for two `Rc<T>`s.
501 /// The two are compared by calling `partial_cmp()` on their inner values.
508 /// let five = Rc::new(5i);
510 /// five.partial_cmp(&Rc::new(5i));
513 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
514 (**self).partial_cmp(&**other)
517 /// Less-than comparison for two `Rc<T>`s.
519 /// The two are compared by calling `<` on their inner values.
526 /// let five = Rc::new(5i);
528 /// five < Rc::new(5i);
531 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
533 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
535 /// The two are compared by calling `<=` on their inner values.
542 /// let five = Rc::new(5i);
544 /// five <= Rc::new(5i);
547 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
549 /// Greater-than comparison for two `Rc<T>`s.
551 /// The two are compared by calling `>` on their inner values.
558 /// let five = Rc::new(5i);
560 /// five > Rc::new(5i);
563 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
565 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
567 /// The two are compared by calling `>=` on their inner values.
574 /// let five = Rc::new(5i);
576 /// five >= Rc::new(5i);
579 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
583 impl<T: Ord> Ord for Rc<T> {
584 /// Comparison for two `Rc<T>`s.
586 /// The two are compared by calling `cmp()` on their inner values.
593 /// let five = Rc::new(5i);
595 /// five.partial_cmp(&Rc::new(5i));
598 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
601 // FIXME (#18248) Make `T` `Sized?`
602 impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> {
604 fn hash(&self, state: &mut S) {
605 (**self).hash(state);
610 impl<T: fmt::Display> fmt::Display for Rc<T> {
611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
612 fmt::Display::fmt(&**self, f)
617 impl<T: fmt::Debug> fmt::Debug for Rc<T> {
618 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
619 fmt::Debug::fmt(&**self, f)
623 /// A weak version of `Rc<T>`.
625 /// Weak references do not count when determining if the inner value should be dropped.
627 /// See the [module level documentation](../index.html) for more.
628 #[unsafe_no_drop_flag]
629 #[unstable = "Weak pointers may not belong in this module."]
631 // FIXME #12808: strange names to try to avoid interfering with
632 // field accesses of the contained type via Deref
633 _ptr: NonZero<*mut RcBox<T>>,
637 impl<T> !marker::Send for Weak<T> {}
640 impl<T> !marker::Sync for Weak<T> {}
643 #[unstable = "Weak pointers may not belong in this module."]
646 /// Upgrades a weak reference to a strong reference.
648 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
650 /// Returns `None` if there were no strong references and the data was destroyed.
657 /// let five = Rc::new(5i);
659 /// let weak_five = five.downgrade();
661 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
663 pub fn upgrade(&self) -> Option<Rc<T>> {
664 if self.strong() == 0 {
668 Some(Rc { _ptr: self._ptr })
675 impl<T> Drop for Weak<T> {
676 /// Drops the `Weak<T>`.
678 /// This will decrement the weak reference count.
686 /// let five = Rc::new(5i);
687 /// let weak_five = five.downgrade();
691 /// drop(weak_five); // explict drop
694 /// let five = Rc::new(5i);
695 /// let weak_five = five.downgrade();
699 /// } // implicit drop
703 let ptr = *self._ptr;
706 // the weak count starts at 1, and will only go to zero if all the strong pointers
708 if self.weak() == 0 {
709 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
710 min_align_of::<RcBox<T>>())
717 #[unstable = "Weak pointers may not belong in this module."]
718 impl<T> Clone for Weak<T> {
720 /// Makes a clone of the `Weak<T>`.
722 /// This increases the weak reference count.
729 /// let weak_five = Rc::new(5i).downgrade();
731 /// weak_five.clone();
734 fn clone(&self) -> Weak<T> {
736 Weak { _ptr: self._ptr }
741 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
749 fn inner(&self) -> &RcBox<T>;
752 fn strong(&self) -> uint { self.inner().strong.get() }
755 fn inc_strong(&self) {
756 let strong = self.strong();
757 // The reference count is always at least one unless we're about to drop the type
758 // This allows the bulk of the destructor to be omitted in cases where we know that
759 // the reference count must be > 0.
760 unsafe { assume(strong > 0); }
761 self.inner().strong.set(strong + 1);
765 fn dec_strong(&self) {
766 let strong = self.strong();
767 // The reference count is always at least one unless we're about to drop the type
768 // This allows the bulk of the destructor to be omitted in cases where we know that
769 // the reference count must be > 0
770 unsafe { assume(strong > 0); }
771 self.inner().strong.set(strong - 1);
775 fn weak(&self) -> uint { self.inner().weak.get() }
778 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
781 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
784 impl<T> RcBoxPtr<T> for Rc<T> {
786 fn inner(&self) -> &RcBox<T> {
788 // Safe to assume this here, as if it weren't true, we'd be breaking
789 // the contract anyway.
790 // This allows the null check to be elided in the destructor if we
791 // manipulated the reference count in the same function.
792 assume(!self._ptr.is_null());
798 impl<T> RcBoxPtr<T> for Weak<T> {
800 fn inner(&self) -> &RcBox<T> {
802 // Safe to assume this here, as if it weren't true, we'd be breaking
803 // the contract anyway
804 // This allows the null check to be elided in the destructor if we
805 // manipulated the reference count in the same function.
806 assume(!self._ptr.is_null());
815 use super::{Rc, Weak, weak_count, strong_count};
816 use std::cell::RefCell;
817 use std::option::Option;
818 use std::option::Option::{Some, None};
819 use std::result::Result::{Err, Ok};
821 use std::clone::Clone;
825 let x = Rc::new(RefCell::new(5i));
827 *x.borrow_mut() = 20;
828 assert_eq!(*y.borrow(), 20);
838 fn test_simple_clone() {
846 fn test_destructor() {
847 let x = Rc::new(box 5i);
854 let y = x.downgrade();
855 assert!(y.upgrade().is_some());
861 let y = x.downgrade();
863 assert!(y.upgrade().is_none());
867 fn weak_self_cyclic() {
869 x: RefCell<Option<Weak<Cycle>>>
872 let a = Rc::new(Cycle { x: RefCell::new(None) });
873 let b = a.clone().downgrade();
874 *a.x.borrow_mut() = Some(b);
876 // hopefully we don't double-free (or leak)...
882 assert!(super::is_unique(&x));
884 assert!(!super::is_unique(&x));
886 assert!(super::is_unique(&x));
887 let w = x.downgrade();
888 assert!(!super::is_unique(&x));
890 assert!(super::is_unique(&x));
894 fn test_strong_count() {
895 let a = Rc::new(0u32);
896 assert!(strong_count(&a) == 1);
897 let w = a.downgrade();
898 assert!(strong_count(&a) == 1);
899 let b = w.upgrade().expect("upgrade of live rc failed");
900 assert!(strong_count(&b) == 2);
901 assert!(strong_count(&a) == 2);
904 assert!(strong_count(&b) == 1);
906 assert!(strong_count(&b) == 2);
907 assert!(strong_count(&c) == 2);
911 fn test_weak_count() {
912 let a = Rc::new(0u32);
913 assert!(strong_count(&a) == 1);
914 assert!(weak_count(&a) == 0);
915 let w = a.downgrade();
916 assert!(strong_count(&a) == 1);
917 assert!(weak_count(&a) == 1);
919 assert!(strong_count(&a) == 1);
920 assert!(weak_count(&a) == 0);
922 assert!(strong_count(&a) == 2);
923 assert!(weak_count(&a) == 0);
930 assert_eq!(super::try_unwrap(x), Ok(3u));
933 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
935 let _w = x.downgrade();
936 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
941 let mut x = Rc::new(3u);
942 *super::get_mut(&mut x).unwrap() = 4u;
945 assert!(super::get_mut(&mut x).is_none());
947 assert!(super::get_mut(&mut x).is_some());
948 let _w = x.downgrade();
949 assert!(super::get_mut(&mut x).is_none());
953 fn test_cowrc_clone_make_unique() {
954 let mut cow0 = Rc::new(75u);
955 let mut cow1 = cow0.clone();
956 let mut cow2 = cow1.clone();
958 assert!(75 == *cow0.make_unique());
959 assert!(75 == *cow1.make_unique());
960 assert!(75 == *cow2.make_unique());
962 *cow0.make_unique() += 1;
963 *cow1.make_unique() += 2;
964 *cow2.make_unique() += 3;
966 assert!(76 == *cow0);
967 assert!(77 == *cow1);
968 assert!(78 == *cow2);
970 // none should point to the same backing memory
971 assert!(*cow0 != *cow1);
972 assert!(*cow0 != *cow2);
973 assert!(*cow1 != *cow2);
977 fn test_cowrc_clone_unique2() {
978 let mut cow0 = Rc::new(75u);
979 let cow1 = cow0.clone();
980 let cow2 = cow1.clone();
982 assert!(75 == *cow0);
983 assert!(75 == *cow1);
984 assert!(75 == *cow2);
986 *cow0.make_unique() += 1;
988 assert!(76 == *cow0);
989 assert!(75 == *cow1);
990 assert!(75 == *cow2);
992 // cow1 and cow2 should share the same contents
993 // cow0 should have a unique reference
994 assert!(*cow0 != *cow1);
995 assert!(*cow0 != *cow2);
996 assert!(*cow1 == *cow2);
1000 fn test_cowrc_clone_weak() {
1001 let mut cow0 = Rc::new(75u);
1002 let cow1_weak = cow0.downgrade();
1004 assert!(75 == *cow0);
1005 assert!(75 == *cow1_weak.upgrade().unwrap());
1007 *cow0.make_unique() += 1;
1009 assert!(76 == *cow0);
1010 assert!(cow1_weak.upgrade().is_none());
1015 let foo = Rc::new(75u);
1016 assert_eq!(format!("{:?}", foo), "75");