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. Destruction is deterministic,
14 //! and will occur as soon as the last owner is gone. It is marked as non-sendable because it
15 //! avoids the overhead of atomic reference counting.
17 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer to the box. A
18 //! `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but will return `None` if the value
19 //! has already been dropped.
21 //! For example, a tree with parent pointers can be represented by putting the nodes behind strong
22 //! `Rc<T>` pointers, and then storing the parent pointers as `Weak<T>` pointers.
26 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. We want to have our
27 //! `Gadget`s point to their `Owner`. We can't do this with unique ownership, because more than one
28 //! gadget may belong to the same `Owner`. `Rc<T>` allows us to share an `Owner` between multiple
29 //! `Gadget`s, and have the `Owner` remain allocated as long as any `Gadget` points at it.
36 //! // ...other fields
42 //! // ...other fields
46 //! // Create a reference counted Owner.
47 //! let gadget_owner : Rc<Owner> = Rc::new(
48 //! Owner { name: String::from_str("Gadget Man") }
51 //! // Create Gadgets belonging to gadget_owner. To increment the reference
52 //! // count we clone the `Rc<T>` object.
53 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
54 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
56 //! drop(gadget_owner);
58 //! // Despite dropping gadget_owner, we're still able to print out the name of
59 //! // the Owner of the Gadgets. This is because we've only dropped the
60 //! // reference count object, not the Owner it wraps. As long as there are
61 //! // other `Rc<T>` objects pointing at the same Owner, it will remain allocated. Notice
62 //! // that the `Rc<T>` wrapper around Gadget.owner gets automatically dereferenced
64 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
65 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
67 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
68 //! // them the last counted references to our Owner. Gadget Man now gets
69 //! // destroyed as well.
73 //! If our requirements change, and we also need to be able to traverse from Owner → Gadget, we
74 //! will run into problems: an `Rc<T>` pointer from Owner → Gadget introduces a cycle between the
75 //! objects. This means that their reference counts can never reach 0, and the objects will remain
76 //! allocated: a memory leak. In order to get around this, we can use `Weak<T>` pointers. These
77 //! pointers don't contribute to the total count.
79 //! Rust actually makes it somewhat difficult to produce this loop in the first place: in order to
80 //! end up with two objects that point at each other, one of them needs to be mutable. This is
81 //! problematic because `Rc<T>` enforces memory safety by only giving out shared references to the
82 //! object it wraps, and these don't allow direct mutation. We need to wrap the part of the object
83 //! we wish to mutate in a `RefCell`, which provides *interior mutability*: a method to achieve
84 //! mutability through a shared reference. `RefCell` enforces Rust's borrowing rules at runtime.
85 //! Read the `Cell` documentation for more details on interior mutability.
89 //! use std::rc::Weak;
90 //! use std::cell::RefCell;
94 //! gadgets: RefCell<Vec<Weak<Gadget>>>
95 //! // ...other fields
101 //! // ...other fields
105 //! // Create a reference counted Owner. Note the fact that we've put the
106 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
107 //! // through a shared reference.
108 //! let gadget_owner : Rc<Owner> = Rc::new(
110 //! name: "Gadget Man".to_string(),
111 //! gadgets: RefCell::new(Vec::new())
115 //! // Create Gadgets belonging to gadget_owner as before.
116 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
117 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
119 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
120 //! // the RefCell holding the Owner's Gadgets.
121 //! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
122 //! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
124 //! // Iterate over our Gadgets, printing their details out
125 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
127 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
128 //! // that their object is still allocated, we need to call upgrade() on them
129 //! // to turn them into a strong reference. This returns an Option, which
130 //! // contains a reference to our object if it still exists.
131 //! let gadget = gadget_opt.upgrade().unwrap();
132 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
135 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
136 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
137 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
138 //! // reference count on Gadget Man, so he gets destroyed as well.
144 use core::borrow::BorrowFrom;
145 use core::cell::Cell;
146 use core::clone::Clone;
147 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
148 use core::default::Default;
150 use core::hash::{mod, Hash};
151 use core::kinds::marker;
152 use core::mem::{transmute, min_align_of, size_of, forget};
153 use core::nonzero::NonZero;
154 use core::ops::{Deref, Drop};
155 use core::option::Option;
156 use core::option::Option::{Some, None};
157 use core::ptr::{mod, PtrExt};
158 use core::result::Result;
159 use core::result::Result::{Ok, Err};
161 use heap::deallocate;
169 /// An immutable reference-counted pointer type.
171 /// See the [module level documentation](../index.html) for more details.
172 #[unsafe_no_drop_flag]
175 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
177 _ptr: NonZero<*mut RcBox<T>>,
178 _nosend: marker::NoSend,
179 _noshare: marker::NoSync
183 /// Constructs a new `Rc<T>`.
190 /// let five = Rc::new(5i);
193 pub fn new(value: T) -> Rc<T> {
196 // there is an implicit weak pointer owned by all the strong pointers, which
197 // ensures that the weak destructor never frees the allocation while the strong
198 // destructor is running, even if the weak pointer is stored inside the strong one.
199 _ptr: NonZero::new(transmute(box RcBox {
201 strong: Cell::new(1),
204 _nosend: marker::NoSend,
205 _noshare: marker::NoSync
210 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
217 /// let five = Rc::new(5i);
219 /// let weak_five = five.downgrade();
221 #[experimental = "Weak pointers may not belong in this module"]
222 pub fn downgrade(&self) -> Weak<T> {
226 _nosend: marker::NoSend,
227 _noshare: marker::NoSync
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::{mod, 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::{mod, 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 {
357 #[experimental = "Deref is experimental."]
358 impl<T> Deref for Rc<T> {
362 fn deref(&self) -> &T {
368 #[experimental = "Drop is experimental."]
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> {
418 /// Makes a clone of the `Rc<T>`.
420 /// This increases the strong reference count.
427 /// let five = Rc::new(5i);
432 fn clone(&self) -> Rc<T> {
434 Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
439 impl<T: Default> Default for Rc<T> {
440 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
446 /// use std::default::Default;
448 /// let x: Rc<int> = Default::default();
452 fn default() -> Rc<T> {
453 Rc::new(Default::default())
458 impl<T: PartialEq> PartialEq for Rc<T> {
459 /// Equality for two `Rc<T>`s.
461 /// Two `Rc<T>`s are equal if their inner value are equal.
468 /// let five = Rc::new(5i);
470 /// five == Rc::new(5i);
473 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
475 /// Inequality for two `Rc<T>`s.
477 /// Two `Rc<T>`s are unequal if their inner value are unequal.
484 /// let five = Rc::new(5i);
486 /// five != Rc::new(5i);
489 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
493 impl<T: Eq> Eq for Rc<T> {}
496 impl<T: PartialOrd> PartialOrd for Rc<T> {
497 /// Partial comparison for two `Rc<T>`s.
499 /// The two are compared by calling `partial_cmp()` on their inner values.
506 /// let five = Rc::new(5i);
508 /// five.partial_cmp(&Rc::new(5i));
511 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
512 (**self).partial_cmp(&**other)
515 /// Less-than comparison for two `Rc<T>`s.
517 /// The two are compared by calling `<` on their inner values.
524 /// let five = Rc::new(5i);
526 /// five < Rc::new(5i);
529 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
531 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
533 /// The two are compared by calling `<=` on their inner values.
540 /// let five = Rc::new(5i);
542 /// five <= Rc::new(5i);
545 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
547 /// Greater-than comparison for two `Rc<T>`s.
549 /// The two are compared by calling `>` on their inner values.
556 /// let five = Rc::new(5i);
558 /// five > Rc::new(5i);
561 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
563 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
565 /// The two are compared by calling `>=` on their inner values.
572 /// let five = Rc::new(5i);
574 /// five >= Rc::new(5i);
577 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
581 impl<T: Ord> Ord for Rc<T> {
582 /// Comparison for two `Rc<T>`s.
584 /// The two are compared by calling `cmp()` on their inner values.
591 /// let five = Rc::new(5i);
593 /// five.partial_cmp(&Rc::new(5i));
596 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
599 // FIXME (#18248) Make `T` `Sized?`
600 impl<S: hash::Writer, T: Hash<S>> Hash<S> for Rc<T> {
602 fn hash(&self, state: &mut S) {
603 (**self).hash(state);
607 #[experimental = "Show is experimental."]
608 impl<T: fmt::Show> fmt::Show for Rc<T> {
609 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614 /// A weak version of `Rc<T>`.
616 /// Weak references do not count when determining if the inner value should be dropped.
618 /// See the [module level documentation](../index.html) for more.
619 #[unsafe_no_drop_flag]
620 #[experimental = "Weak pointers may not belong in this module."]
622 // FIXME #12808: strange names to try to avoid interfering with
623 // field accesses of the contained type via Deref
624 _ptr: NonZero<*mut RcBox<T>>,
625 _nosend: marker::NoSend,
626 _noshare: marker::NoSync
629 #[experimental = "Weak pointers may not belong in this module."]
631 /// Upgrades a weak reference to a strong reference.
633 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
635 /// Returns `None` if there were no strong references and the data was destroyed.
642 /// let five = Rc::new(5i);
644 /// let weak_five = five.downgrade();
646 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
648 pub fn upgrade(&self) -> Option<Rc<T>> {
649 if self.strong() == 0 {
653 Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync })
659 #[experimental = "Weak pointers may not belong in this module."]
660 impl<T> Drop for Weak<T> {
661 /// Drops the `Weak<T>`.
663 /// This will decrement the weak reference count.
671 /// let five = Rc::new(5i);
672 /// let weak_five = five.downgrade();
676 /// drop(weak_five); // explict drop
679 /// let five = Rc::new(5i);
680 /// let weak_five = five.downgrade();
684 /// } // implicit drop
688 let ptr = *self._ptr;
691 // the weak count starts at 1, and will only go to zero if all the strong pointers
693 if self.weak() == 0 {
694 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
695 min_align_of::<RcBox<T>>())
702 #[experimental = "Weak pointers may not belong in this module."]
703 impl<T> Clone for Weak<T> {
704 /// Makes a clone of the `Weak<T>`.
706 /// This increases the weak reference count.
713 /// let weak_five = Rc::new(5i).downgrade();
715 /// weak_five.clone();
718 fn clone(&self) -> Weak<T> {
720 Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
724 #[experimental = "Show is experimental."]
725 impl<T: fmt::Show> fmt::Show for Weak<T> {
726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
733 fn inner(&self) -> &RcBox<T>;
736 fn strong(&self) -> uint { self.inner().strong.get() }
739 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
742 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
745 fn weak(&self) -> uint { self.inner().weak.get() }
748 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
751 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
754 impl<T> RcBoxPtr<T> for Rc<T> {
756 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
759 impl<T> RcBoxPtr<T> for Weak<T> {
761 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
765 #[allow(experimental)]
767 use super::{Rc, Weak, weak_count, strong_count};
768 use std::cell::RefCell;
769 use std::option::Option;
770 use std::option::Option::{Some, None};
771 use std::result::Result::{Err, Ok};
773 use std::clone::Clone;
777 let x = Rc::new(RefCell::new(5i));
779 *x.borrow_mut() = 20;
780 assert_eq!(*y.borrow(), 20);
790 fn test_simple_clone() {
798 fn test_destructor() {
799 let x = Rc::new(box 5i);
806 let y = x.downgrade();
807 assert!(y.upgrade().is_some());
813 let y = x.downgrade();
815 assert!(y.upgrade().is_none());
819 fn weak_self_cyclic() {
821 x: RefCell<Option<Weak<Cycle>>>
824 let a = Rc::new(Cycle { x: RefCell::new(None) });
825 let b = a.clone().downgrade();
826 *a.x.borrow_mut() = Some(b);
828 // hopefully we don't double-free (or leak)...
834 assert!(super::is_unique(&x));
836 assert!(!super::is_unique(&x));
838 assert!(super::is_unique(&x));
839 let w = x.downgrade();
840 assert!(!super::is_unique(&x));
842 assert!(super::is_unique(&x));
846 fn test_strong_count() {
847 let a = Rc::new(0u32);
848 assert!(strong_count(&a) == 1);
849 let w = a.downgrade();
850 assert!(strong_count(&a) == 1);
851 let b = w.upgrade().expect("upgrade of live rc failed");
852 assert!(strong_count(&b) == 2);
853 assert!(strong_count(&a) == 2);
856 assert!(strong_count(&b) == 1);
858 assert!(strong_count(&b) == 2);
859 assert!(strong_count(&c) == 2);
863 fn test_weak_count() {
864 let a = Rc::new(0u32);
865 assert!(strong_count(&a) == 1);
866 assert!(weak_count(&a) == 0);
867 let w = a.downgrade();
868 assert!(strong_count(&a) == 1);
869 assert!(weak_count(&a) == 1);
871 assert!(strong_count(&a) == 1);
872 assert!(weak_count(&a) == 0);
874 assert!(strong_count(&a) == 2);
875 assert!(weak_count(&a) == 0);
882 assert_eq!(super::try_unwrap(x), Ok(3u));
885 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
887 let _w = x.downgrade();
888 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
893 let mut x = Rc::new(3u);
894 *super::get_mut(&mut x).unwrap() = 4u;
897 assert!(super::get_mut(&mut x).is_none());
899 assert!(super::get_mut(&mut x).is_some());
900 let _w = x.downgrade();
901 assert!(super::get_mut(&mut x).is_none());
905 fn test_cowrc_clone_make_unique() {
906 let mut cow0 = Rc::new(75u);
907 let mut cow1 = cow0.clone();
908 let mut cow2 = cow1.clone();
910 assert!(75 == *cow0.make_unique());
911 assert!(75 == *cow1.make_unique());
912 assert!(75 == *cow2.make_unique());
914 *cow0.make_unique() += 1;
915 *cow1.make_unique() += 2;
916 *cow2.make_unique() += 3;
918 assert!(76 == *cow0);
919 assert!(77 == *cow1);
920 assert!(78 == *cow2);
922 // none should point to the same backing memory
923 assert!(*cow0 != *cow1);
924 assert!(*cow0 != *cow2);
925 assert!(*cow1 != *cow2);
929 fn test_cowrc_clone_unique2() {
930 let mut cow0 = Rc::new(75u);
931 let cow1 = cow0.clone();
932 let cow2 = cow1.clone();
934 assert!(75 == *cow0);
935 assert!(75 == *cow1);
936 assert!(75 == *cow2);
938 *cow0.make_unique() += 1;
940 assert!(76 == *cow0);
941 assert!(75 == *cow1);
942 assert!(75 == *cow2);
944 // cow1 and cow2 should share the same contents
945 // cow0 should have a unique reference
946 assert!(*cow0 != *cow1);
947 assert!(*cow0 != *cow2);
948 assert!(*cow1 == *cow2);
952 fn test_cowrc_clone_weak() {
953 let mut cow0 = Rc::new(75u);
954 let cow1_weak = cow0.downgrade();
956 assert!(75 == *cow0);
957 assert!(75 == *cow1_weak.upgrade().unwrap());
959 *cow0.make_unique() += 1;
961 assert!(76 == *cow0);
962 assert!(cow1_weak.upgrade().is_none());