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};
164 use heap::deallocate;
172 /// An immutable reference-counted pointer type.
174 /// See the [module level documentation](../index.html) for more details.
175 #[unsafe_no_drop_flag]
178 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
180 _ptr: NonZero<*mut RcBox<T>>,
183 impl<T> !marker::Send for Rc<T> {}
185 impl<T> !marker::Sync for Rc<T> {}
189 /// Constructs a new `Rc<T>`.
196 /// let five = Rc::new(5i);
199 pub fn new(value: T) -> Rc<T> {
202 // there is an implicit weak pointer owned by all the strong pointers, which
203 // ensures that the weak destructor never frees the allocation while the strong
204 // destructor is running, even if the weak pointer is stored inside the strong one.
205 _ptr: NonZero::new(transmute(box RcBox {
207 strong: Cell::new(1),
214 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
221 /// let five = Rc::new(5i);
223 /// let weak_five = five.downgrade();
225 #[unstable = "Weak pointers may not belong in this module"]
226 pub fn downgrade(&self) -> Weak<T> {
228 Weak { _ptr: self._ptr }
232 /// Get the number of weak references to this value.
235 pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 }
237 /// Get the number of strong references to this value.
240 pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
242 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
250 /// let five = Rc::new(5i);
252 /// rc::is_unique(&five);
256 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
257 weak_count(rc) == 0 && strong_count(rc) == 1
260 /// Unwraps the contained value if the `Rc<T>` is unique.
262 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
267 /// use std::rc::{self, Rc};
269 /// let x = Rc::new(3u);
270 /// assert_eq!(rc::try_unwrap(x), Ok(3u));
272 /// let x = Rc::new(4u);
273 /// let _y = x.clone();
274 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u)));
278 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
281 let val = ptr::read(&*rc); // copy the contained object
282 // destruct the box and skip our Drop
283 // we can ignore the refcounts because we know we're unique
284 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
285 min_align_of::<RcBox<T>>());
294 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
296 /// Returns `None` if the `Rc<T>` is not unique.
301 /// use std::rc::{self, Rc};
303 /// let mut x = Rc::new(3u);
304 /// *rc::get_mut(&mut x).unwrap() = 4u;
305 /// assert_eq!(*x, 4u);
307 /// let _y = x.clone();
308 /// assert!(rc::get_mut(&mut x).is_none());
312 pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {
314 let inner = unsafe { &mut **rc._ptr };
315 Some(&mut inner.value)
321 impl<T: Clone> Rc<T> {
322 /// Make a mutable reference from the given `Rc<T>`.
324 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
325 /// the reference count is greater than one.
332 /// let mut five = Rc::new(5i);
334 /// let mut_five = five.make_unique();
338 pub fn make_unique(&mut self) -> &mut T {
339 if !is_unique(self) {
340 *self = Rc::new((**self).clone())
342 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
343 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
344 // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
345 // possible reference to the inner value.
346 let inner = unsafe { &mut **self._ptr };
351 impl<T> BorrowFrom<Rc<T>> for T {
352 fn borrow_from(owned: &Rc<T>) -> &T {
358 impl<T> Deref for Rc<T> {
362 fn deref(&self) -> &T {
369 impl<T> Drop for Rc<T> {
370 /// Drops the `Rc<T>`.
372 /// This will decrement the strong reference count. If the strong reference count becomes zero
373 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
381 /// let five = Rc::new(5i);
385 /// drop(five); // explict drop
388 /// let five = Rc::new(5i);
392 /// } // implicit drop
396 let ptr = *self._ptr;
399 if self.strong() == 0 {
400 ptr::read(&**self); // destroy the contained object
402 // remove the implicit "strong weak" pointer now that we've destroyed the
406 if self.weak() == 0 {
407 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
408 min_align_of::<RcBox<T>>())
417 impl<T> Clone for Rc<T> {
419 /// Makes a clone of the `Rc<T>`.
421 /// This increases the strong reference count.
428 /// let five = Rc::new(5i);
433 fn clone(&self) -> Rc<T> {
435 Rc { _ptr: self._ptr }
440 impl<T: Default> Default for Rc<T> {
441 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
447 /// use std::default::Default;
449 /// let x: Rc<int> = Default::default();
453 fn default() -> Rc<T> {
454 Rc::new(Default::default())
459 impl<T: PartialEq> PartialEq for Rc<T> {
460 /// Equality for two `Rc<T>`s.
462 /// Two `Rc<T>`s are equal if their inner value are equal.
469 /// let five = Rc::new(5i);
471 /// five == Rc::new(5i);
474 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
476 /// Inequality for two `Rc<T>`s.
478 /// Two `Rc<T>`s are unequal if their inner value are unequal.
485 /// let five = Rc::new(5i);
487 /// five != Rc::new(5i);
490 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
494 impl<T: Eq> Eq for Rc<T> {}
497 impl<T: PartialOrd> PartialOrd for Rc<T> {
498 /// Partial comparison for two `Rc<T>`s.
500 /// The two are compared by calling `partial_cmp()` on their inner values.
507 /// let five = Rc::new(5i);
509 /// five.partial_cmp(&Rc::new(5i));
512 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
513 (**self).partial_cmp(&**other)
516 /// Less-than comparison for two `Rc<T>`s.
518 /// The two are compared by calling `<` on their inner values.
525 /// let five = Rc::new(5i);
527 /// five < Rc::new(5i);
530 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
532 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
534 /// The two are compared by calling `<=` on their inner values.
541 /// let five = Rc::new(5i);
543 /// five <= Rc::new(5i);
546 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
548 /// Greater-than comparison for two `Rc<T>`s.
550 /// The two are compared by calling `>` on their inner values.
557 /// let five = Rc::new(5i);
559 /// five > Rc::new(5i);
562 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
564 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
566 /// The two are compared by calling `>=` on their inner values.
573 /// let five = Rc::new(5i);
575 /// five >= Rc::new(5i);
578 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
582 impl<T: Ord> Ord for Rc<T> {
583 /// Comparison for two `Rc<T>`s.
585 /// The two are compared by calling `cmp()` on their inner values.
592 /// let five = Rc::new(5i);
594 /// five.partial_cmp(&Rc::new(5i));
597 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
600 // FIXME (#18248) Make `T` `Sized?`
601 impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> {
603 fn hash(&self, state: &mut S) {
604 (**self).hash(state);
608 #[unstable = "Show is experimental."]
609 impl<T: fmt::Show> fmt::Show for Rc<T> {
610 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611 write!(f, "Rc({:?})", **self)
616 impl<T: fmt::String> fmt::String for Rc<T> {
617 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
618 fmt::String::fmt(&**self, f)
622 /// A weak version of `Rc<T>`.
624 /// Weak references do not count when determining if the inner value should be dropped.
626 /// See the [module level documentation](../index.html) for more.
627 #[unsafe_no_drop_flag]
628 #[unstable = "Weak pointers may not belong in this module."]
630 // FIXME #12808: strange names to try to avoid interfering with
631 // field accesses of the contained type via Deref
632 _ptr: NonZero<*mut RcBox<T>>,
636 impl<T> !marker::Send for Weak<T> {}
639 impl<T> !marker::Sync for Weak<T> {}
642 #[unstable = "Weak pointers may not belong in this module."]
645 /// Upgrades a weak reference to a strong reference.
647 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
649 /// Returns `None` if there were no strong references and the data was destroyed.
656 /// let five = Rc::new(5i);
658 /// let weak_five = five.downgrade();
660 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
662 pub fn upgrade(&self) -> Option<Rc<T>> {
663 if self.strong() == 0 {
667 Some(Rc { _ptr: self._ptr })
674 impl<T> Drop for Weak<T> {
675 /// Drops the `Weak<T>`.
677 /// This will decrement the weak reference count.
685 /// let five = Rc::new(5i);
686 /// let weak_five = five.downgrade();
690 /// drop(weak_five); // explict drop
693 /// let five = Rc::new(5i);
694 /// let weak_five = five.downgrade();
698 /// } // implicit drop
702 let ptr = *self._ptr;
705 // the weak count starts at 1, and will only go to zero if all the strong pointers
707 if self.weak() == 0 {
708 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
709 min_align_of::<RcBox<T>>())
716 #[unstable = "Weak pointers may not belong in this module."]
717 impl<T> Clone for Weak<T> {
719 /// Makes a clone of the `Weak<T>`.
721 /// This increases the weak reference count.
728 /// let weak_five = Rc::new(5i).downgrade();
730 /// weak_five.clone();
733 fn clone(&self) -> Weak<T> {
735 Weak { _ptr: self._ptr }
739 #[unstable = "Show is experimental."]
740 impl<T: fmt::Show> fmt::Show for Weak<T> {
741 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
748 fn inner(&self) -> &RcBox<T>;
751 fn strong(&self) -> uint { self.inner().strong.get() }
754 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
757 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
760 fn weak(&self) -> uint { self.inner().weak.get() }
763 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
766 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
769 impl<T> RcBoxPtr<T> for Rc<T> {
771 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
774 impl<T> RcBoxPtr<T> for Weak<T> {
776 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
782 use super::{Rc, Weak, weak_count, strong_count};
783 use std::cell::RefCell;
784 use std::option::Option;
785 use std::option::Option::{Some, None};
786 use std::result::Result::{Err, Ok};
788 use std::clone::Clone;
792 let x = Rc::new(RefCell::new(5i));
794 *x.borrow_mut() = 20;
795 assert_eq!(*y.borrow(), 20);
805 fn test_simple_clone() {
813 fn test_destructor() {
814 let x = Rc::new(box 5i);
821 let y = x.downgrade();
822 assert!(y.upgrade().is_some());
828 let y = x.downgrade();
830 assert!(y.upgrade().is_none());
834 fn weak_self_cyclic() {
836 x: RefCell<Option<Weak<Cycle>>>
839 let a = Rc::new(Cycle { x: RefCell::new(None) });
840 let b = a.clone().downgrade();
841 *a.x.borrow_mut() = Some(b);
843 // hopefully we don't double-free (or leak)...
849 assert!(super::is_unique(&x));
851 assert!(!super::is_unique(&x));
853 assert!(super::is_unique(&x));
854 let w = x.downgrade();
855 assert!(!super::is_unique(&x));
857 assert!(super::is_unique(&x));
861 fn test_strong_count() {
862 let a = Rc::new(0u32);
863 assert!(strong_count(&a) == 1);
864 let w = a.downgrade();
865 assert!(strong_count(&a) == 1);
866 let b = w.upgrade().expect("upgrade of live rc failed");
867 assert!(strong_count(&b) == 2);
868 assert!(strong_count(&a) == 2);
871 assert!(strong_count(&b) == 1);
873 assert!(strong_count(&b) == 2);
874 assert!(strong_count(&c) == 2);
878 fn test_weak_count() {
879 let a = Rc::new(0u32);
880 assert!(strong_count(&a) == 1);
881 assert!(weak_count(&a) == 0);
882 let w = a.downgrade();
883 assert!(strong_count(&a) == 1);
884 assert!(weak_count(&a) == 1);
886 assert!(strong_count(&a) == 1);
887 assert!(weak_count(&a) == 0);
889 assert!(strong_count(&a) == 2);
890 assert!(weak_count(&a) == 0);
897 assert_eq!(super::try_unwrap(x), Ok(3u));
900 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
902 let _w = x.downgrade();
903 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
908 let mut x = Rc::new(3u);
909 *super::get_mut(&mut x).unwrap() = 4u;
912 assert!(super::get_mut(&mut x).is_none());
914 assert!(super::get_mut(&mut x).is_some());
915 let _w = x.downgrade();
916 assert!(super::get_mut(&mut x).is_none());
920 fn test_cowrc_clone_make_unique() {
921 let mut cow0 = Rc::new(75u);
922 let mut cow1 = cow0.clone();
923 let mut cow2 = cow1.clone();
925 assert!(75 == *cow0.make_unique());
926 assert!(75 == *cow1.make_unique());
927 assert!(75 == *cow2.make_unique());
929 *cow0.make_unique() += 1;
930 *cow1.make_unique() += 2;
931 *cow2.make_unique() += 3;
933 assert!(76 == *cow0);
934 assert!(77 == *cow1);
935 assert!(78 == *cow2);
937 // none should point to the same backing memory
938 assert!(*cow0 != *cow1);
939 assert!(*cow0 != *cow2);
940 assert!(*cow1 != *cow2);
944 fn test_cowrc_clone_unique2() {
945 let mut cow0 = Rc::new(75u);
946 let cow1 = cow0.clone();
947 let cow2 = cow1.clone();
949 assert!(75 == *cow0);
950 assert!(75 == *cow1);
951 assert!(75 == *cow2);
953 *cow0.make_unique() += 1;
955 assert!(76 == *cow0);
956 assert!(75 == *cow1);
957 assert!(75 == *cow2);
959 // cow1 and cow2 should share the same contents
960 // cow0 should have a unique reference
961 assert!(*cow0 != *cow1);
962 assert!(*cow0 != *cow2);
963 assert!(*cow1 == *cow2);
967 fn test_cowrc_clone_weak() {
968 let mut cow0 = Rc::new(75u);
969 let cow1_weak = cow0.downgrade();
971 assert!(75 == *cow0);
972 assert!(75 == *cow1_weak.upgrade().unwrap());
974 *cow0.make_unique() += 1;
976 assert!(76 == *cow0);
977 assert!(cow1_weak.upgrade().is_none());
982 let foo = Rc::new(75u);
983 assert!(format!("{:?}", foo) == "Rc(75u)")