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 //! Task-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::cell::Cell;
145 use core::clone::Clone;
146 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
147 use core::default::Default;
149 use core::kinds::marker;
150 use core::mem::{transmute, min_align_of, size_of, forget};
151 use core::ops::{Deref, Drop};
152 use core::option::Option;
153 use core::option::Option::{Some, None};
155 use core::ptr::RawPtr;
156 use core::result::Result;
157 use core::result::Result::{Ok, Err};
159 use heap::deallocate;
167 /// An immutable reference-counted pointer type.
169 /// See the [module level documentation](../index.html) for more.
170 #[unsafe_no_drop_flag]
173 // FIXME #12808: strange names to try to avoid interfering with
174 // field accesses of the contained type via Deref
176 _nosend: marker::NoSend,
177 _noshare: marker::NoSync
181 /// Constructs a new `Rc<T>`.
188 /// let five = Rc::new(5i);
191 pub fn new(value: T) -> Rc<T> {
194 // there is an implicit weak pointer owned by all the
195 // strong pointers, which ensures that the weak
196 // destructor never frees the allocation while the
197 // strong destructor is running, even if the weak
198 // pointer is stored inside the strong one.
199 _ptr: 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
343 // returned is the *only* pointer that will ever be returned to T. Our
344 // reference count is guaranteed to be 1 at this point, and we required
345 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
346 // reference to the inner value.
347 let inner = unsafe { &mut *self._ptr };
352 #[experimental = "Deref is experimental."]
353 impl<T> Deref<T> for Rc<T> {
355 fn deref(&self) -> &T {
361 #[experimental = "Drop is experimental."]
362 impl<T> Drop for Rc<T> {
363 /// Drops the `Rc<T>`.
365 /// This will decrement the strong reference count. If the strong reference count becomes zero
366 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
374 /// let five = Rc::new(5i);
378 /// drop(five); // explict drop
381 /// let five = Rc::new(5i);
385 /// } // implicit drop
389 if !self._ptr.is_null() {
391 if self.strong() == 0 {
392 ptr::read(&**self); // destroy the contained object
394 // remove the implicit "strong weak" pointer now
395 // that we've destroyed the contents.
398 if self.weak() == 0 {
399 deallocate(self._ptr as *mut u8, size_of::<RcBox<T>>(),
400 min_align_of::<RcBox<T>>())
408 #[unstable = "Clone is unstable."]
409 impl<T> Clone for Rc<T> {
410 /// Makes a clone of the `Rc<T>`.
412 /// This increases the strong reference count.
419 /// let five = Rc::new(5i);
424 fn clone(&self) -> Rc<T> {
426 Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
431 impl<T: Default> Default for Rc<T> {
432 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
438 /// use std::default::Default;
440 /// let x: Rc<int> = Default::default();
443 fn default() -> Rc<T> {
444 Rc::new(Default::default())
448 #[unstable = "PartialEq is unstable."]
449 impl<T: PartialEq> PartialEq for Rc<T> {
450 /// Equality for two `Rc<T>`s.
452 /// Two `Rc<T>`s are equal if their inner value are equal.
459 /// let five = Rc::new(5i);
461 /// five == Rc::new(5i);
464 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
466 /// Inequality for two `Rc<T>`s.
468 /// Two `Rc<T>`s are unequal if their inner value are unequal.
475 /// let five = Rc::new(5i);
477 /// five != Rc::new(5i);
480 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
483 #[unstable = "Eq is unstable."]
484 impl<T: Eq> Eq for Rc<T> {}
486 #[unstable = "PartialOrd is unstable."]
487 impl<T: PartialOrd> PartialOrd for Rc<T> {
488 /// Partial comparison for two `Rc<T>`s.
490 /// The two are compared by calling `partial_cmp()` on their inner values.
497 /// let five = Rc::new(5i);
499 /// five.partial_cmp(&Rc::new(5i));
502 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
503 (**self).partial_cmp(&**other)
506 /// Less-than comparison for two `Rc<T>`s.
508 /// The two are compared by calling `<` on their inner values.
515 /// let five = Rc::new(5i);
517 /// five < Rc::new(5i);
520 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
522 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
524 /// The two are compared by calling `<=` on their inner values.
531 /// let five = Rc::new(5i);
533 /// five <= Rc::new(5i);
536 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
538 /// Greater-than comparison for two `Rc<T>`s.
540 /// The two are compared by calling `>` on their inner values.
547 /// let five = Rc::new(5i);
549 /// five > Rc::new(5i);
552 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
554 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
556 /// The two are compared by calling `>=` on their inner values.
563 /// let five = Rc::new(5i);
565 /// five >= Rc::new(5i);
568 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
571 #[unstable = "Ord is unstable."]
572 impl<T: Ord> Ord for Rc<T> {
573 /// Comparison for two `Rc<T>`s.
575 /// The two are compared by calling `cmp()` on their inner values.
582 /// let five = Rc::new(5i);
584 /// five.partial_cmp(&Rc::new(5i));
587 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
590 #[experimental = "Show is experimental."]
591 impl<T: fmt::Show> fmt::Show for Rc<T> {
592 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
597 /// A weak version of `Rc<T>`.
599 /// Weak references do not count when determining if the inner value should be dropped.
601 /// See the [module level documentation](../index.html) for more.
602 #[unsafe_no_drop_flag]
603 #[experimental = "Weak pointers may not belong in this module."]
605 // FIXME #12808: strange names to try to avoid interfering with
606 // field accesses of the contained type via Deref
608 _nosend: marker::NoSend,
609 _noshare: marker::NoSync
612 #[experimental = "Weak pointers may not belong in this module."]
614 /// Upgrades a weak reference to a strong reference.
616 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
618 /// Returns `None` if there were no strong references and the data was destroyed.
625 /// let five = Rc::new(5i);
627 /// let weak_five = five.downgrade();
629 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
631 pub fn upgrade(&self) -> Option<Rc<T>> {
632 if self.strong() == 0 {
636 Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync })
642 #[experimental = "Weak pointers may not belong in this module."]
643 impl<T> Drop for Weak<T> {
644 /// Drops the `Weak<T>`.
646 /// This will decrement the weak reference count.
654 /// let five = Rc::new(5i);
655 /// let weak_five = five.downgrade();
659 /// drop(weak_five); // explict drop
662 /// let five = Rc::new(5i);
663 /// let weak_five = five.downgrade();
667 /// } // implicit drop
671 if !self._ptr.is_null() {
673 // the weak count starts at 1, and will only go to
674 // zero if all the strong pointers have disappeared.
675 if self.weak() == 0 {
676 deallocate(self._ptr as *mut u8, size_of::<RcBox<T>>(),
677 min_align_of::<RcBox<T>>())
684 #[experimental = "Weak pointers may not belong in this module."]
685 impl<T> Clone for Weak<T> {
686 /// Makes a clone of the `Weak<T>`.
688 /// This increases the weak reference count.
695 /// let weak_five = Rc::new(5i).downgrade();
697 /// weak_five.clone();
700 fn clone(&self) -> Weak<T> {
702 Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
708 fn inner(&self) -> &RcBox<T>;
711 fn strong(&self) -> uint { self.inner().strong.get() }
714 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
717 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
720 fn weak(&self) -> uint { self.inner().weak.get() }
723 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
726 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
729 impl<T> RcBoxPtr<T> for Rc<T> {
731 fn inner(&self) -> &RcBox<T> { unsafe { &(*self._ptr) } }
734 impl<T> RcBoxPtr<T> for Weak<T> {
736 fn inner(&self) -> &RcBox<T> { unsafe { &(*self._ptr) } }
740 #[allow(experimental)]
742 use super::{Rc, Weak, weak_count, strong_count};
743 use std::cell::RefCell;
744 use std::option::Option;
745 use std::option::Option::{Some, None};
746 use std::result::Result::{Err, Ok};
748 use std::clone::Clone;
752 let x = Rc::new(RefCell::new(5i));
754 *x.borrow_mut() = 20;
755 assert_eq!(*y.borrow(), 20);
765 fn test_simple_clone() {
773 fn test_destructor() {
774 let x = Rc::new(box 5i);
781 let y = x.downgrade();
782 assert!(y.upgrade().is_some());
788 let y = x.downgrade();
790 assert!(y.upgrade().is_none());
794 fn weak_self_cyclic() {
796 x: RefCell<Option<Weak<Cycle>>>
799 let a = Rc::new(Cycle { x: RefCell::new(None) });
800 let b = a.clone().downgrade();
801 *a.x.borrow_mut() = Some(b);
803 // hopefully we don't double-free (or leak)...
809 assert!(super::is_unique(&x));
811 assert!(!super::is_unique(&x));
813 assert!(super::is_unique(&x));
814 let w = x.downgrade();
815 assert!(!super::is_unique(&x));
817 assert!(super::is_unique(&x));
821 fn test_strong_count() {
822 let a = Rc::new(0u32);
823 assert!(strong_count(&a) == 1);
824 let w = a.downgrade();
825 assert!(strong_count(&a) == 1);
826 let b = w.upgrade().expect("upgrade of live rc failed");
827 assert!(strong_count(&b) == 2);
828 assert!(strong_count(&a) == 2);
831 assert!(strong_count(&b) == 1);
833 assert!(strong_count(&b) == 2);
834 assert!(strong_count(&c) == 2);
838 fn test_weak_count() {
839 let a = Rc::new(0u32);
840 assert!(strong_count(&a) == 1);
841 assert!(weak_count(&a) == 0);
842 let w = a.downgrade();
843 assert!(strong_count(&a) == 1);
844 assert!(weak_count(&a) == 1);
846 assert!(strong_count(&a) == 1);
847 assert!(weak_count(&a) == 0);
849 assert!(strong_count(&a) == 2);
850 assert!(weak_count(&a) == 0);
857 assert_eq!(super::try_unwrap(x), Ok(3u));
860 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
862 let _w = x.downgrade();
863 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
868 let mut x = Rc::new(3u);
869 *super::get_mut(&mut x).unwrap() = 4u;
872 assert!(super::get_mut(&mut x).is_none());
874 assert!(super::get_mut(&mut x).is_some());
875 let _w = x.downgrade();
876 assert!(super::get_mut(&mut x).is_none());
880 fn test_cowrc_clone_make_unique() {
881 let mut cow0 = Rc::new(75u);
882 let mut cow1 = cow0.clone();
883 let mut cow2 = cow1.clone();
885 assert!(75 == *cow0.make_unique());
886 assert!(75 == *cow1.make_unique());
887 assert!(75 == *cow2.make_unique());
889 *cow0.make_unique() += 1;
890 *cow1.make_unique() += 2;
891 *cow2.make_unique() += 3;
893 assert!(76 == *cow0);
894 assert!(77 == *cow1);
895 assert!(78 == *cow2);
897 // none should point to the same backing memory
898 assert!(*cow0 != *cow1);
899 assert!(*cow0 != *cow2);
900 assert!(*cow1 != *cow2);
904 fn test_cowrc_clone_unique2() {
905 let mut cow0 = Rc::new(75u);
906 let cow1 = cow0.clone();
907 let cow2 = cow1.clone();
909 assert!(75 == *cow0);
910 assert!(75 == *cow1);
911 assert!(75 == *cow2);
913 *cow0.make_unique() += 1;
915 assert!(76 == *cow0);
916 assert!(75 == *cow1);
917 assert!(75 == *cow2);
919 // cow1 and cow2 should share the same contents
920 // cow0 should have a unique reference
921 assert!(*cow0 != *cow1);
922 assert!(*cow0 != *cow2);
923 assert!(*cow1 == *cow2);
927 fn test_cowrc_clone_weak() {
928 let mut cow0 = Rc::new(75u);
929 let cow1_weak = cow0.downgrade();
931 assert!(75 == *cow0);
932 assert!(75 == *cow1_weak.upgrade().unwrap());
934 *cow0.make_unique() += 1;
936 assert!(76 == *cow0);
937 assert!(cow1_weak.upgrade().is_none());