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>>,
181 _nosend: marker::NoSend,
182 _noshare: marker::NoSync
186 /// Constructs a new `Rc<T>`.
193 /// let five = Rc::new(5i);
196 pub fn new(value: T) -> Rc<T> {
199 // there is an implicit weak pointer owned by all the strong pointers, which
200 // ensures that the weak destructor never frees the allocation while the strong
201 // destructor is running, even if the weak pointer is stored inside the strong one.
202 _ptr: NonZero::new(transmute(box RcBox {
204 strong: Cell::new(1),
207 _nosend: marker::NoSend,
208 _noshare: marker::NoSync
213 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
220 /// let five = Rc::new(5i);
222 /// let weak_five = five.downgrade();
224 #[experimental = "Weak pointers may not belong in this module"]
225 pub fn downgrade(&self) -> Weak<T> {
229 _nosend: marker::NoSend,
230 _noshare: marker::NoSync
235 /// Get the number of weak references to this value.
238 pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 }
240 /// Get the number of strong references to this value.
243 pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
245 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
253 /// let five = Rc::new(5i);
255 /// rc::is_unique(&five);
259 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
260 weak_count(rc) == 0 && strong_count(rc) == 1
263 /// Unwraps the contained value if the `Rc<T>` is unique.
265 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
270 /// use std::rc::{self, Rc};
272 /// let x = Rc::new(3u);
273 /// assert_eq!(rc::try_unwrap(x), Ok(3u));
275 /// let x = Rc::new(4u);
276 /// let _y = x.clone();
277 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u)));
281 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
284 let val = ptr::read(&*rc); // copy the contained object
285 // destruct the box and skip our Drop
286 // we can ignore the refcounts because we know we're unique
287 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
288 min_align_of::<RcBox<T>>());
297 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
299 /// Returns `None` if the `Rc<T>` is not unique.
304 /// use std::rc::{self, Rc};
306 /// let mut x = Rc::new(3u);
307 /// *rc::get_mut(&mut x).unwrap() = 4u;
308 /// assert_eq!(*x, 4u);
310 /// let _y = x.clone();
311 /// assert!(rc::get_mut(&mut x).is_none());
315 pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {
317 let inner = unsafe { &mut **rc._ptr };
318 Some(&mut inner.value)
324 impl<T: Clone> Rc<T> {
325 /// Make a mutable reference from the given `Rc<T>`.
327 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
328 /// the reference count is greater than one.
335 /// let mut five = Rc::new(5i);
337 /// let mut_five = five.make_unique();
341 pub fn make_unique(&mut self) -> &mut T {
342 if !is_unique(self) {
343 *self = Rc::new((**self).clone())
345 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
346 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
347 // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
348 // possible reference to the inner value.
349 let inner = unsafe { &mut **self._ptr };
354 impl<T> BorrowFrom<Rc<T>> for T {
355 fn borrow_from(owned: &Rc<T>) -> &T {
361 impl<T> Deref for Rc<T> {
365 fn deref(&self) -> &T {
372 impl<T> Drop for Rc<T> {
373 /// Drops the `Rc<T>`.
375 /// This will decrement the strong reference count. If the strong reference count becomes zero
376 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
384 /// let five = Rc::new(5i);
388 /// drop(five); // explict drop
391 /// let five = Rc::new(5i);
395 /// } // implicit drop
399 let ptr = *self._ptr;
402 if self.strong() == 0 {
403 ptr::read(&**self); // destroy the contained object
405 // remove the implicit "strong weak" pointer now that we've destroyed the
409 if self.weak() == 0 {
410 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
411 min_align_of::<RcBox<T>>())
420 impl<T> Clone for Rc<T> {
421 /// Makes a clone of the `Rc<T>`.
423 /// This increases the strong reference count.
430 /// let five = Rc::new(5i);
435 fn clone(&self) -> Rc<T> {
437 Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
442 impl<T: Default> Default for Rc<T> {
443 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
449 /// use std::default::Default;
451 /// let x: Rc<int> = Default::default();
455 fn default() -> Rc<T> {
456 Rc::new(Default::default())
461 impl<T: PartialEq> PartialEq for Rc<T> {
462 /// Equality for two `Rc<T>`s.
464 /// Two `Rc<T>`s are equal if their inner value are equal.
471 /// let five = Rc::new(5i);
473 /// five == Rc::new(5i);
476 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
478 /// Inequality for two `Rc<T>`s.
480 /// Two `Rc<T>`s are unequal if their inner value are unequal.
487 /// let five = Rc::new(5i);
489 /// five != Rc::new(5i);
492 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
496 impl<T: Eq> Eq for Rc<T> {}
499 impl<T: PartialOrd> PartialOrd for Rc<T> {
500 /// Partial comparison for two `Rc<T>`s.
502 /// The two are compared by calling `partial_cmp()` on their inner values.
509 /// let five = Rc::new(5i);
511 /// five.partial_cmp(&Rc::new(5i));
514 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
515 (**self).partial_cmp(&**other)
518 /// Less-than comparison for two `Rc<T>`s.
520 /// The two are compared by calling `<` on their inner values.
527 /// let five = Rc::new(5i);
529 /// five < Rc::new(5i);
532 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
534 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
536 /// The two are compared by calling `<=` on their inner values.
543 /// let five = Rc::new(5i);
545 /// five <= Rc::new(5i);
548 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
550 /// Greater-than comparison for two `Rc<T>`s.
552 /// The two are compared by calling `>` on their inner values.
559 /// let five = Rc::new(5i);
561 /// five > Rc::new(5i);
564 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
566 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
568 /// The two are compared by calling `>=` on their inner values.
575 /// let five = Rc::new(5i);
577 /// five >= Rc::new(5i);
580 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
584 impl<T: Ord> Ord for Rc<T> {
585 /// Comparison for two `Rc<T>`s.
587 /// The two are compared by calling `cmp()` on their inner values.
594 /// let five = Rc::new(5i);
596 /// five.partial_cmp(&Rc::new(5i));
599 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
602 // FIXME (#18248) Make `T` `Sized?`
604 impl<S: hash::Writer, T: Hash<S>> Hash<S> for Rc<T> {
606 fn hash(&self, state: &mut S) {
607 (**self).hash(state);
611 impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> {
613 fn hash(&self, state: &mut S) {
614 (**self).hash(state);
618 #[experimental = "Show is experimental."]
619 impl<T: fmt::Show> fmt::Show for Rc<T> {
620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
621 write!(f, "Rc({:?})", **self)
625 /// A weak version of `Rc<T>`.
627 /// Weak references do not count when determining if the inner value should be dropped.
629 /// See the [module level documentation](../index.html) for more.
630 #[unsafe_no_drop_flag]
631 #[experimental = "Weak pointers may not belong in this module."]
633 // FIXME #12808: strange names to try to avoid interfering with
634 // field accesses of the contained type via Deref
635 _ptr: NonZero<*mut RcBox<T>>,
636 _nosend: marker::NoSend,
637 _noshare: marker::NoSync
640 #[experimental = "Weak pointers may not belong in this module."]
642 /// Upgrades a weak reference to a strong reference.
644 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
646 /// Returns `None` if there were no strong references and the data was destroyed.
653 /// let five = Rc::new(5i);
655 /// let weak_five = five.downgrade();
657 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
659 pub fn upgrade(&self) -> Option<Rc<T>> {
660 if self.strong() == 0 {
664 Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync })
671 impl<T> Drop for Weak<T> {
672 /// Drops the `Weak<T>`.
674 /// This will decrement the weak reference count.
682 /// let five = Rc::new(5i);
683 /// let weak_five = five.downgrade();
687 /// drop(weak_five); // explict drop
690 /// let five = Rc::new(5i);
691 /// let weak_five = five.downgrade();
695 /// } // implicit drop
699 let ptr = *self._ptr;
702 // the weak count starts at 1, and will only go to zero if all the strong pointers
704 if self.weak() == 0 {
705 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
706 min_align_of::<RcBox<T>>())
713 #[experimental = "Weak pointers may not belong in this module."]
714 impl<T> Clone for Weak<T> {
715 /// Makes a clone of the `Weak<T>`.
717 /// This increases the weak reference count.
724 /// let weak_five = Rc::new(5i).downgrade();
726 /// weak_five.clone();
729 fn clone(&self) -> Weak<T> {
731 Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
735 #[experimental = "Show is experimental."]
736 impl<T: fmt::Show> fmt::Show for Weak<T> {
737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
744 fn inner(&self) -> &RcBox<T>;
747 fn strong(&self) -> uint { self.inner().strong.get() }
750 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
753 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
756 fn weak(&self) -> uint { self.inner().weak.get() }
759 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
762 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
765 impl<T> RcBoxPtr<T> for Rc<T> {
767 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
770 impl<T> RcBoxPtr<T> for Weak<T> {
772 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
776 #[allow(experimental)]
778 use super::{Rc, Weak, weak_count, strong_count};
779 use std::cell::RefCell;
780 use std::option::Option;
781 use std::option::Option::{Some, None};
782 use std::result::Result::{Err, Ok};
784 use std::clone::Clone;
788 let x = Rc::new(RefCell::new(5i));
790 *x.borrow_mut() = 20;
791 assert_eq!(*y.borrow(), 20);
801 fn test_simple_clone() {
809 fn test_destructor() {
810 let x = Rc::new(box 5i);
817 let y = x.downgrade();
818 assert!(y.upgrade().is_some());
824 let y = x.downgrade();
826 assert!(y.upgrade().is_none());
830 fn weak_self_cyclic() {
832 x: RefCell<Option<Weak<Cycle>>>
835 let a = Rc::new(Cycle { x: RefCell::new(None) });
836 let b = a.clone().downgrade();
837 *a.x.borrow_mut() = Some(b);
839 // hopefully we don't double-free (or leak)...
845 assert!(super::is_unique(&x));
847 assert!(!super::is_unique(&x));
849 assert!(super::is_unique(&x));
850 let w = x.downgrade();
851 assert!(!super::is_unique(&x));
853 assert!(super::is_unique(&x));
857 fn test_strong_count() {
858 let a = Rc::new(0u32);
859 assert!(strong_count(&a) == 1);
860 let w = a.downgrade();
861 assert!(strong_count(&a) == 1);
862 let b = w.upgrade().expect("upgrade of live rc failed");
863 assert!(strong_count(&b) == 2);
864 assert!(strong_count(&a) == 2);
867 assert!(strong_count(&b) == 1);
869 assert!(strong_count(&b) == 2);
870 assert!(strong_count(&c) == 2);
874 fn test_weak_count() {
875 let a = Rc::new(0u32);
876 assert!(strong_count(&a) == 1);
877 assert!(weak_count(&a) == 0);
878 let w = a.downgrade();
879 assert!(strong_count(&a) == 1);
880 assert!(weak_count(&a) == 1);
882 assert!(strong_count(&a) == 1);
883 assert!(weak_count(&a) == 0);
885 assert!(strong_count(&a) == 2);
886 assert!(weak_count(&a) == 0);
893 assert_eq!(super::try_unwrap(x), Ok(3u));
896 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
898 let _w = x.downgrade();
899 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
904 let mut x = Rc::new(3u);
905 *super::get_mut(&mut x).unwrap() = 4u;
908 assert!(super::get_mut(&mut x).is_none());
910 assert!(super::get_mut(&mut x).is_some());
911 let _w = x.downgrade();
912 assert!(super::get_mut(&mut x).is_none());
916 fn test_cowrc_clone_make_unique() {
917 let mut cow0 = Rc::new(75u);
918 let mut cow1 = cow0.clone();
919 let mut cow2 = cow1.clone();
921 assert!(75 == *cow0.make_unique());
922 assert!(75 == *cow1.make_unique());
923 assert!(75 == *cow2.make_unique());
925 *cow0.make_unique() += 1;
926 *cow1.make_unique() += 2;
927 *cow2.make_unique() += 3;
929 assert!(76 == *cow0);
930 assert!(77 == *cow1);
931 assert!(78 == *cow2);
933 // none should point to the same backing memory
934 assert!(*cow0 != *cow1);
935 assert!(*cow0 != *cow2);
936 assert!(*cow1 != *cow2);
940 fn test_cowrc_clone_unique2() {
941 let mut cow0 = Rc::new(75u);
942 let cow1 = cow0.clone();
943 let cow2 = cow1.clone();
945 assert!(75 == *cow0);
946 assert!(75 == *cow1);
947 assert!(75 == *cow2);
949 *cow0.make_unique() += 1;
951 assert!(76 == *cow0);
952 assert!(75 == *cow1);
953 assert!(75 == *cow2);
955 // cow1 and cow2 should share the same contents
956 // cow0 should have a unique reference
957 assert!(*cow0 != *cow1);
958 assert!(*cow0 != *cow2);
959 assert!(*cow1 == *cow2);
963 fn test_cowrc_clone_weak() {
964 let mut cow0 = Rc::new(75u);
965 let cow1_weak = cow0.downgrade();
967 assert!(75 == *cow0);
968 assert!(75 == *cow1_weak.upgrade().unwrap());
970 *cow0.make_unique() += 1;
972 assert!(76 == *cow0);
973 assert!(cow1_weak.upgrade().is_none());
978 let foo = Rc::new(75u);
979 assert!(format!("{:?}", foo) == "Rc(75u)")