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.
145 #![stable(feature = "rust1", since = "1.0.0")]
147 use core::cell::Cell;
148 use core::clone::Clone;
149 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
150 use core::default::Default;
152 use core::hash::{Hasher, Hash};
154 use core::mem::{transmute, min_align_of, size_of, forget};
155 use core::nonzero::NonZero;
156 use core::ops::{Deref, Drop};
157 use core::option::Option;
158 use core::option::Option::{Some, None};
159 use core::ptr::{self, PtrExt};
160 use core::result::Result;
161 use core::result::Result::{Ok, Err};
162 use core::intrinsics::assume;
164 use heap::deallocate;
172 /// A reference-counted pointer type over an immutable value.
174 /// See the [module level documentation](./index.html) for more details.
175 #[unsafe_no_drop_flag]
176 #[stable(feature = "rust1", since = "1.0.0")]
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> {}
188 /// Constructs a new `Rc<T>`.
195 /// let five = Rc::new(5);
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn new(value: T) -> Rc<T> {
201 // there is an implicit weak pointer owned by all the strong pointers, which
202 // ensures that the weak destructor never frees the allocation while the strong
203 // destructor is running, even if the weak pointer is stored inside the strong one.
204 _ptr: NonZero::new(transmute(box RcBox {
206 strong: Cell::new(1),
213 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
220 /// let five = Rc::new(5);
222 /// let weak_five = five.downgrade();
224 #[unstable(feature = "alloc",
225 reason = "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.
234 #[unstable(feature = "alloc")]
235 pub fn weak_count<T>(this: &Rc<T>) -> usize { this.weak() - 1 }
237 /// Get the number of strong references to this value.
239 #[unstable(feature = "alloc")]
240 pub fn strong_count<T>(this: &Rc<T>) -> usize { 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(5);
252 /// rc::is_unique(&five);
255 #[unstable(feature = "alloc")]
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(3);
270 /// assert_eq!(rc::try_unwrap(x), Ok(3));
272 /// let x = Rc::new(4);
273 /// let _y = x.clone();
274 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4)));
277 #[unstable(feature = "alloc")]
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(3);
304 /// *rc::get_mut(&mut x).unwrap() = 4;
305 /// assert_eq!(*x, 4);
307 /// let _y = x.clone();
308 /// assert!(rc::get_mut(&mut x).is_none());
311 #[unstable(feature = "alloc")]
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(5);
334 /// let mut_five = five.make_unique();
337 #[unstable(feature = "alloc")]
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 #[stable(feature = "rust1", since = "1.0.0")]
352 impl<T> Deref for Rc<T> {
356 fn deref(&self) -> &T {
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<T> Drop for Rc<T> {
364 /// Drops the `Rc<T>`.
366 /// This will decrement the strong reference count. If the strong reference count becomes zero
367 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
375 /// let five = Rc::new(5);
379 /// drop(five); // explicit drop
382 /// let five = Rc::new(5);
386 /// } // implicit drop
390 let ptr = *self._ptr;
393 if self.strong() == 0 {
394 ptr::read(&**self); // destroy the contained object
396 // remove the implicit "strong weak" pointer now that we've destroyed the
400 if self.weak() == 0 {
401 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
402 min_align_of::<RcBox<T>>())
410 #[stable(feature = "rust1", since = "1.0.0")]
411 impl<T> Clone for Rc<T> {
413 /// Makes a clone of the `Rc<T>`.
415 /// This increases the strong reference count.
422 /// let five = Rc::new(5);
427 fn clone(&self) -> Rc<T> {
429 Rc { _ptr: self._ptr }
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: Default> Default for Rc<T> {
435 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
441 /// use std::default::Default;
443 /// let x: Rc<i32> = Default::default();
446 #[stable(feature = "rust1", since = "1.0.0")]
447 fn default() -> Rc<T> {
448 Rc::new(Default::default())
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<T: PartialEq> PartialEq for Rc<T> {
454 /// Equality for two `Rc<T>`s.
456 /// Two `Rc<T>`s are equal if their inner value are equal.
463 /// let five = Rc::new(5);
465 /// five == Rc::new(5);
468 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
470 /// Inequality for two `Rc<T>`s.
472 /// Two `Rc<T>`s are unequal if their inner value are unequal.
479 /// let five = Rc::new(5);
481 /// five != Rc::new(5);
484 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl<T: Eq> Eq for Rc<T> {}
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<T: PartialOrd> PartialOrd for Rc<T> {
492 /// Partial comparison for two `Rc<T>`s.
494 /// The two are compared by calling `partial_cmp()` on their inner values.
501 /// let five = Rc::new(5);
503 /// five.partial_cmp(&Rc::new(5));
506 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
507 (**self).partial_cmp(&**other)
510 /// Less-than comparison for two `Rc<T>`s.
512 /// The two are compared by calling `<` on their inner values.
519 /// let five = Rc::new(5);
521 /// five < Rc::new(5);
524 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
526 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
528 /// The two are compared by calling `<=` on their inner values.
535 /// let five = Rc::new(5);
537 /// five <= Rc::new(5);
540 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
542 /// Greater-than comparison for two `Rc<T>`s.
544 /// The two are compared by calling `>` on their inner values.
551 /// let five = Rc::new(5);
553 /// five > Rc::new(5);
556 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
558 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
560 /// The two are compared by calling `>=` on their inner values.
567 /// let five = Rc::new(5);
569 /// five >= Rc::new(5);
572 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<T: Ord> Ord for Rc<T> {
577 /// Comparison for two `Rc<T>`s.
579 /// The two are compared by calling `cmp()` on their inner values.
586 /// let five = Rc::new(5);
588 /// five.partial_cmp(&Rc::new(5));
591 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
594 // FIXME (#18248) Make `T` `Sized?`
596 impl<S: Hasher, T: Hash<S>> Hash<S> for Rc<T> {
598 fn hash(&self, state: &mut S) {
599 (**self).hash(state);
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl<T: Hash> Hash for Rc<T> {
605 fn hash<H: Hasher>(&self, state: &mut H) {
606 (**self).hash(state);
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl<T: fmt::Display> fmt::Display for Rc<T> {
612 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
613 fmt::Display::fmt(&**self, f)
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<T: fmt::Debug> fmt::Debug for Rc<T> {
619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
620 fmt::Debug::fmt(&**self, f)
624 /// A weak version of `Rc<T>`.
626 /// Weak references do not count when determining if the inner value should be dropped.
628 /// See the [module level documentation](./index.html) for more.
629 #[unsafe_no_drop_flag]
630 #[unstable(feature = "alloc",
631 reason = "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>>,
638 impl<T> !marker::Send for Weak<T> {}
640 impl<T> !marker::Sync for Weak<T> {}
643 #[unstable(feature = "alloc",
644 reason = "Weak pointers may not belong in this module.")]
647 /// Upgrades a weak reference to a strong reference.
649 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
651 /// Returns `None` if there were no strong references and the data was destroyed.
658 /// let five = Rc::new(5);
660 /// let weak_five = five.downgrade();
662 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
664 pub fn upgrade(&self) -> Option<Rc<T>> {
665 if self.strong() == 0 {
669 Some(Rc { _ptr: self._ptr })
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl<T> Drop for Weak<T> {
677 /// Drops the `Weak<T>`.
679 /// This will decrement the weak reference count.
687 /// let five = Rc::new(5);
688 /// let weak_five = five.downgrade();
692 /// drop(weak_five); // explicit drop
695 /// let five = Rc::new(5);
696 /// let weak_five = five.downgrade();
700 /// } // implicit drop
704 let ptr = *self._ptr;
707 // the weak count starts at 1, and will only go to zero if all the strong pointers
709 if self.weak() == 0 {
710 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
711 min_align_of::<RcBox<T>>())
718 #[unstable(feature = "alloc",
719 reason = "Weak pointers may not belong in this module.")]
720 impl<T> Clone for Weak<T> {
722 /// Makes a clone of the `Weak<T>`.
724 /// This increases the weak reference count.
731 /// let weak_five = Rc::new(5).downgrade();
733 /// weak_five.clone();
736 fn clone(&self) -> Weak<T> {
738 Weak { _ptr: self._ptr }
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
751 fn inner(&self) -> &RcBox<T>;
754 fn strong(&self) -> usize { self.inner().strong.get() }
757 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
760 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
763 fn weak(&self) -> usize { self.inner().weak.get() }
766 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
769 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
772 impl<T> RcBoxPtr<T> for Rc<T> {
774 fn inner(&self) -> &RcBox<T> {
776 // Safe to assume this here, as if it weren't true, we'd be breaking
777 // the contract anyway.
778 // This allows the null check to be elided in the destructor if we
779 // manipulated the reference count in the same function.
780 assume(!self._ptr.is_null());
786 impl<T> RcBoxPtr<T> for Weak<T> {
788 fn inner(&self) -> &RcBox<T> {
790 // Safe to assume this here, as if it weren't true, we'd be breaking
791 // the contract anyway.
792 // This allows the null check to be elided in the destructor if we
793 // manipulated the reference count in the same function.
794 assume(!self._ptr.is_null());
802 use super::{Rc, Weak, weak_count, strong_count};
803 use std::cell::RefCell;
804 use std::option::Option;
805 use std::option::Option::{Some, None};
806 use std::result::Result::{Err, Ok};
808 use std::clone::Clone;
812 let x = Rc::new(RefCell::new(5));
814 *x.borrow_mut() = 20;
815 assert_eq!(*y.borrow(), 20);
825 fn test_simple_clone() {
833 fn test_destructor() {
834 let x = Rc::new(box 5);
841 let y = x.downgrade();
842 assert!(y.upgrade().is_some());
848 let y = x.downgrade();
850 assert!(y.upgrade().is_none());
854 fn weak_self_cyclic() {
856 x: RefCell<Option<Weak<Cycle>>>
859 let a = Rc::new(Cycle { x: RefCell::new(None) });
860 let b = a.clone().downgrade();
861 *a.x.borrow_mut() = Some(b);
863 // hopefully we don't double-free (or leak)...
869 assert!(super::is_unique(&x));
871 assert!(!super::is_unique(&x));
873 assert!(super::is_unique(&x));
874 let w = x.downgrade();
875 assert!(!super::is_unique(&x));
877 assert!(super::is_unique(&x));
881 fn test_strong_count() {
882 let a = Rc::new(0u32);
883 assert!(strong_count(&a) == 1);
884 let w = a.downgrade();
885 assert!(strong_count(&a) == 1);
886 let b = w.upgrade().expect("upgrade of live rc failed");
887 assert!(strong_count(&b) == 2);
888 assert!(strong_count(&a) == 2);
891 assert!(strong_count(&b) == 1);
893 assert!(strong_count(&b) == 2);
894 assert!(strong_count(&c) == 2);
898 fn test_weak_count() {
899 let a = Rc::new(0u32);
900 assert!(strong_count(&a) == 1);
901 assert!(weak_count(&a) == 0);
902 let w = a.downgrade();
903 assert!(strong_count(&a) == 1);
904 assert!(weak_count(&a) == 1);
906 assert!(strong_count(&a) == 1);
907 assert!(weak_count(&a) == 0);
909 assert!(strong_count(&a) == 2);
910 assert!(weak_count(&a) == 0);
917 assert_eq!(super::try_unwrap(x), Ok(3));
920 assert_eq!(super::try_unwrap(x), Err(Rc::new(4)));
922 let _w = x.downgrade();
923 assert_eq!(super::try_unwrap(x), Err(Rc::new(5)));
928 let mut x = Rc::new(3);
929 *super::get_mut(&mut x).unwrap() = 4;
932 assert!(super::get_mut(&mut x).is_none());
934 assert!(super::get_mut(&mut x).is_some());
935 let _w = x.downgrade();
936 assert!(super::get_mut(&mut x).is_none());
940 fn test_cowrc_clone_make_unique() {
941 let mut cow0 = Rc::new(75);
942 let mut cow1 = cow0.clone();
943 let mut cow2 = cow1.clone();
945 assert!(75 == *cow0.make_unique());
946 assert!(75 == *cow1.make_unique());
947 assert!(75 == *cow2.make_unique());
949 *cow0.make_unique() += 1;
950 *cow1.make_unique() += 2;
951 *cow2.make_unique() += 3;
953 assert!(76 == *cow0);
954 assert!(77 == *cow1);
955 assert!(78 == *cow2);
957 // none should point to the same backing memory
958 assert!(*cow0 != *cow1);
959 assert!(*cow0 != *cow2);
960 assert!(*cow1 != *cow2);
964 fn test_cowrc_clone_unique2() {
965 let mut cow0 = Rc::new(75);
966 let cow1 = cow0.clone();
967 let cow2 = cow1.clone();
969 assert!(75 == *cow0);
970 assert!(75 == *cow1);
971 assert!(75 == *cow2);
973 *cow0.make_unique() += 1;
975 assert!(76 == *cow0);
976 assert!(75 == *cow1);
977 assert!(75 == *cow2);
979 // cow1 and cow2 should share the same contents
980 // cow0 should have a unique reference
981 assert!(*cow0 != *cow1);
982 assert!(*cow0 != *cow2);
983 assert!(*cow1 == *cow2);
987 fn test_cowrc_clone_weak() {
988 let mut cow0 = Rc::new(75);
989 let cow1_weak = cow0.downgrade();
991 assert!(75 == *cow0);
992 assert!(75 == *cow1_weak.upgrade().unwrap());
994 *cow0.make_unique() += 1;
996 assert!(76 == *cow0);
997 assert!(cow1_weak.upgrade().is_none());
1002 let foo = Rc::new(75);
1003 assert_eq!(format!("{:?}", foo), "75");