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.
35 //! # #![feature(alloc)]
40 //! // ...other fields
46 //! // ...other fields
50 //! // Create a reference counted Owner.
51 //! let gadget_owner : Rc<Owner> = Rc::new(
52 //! Owner { name: String::from("Gadget Man") }
55 //! // Create Gadgets belonging to gadget_owner. To increment the reference
56 //! // count we clone the `Rc<T>` object.
57 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
58 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
60 //! drop(gadget_owner);
62 //! // Despite dropping gadget_owner, we're still able to print out the name
63 //! // of the Owner of the Gadgets. This is because we've only dropped the
64 //! // reference count object, not the Owner it wraps. As long as there are
65 //! // other `Rc<T>` objects pointing at the same Owner, it will remain
66 //! // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
67 //! // automatically dereferenced for us.
68 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
69 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
71 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
72 //! // them the last counted references to our Owner. Gadget Man now gets
73 //! // destroyed as well.
77 //! If our requirements change, and we also need to be able to traverse from
78 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
79 //! → Gadget introduces a cycle between the objects. This means that their
80 //! reference counts can never reach 0, and the objects will remain allocated: a
81 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
82 //! These pointers don't contribute to the total count.
84 //! Rust actually makes it somewhat difficult to produce this loop in the first
85 //! place: in order to end up with two objects that point at each other, one of
86 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
87 //! memory safety by only giving out shared references to the object it wraps,
88 //! and these don't allow direct mutation. We need to wrap the part of the
89 //! object we wish to mutate in a `RefCell`, which provides *interior
90 //! mutability*: a method to achieve mutability through a shared reference.
91 //! `RefCell` enforces Rust's borrowing rules at runtime. Read the `Cell`
92 //! documentation for more details on interior mutability.
95 //! # #![feature(alloc)]
97 //! use std::rc::Weak;
98 //! use std::cell::RefCell;
102 //! gadgets: RefCell<Vec<Weak<Gadget>>>
103 //! // ...other fields
109 //! // ...other fields
113 //! // Create a reference counted Owner. Note the fact that we've put the
114 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
115 //! // through a shared reference.
116 //! let gadget_owner : Rc<Owner> = Rc::new(
118 //! name: "Gadget Man".to_string(),
119 //! gadgets: RefCell::new(Vec::new())
123 //! // Create Gadgets belonging to gadget_owner as before.
124 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
125 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
127 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
128 //! // the RefCell holding the Owner's Gadgets.
129 //! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
130 //! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
132 //! // Iterate over our Gadgets, printing their details out
133 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
135 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
136 //! // that their object is still allocated, we need to call upgrade()
137 //! // on them to turn them into a strong reference. This returns an
138 //! // Option, which contains a reference to our object if it still
140 //! let gadget = gadget_opt.upgrade().unwrap();
141 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
144 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
145 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
146 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
147 //! // reference count on Gadget Man, so he gets destroyed as well.
151 #![stable(feature = "rust1", since = "1.0.0")]
156 use core::cell::Cell;
157 use core::clone::Clone;
158 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
159 use core::default::Default;
161 use core::hash::{Hasher, Hash};
162 use core::marker::{self, Sized};
163 use core::mem::{self, min_align_of, size_of, forget};
164 use core::nonzero::NonZero;
165 use core::ops::{Deref, Drop};
166 use core::option::Option;
167 use core::option::Option::{Some, None};
169 use core::result::Result;
170 use core::result::Result::{Ok, Err};
171 use core::intrinsics::assume;
174 use core::intrinsics::drop_in_place;
176 use core::marker::Unsize;
178 use core::mem::{min_align_of_val, size_of_val};
180 use core::ops::CoerceUnsized;
182 use heap::deallocate;
192 struct RcBox<T: ?Sized> {
199 /// A reference-counted pointer type over an immutable value.
201 /// See the [module level documentation](./index.html) for more details.
203 #[unsafe_no_drop_flag]
204 #[stable(feature = "rust1", since = "1.0.0")]
206 // FIXME #12808: strange names to try to avoid interfering with field
207 // accesses of the contained type via Deref
208 _ptr: NonZero<*mut RcBox<T>>,
211 #[unsafe_no_drop_flag]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub struct Rc<T: ?Sized> {
214 // FIXME #12808: strange names to try to avoid interfering with field
215 // accesses of the contained type via Deref
216 _ptr: NonZero<*mut RcBox<T>>,
220 impl<T> !marker::Send for Rc<T> {}
223 impl<T: ?Sized> !marker::Send for Rc<T> {}
226 impl<T> !marker::Sync for Rc<T> {}
229 impl<T: ?Sized> !marker::Sync for Rc<T> {}
232 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
235 /// Constructs a new `Rc<T>`.
242 /// let five = Rc::new(5);
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn new(value: T) -> Rc<T> {
248 // there is an implicit weak pointer owned by all the strong
249 // pointers, which ensures that the weak destructor never frees
250 // the allocation while the strong destructor is running, even
251 // if the weak pointer is stored inside the strong one.
252 _ptr: NonZero::new(boxed::into_raw(box RcBox {
253 strong: Cell::new(1),
263 impl<T: ?Sized> Rc<T> {
264 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
269 /// # #![feature(alloc)]
272 /// let five = Rc::new(5);
274 /// let weak_five = five.downgrade();
276 #[unstable(feature = "alloc",
277 reason = "Weak pointers may not belong in this module")]
278 pub fn downgrade(&self) -> Weak<T> {
280 Weak { _ptr: self._ptr }
286 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
291 /// # #![feature(alloc)]
294 /// let five = Rc::new(5);
296 /// let weak_five = five.downgrade();
298 #[unstable(feature = "alloc",
299 reason = "Weak pointers may not belong in this module")]
300 pub fn downgrade(&self) -> Weak<T> {
302 Weak { _ptr: self._ptr }
306 /// Get the number of weak references to this value.
309 #[unstable(feature = "alloc")]
310 pub fn weak_count<T>(this: &Rc<T>) -> usize { this.weak() - 1 }
313 #[unstable(feature = "alloc")]
314 pub fn weak_count<T: ?Sized>(this: &Rc<T>) -> usize { this.weak() - 1 }
316 /// Get the number of strong references to this value.
319 #[unstable(feature = "alloc")]
320 pub fn strong_count<T>(this: &Rc<T>) -> usize { this.strong() }
323 #[unstable(feature = "alloc")]
324 pub fn strong_count<T: ?Sized>(this: &Rc<T>) -> usize { this.strong() }
326 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the
327 /// same inner value.
332 /// # #![feature(alloc)]
336 /// let five = Rc::new(5);
338 /// rc::is_unique(&five);
341 #[unstable(feature = "alloc")]
342 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
343 weak_count(rc) == 0 && strong_count(rc) == 1
346 /// Unwraps the contained value if the `Rc<T>` is unique.
348 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
353 /// # #![feature(alloc)]
354 /// use std::rc::{self, Rc};
356 /// let x = Rc::new(3);
357 /// assert_eq!(rc::try_unwrap(x), Ok(3));
359 /// let x = Rc::new(4);
360 /// let _y = x.clone();
361 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4)));
364 #[unstable(feature = "alloc")]
365 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
368 let val = ptr::read(&*rc); // copy the contained object
369 // destruct the box and skip our Drop
370 // we can ignore the refcounts because we know we're unique
371 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
372 min_align_of::<RcBox<T>>());
381 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
383 /// Returns `None` if the `Rc<T>` is not unique.
388 /// # #![feature(alloc)]
389 /// use std::rc::{self, Rc};
391 /// let mut x = Rc::new(3);
392 /// *rc::get_mut(&mut x).unwrap() = 4;
393 /// assert_eq!(*x, 4);
395 /// let _y = x.clone();
396 /// assert!(rc::get_mut(&mut x).is_none());
399 #[unstable(feature = "alloc")]
400 pub fn get_mut<T>(rc: &mut Rc<T>) -> Option<&mut T> {
402 let inner = unsafe { &mut **rc._ptr };
403 Some(&mut inner.value)
409 impl<T: Clone> Rc<T> {
410 /// Make a mutable reference from the given `Rc<T>`.
412 /// This is also referred to as a copy-on-write operation because the inner
413 /// data is cloned if the reference count is greater than one.
418 /// # #![feature(alloc)]
421 /// let mut five = Rc::new(5);
423 /// let mut_five = five.make_unique();
426 #[unstable(feature = "alloc")]
427 pub fn make_unique(&mut self) -> &mut T {
428 if !is_unique(self) {
429 *self = Rc::new((**self).clone())
431 // This unsafety is ok because we're guaranteed that the pointer
432 // returned is the *only* pointer that will ever be returned to T. Our
433 // reference count is guaranteed to be 1 at this point, and we required
434 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
435 // reference to the inner value.
436 let inner = unsafe { &mut **self._ptr };
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<T> Deref for Rc<T> {
447 fn deref(&self) -> &T {
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<T: ?Sized> Deref for Rc<T> {
457 fn deref(&self) -> &T {
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<T> Drop for Rc<T> {
465 /// Drops the `Rc<T>`.
467 /// This will decrement the strong reference count. If the strong reference
468 /// count becomes zero and the only other references are `Weak<T>` ones,
469 /// `drop`s the inner value.
474 /// # #![feature(alloc)]
478 /// let five = Rc::new(5);
482 /// drop(five); // explicit drop
485 /// let five = Rc::new(5);
489 /// } // implicit drop
493 let ptr = *self._ptr;
494 if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
496 if self.strong() == 0 {
497 ptr::read(&**self); // destroy the contained object
499 // remove the implicit "strong weak" pointer now that we've
500 // destroyed the contents.
503 if self.weak() == 0 {
504 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
505 min_align_of::<RcBox<T>>())
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T: ?Sized> Drop for Rc<T> {
516 /// Drops the `Rc<T>`.
518 /// This will decrement the strong reference count. If the strong reference
519 /// count becomes zero and the only other references are `Weak<T>` ones,
520 /// `drop`s the inner value.
525 /// # #![feature(alloc)]
529 /// let five = Rc::new(5);
533 /// drop(five); // explicit drop
536 /// let five = Rc::new(5);
540 /// } // implicit drop
544 let ptr = *self._ptr;
545 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
546 ptr as usize != mem::POST_DROP_USIZE {
548 if self.strong() == 0 {
549 // destroy the contained object
550 drop_in_place(&mut (*ptr).value);
552 // remove the implicit "strong weak" pointer now that we've
553 // destroyed the contents.
556 if self.weak() == 0 {
557 deallocate(ptr as *mut u8,
559 min_align_of_val(&*ptr))
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl<T> Clone for Rc<T> {
571 /// Makes a clone of the `Rc<T>`.
573 /// When you clone an `Rc<T>`, it will create another pointer to the data and
574 /// increase the strong reference counter.
579 /// # #![feature(alloc)]
582 /// let five = Rc::new(5);
587 fn clone(&self) -> Rc<T> {
589 Rc { _ptr: self._ptr }
593 #[stable(feature = "rust1", since = "1.0.0")]
594 impl<T: ?Sized> Clone for Rc<T> {
596 /// Makes a clone of the `Rc<T>`.
598 /// When you clone an `Rc<T>`, it will create another pointer to the data and
599 /// increase the strong reference counter.
604 /// # #![feature(alloc)]
607 /// let five = Rc::new(5);
612 fn clone(&self) -> Rc<T> {
614 Rc { _ptr: self._ptr }
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl<T: Default> Default for Rc<T> {
620 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
627 /// let x: Rc<i32> = Default::default();
630 #[stable(feature = "rust1", since = "1.0.0")]
631 fn default() -> Rc<T> {
632 Rc::new(Default::default())
636 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<T: PartialEq> PartialEq for Rc<T> {
640 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
643 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
646 #[stable(feature = "rust1", since = "1.0.0")]
648 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
649 /// Equality for two `Rc<T>`s.
651 /// Two `Rc<T>`s are equal if their inner value are equal.
658 /// let five = Rc::new(5);
660 /// five == Rc::new(5);
663 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
665 /// Inequality for two `Rc<T>`s.
667 /// Two `Rc<T>`s are unequal if their inner value are unequal.
674 /// let five = Rc::new(5);
676 /// five != Rc::new(5);
679 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
682 #[stable(feature = "rust1", since = "1.0.0")]
684 impl<T: Eq> Eq for Rc<T> {}
685 #[stable(feature = "rust1", since = "1.0.0")]
687 impl<T: ?Sized + Eq> Eq for Rc<T> {}
689 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T: PartialOrd> PartialOrd for Rc<T> {
693 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
694 (**self).partial_cmp(&**other)
698 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
701 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
704 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
707 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
709 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
712 /// Partial comparison for two `Rc<T>`s.
714 /// The two are compared by calling `partial_cmp()` on their inner values.
721 /// let five = Rc::new(5);
723 /// five.partial_cmp(&Rc::new(5));
726 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
727 (**self).partial_cmp(&**other)
730 /// Less-than comparison for two `Rc<T>`s.
732 /// The two are compared by calling `<` on their inner values.
739 /// let five = Rc::new(5);
741 /// five < Rc::new(5);
744 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
746 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
748 /// The two are compared by calling `<=` on their inner values.
755 /// let five = Rc::new(5);
757 /// five <= Rc::new(5);
760 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
762 /// Greater-than comparison for two `Rc<T>`s.
764 /// The two are compared by calling `>` on their inner values.
771 /// let five = Rc::new(5);
773 /// five > Rc::new(5);
776 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
778 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
780 /// The two are compared by calling `>=` on their inner values.
787 /// let five = Rc::new(5);
789 /// five >= Rc::new(5);
792 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
795 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<T: Ord> Ord for Rc<T> {
799 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
801 #[stable(feature = "rust1", since = "1.0.0")]
803 impl<T: ?Sized + Ord> Ord for Rc<T> {
804 /// Comparison for two `Rc<T>`s.
806 /// The two are compared by calling `cmp()` on their inner values.
813 /// let five = Rc::new(5);
815 /// five.partial_cmp(&Rc::new(5));
818 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<T: Hash> Hash for Rc<T> {
824 fn hash<H: Hasher>(&self, state: &mut H) {
825 (**self).hash(state);
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<T: ?Sized+Hash> Hash for Rc<T> {
831 fn hash<H: Hasher>(&self, state: &mut H) {
832 (**self).hash(state);
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl<T: fmt::Display> fmt::Display for Rc<T> {
839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
840 fmt::Display::fmt(&**self, f)
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 fmt::Display::fmt(&**self, f)
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl<T: fmt::Debug> fmt::Debug for Rc<T> {
854 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
855 fmt::Debug::fmt(&**self, f)
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
861 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
862 fmt::Debug::fmt(&**self, f)
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<T> fmt::Pointer for Rc<T> {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 fmt::Pointer::fmt(&*self._ptr, f)
873 /// A weak version of `Rc<T>`.
875 /// Weak references do not count when determining if the inner value should be
878 /// See the [module level documentation](./index.html) for more.
880 #[unsafe_no_drop_flag]
881 #[unstable(feature = "alloc",
882 reason = "Weak pointers may not belong in this module.")]
884 // FIXME #12808: strange names to try to avoid interfering with
885 // field accesses of the contained type via Deref
886 _ptr: NonZero<*mut RcBox<T>>,
889 #[unsafe_no_drop_flag]
890 #[unstable(feature = "alloc",
891 reason = "Weak pointers may not belong in this module.")]
892 pub struct Weak<T: ?Sized> {
893 // FIXME #12808: strange names to try to avoid interfering with
894 // field accesses of the contained type via Deref
895 _ptr: NonZero<*mut RcBox<T>>,
899 impl<T> !marker::Send for Weak<T> {}
901 impl<T: ?Sized> !marker::Send for Weak<T> {}
904 impl<T> !marker::Sync for Weak<T> {}
906 impl<T: ?Sized> !marker::Sync for Weak<T> {}
910 #[unstable(feature = "alloc",
911 reason = "Weak pointers may not belong in this module.")]
914 /// Upgrades a weak reference to a strong reference.
916 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
918 /// Returns `None` if there were no strong references and the data was
924 /// # #![feature(alloc)]
927 /// let five = Rc::new(5);
929 /// let weak_five = five.downgrade();
931 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
933 pub fn upgrade(&self) -> Option<Rc<T>> {
934 if self.strong() == 0 {
938 Some(Rc { _ptr: self._ptr })
943 #[unstable(feature = "alloc",
944 reason = "Weak pointers may not belong in this module.")]
945 impl<T: ?Sized> Weak<T> {
947 /// Upgrades a weak reference to a strong reference.
949 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
951 /// Returns `None` if there were no strong references and the data was
957 /// # #![feature(alloc)]
960 /// let five = Rc::new(5);
962 /// let weak_five = five.downgrade();
964 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
966 pub fn upgrade(&self) -> Option<Rc<T>> {
967 if self.strong() == 0 {
971 Some(Rc { _ptr: self._ptr })
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<T> Drop for Weak<T> {
979 /// Drops the `Weak<T>`.
981 /// This will decrement the weak reference count.
986 /// # #![feature(alloc)]
990 /// let five = Rc::new(5);
991 /// let weak_five = five.downgrade();
995 /// drop(weak_five); // explicit drop
998 /// let five = Rc::new(5);
999 /// let weak_five = five.downgrade();
1003 /// } // implicit drop
1005 fn drop(&mut self) {
1007 let ptr = *self._ptr;
1008 if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
1010 // the weak count starts at 1, and will only go to zero if all
1011 // the strong pointers have disappeared.
1012 if self.weak() == 0 {
1013 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
1014 min_align_of::<RcBox<T>>())
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<T: ?Sized> Drop for Weak<T> {
1024 /// Drops the `Weak<T>`.
1026 /// This will decrement the weak reference count.
1031 /// # #![feature(alloc)]
1032 /// use std::rc::Rc;
1035 /// let five = Rc::new(5);
1036 /// let weak_five = five.downgrade();
1040 /// drop(weak_five); // explicit drop
1043 /// let five = Rc::new(5);
1044 /// let weak_five = five.downgrade();
1048 /// } // implicit drop
1050 fn drop(&mut self) {
1052 let ptr = *self._ptr;
1053 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
1054 ptr as usize != mem::POST_DROP_USIZE {
1056 // the weak count starts at 1, and will only go to zero if all
1057 // the strong pointers have disappeared.
1058 if self.weak() == 0 {
1059 deallocate(ptr as *mut u8, size_of_val(&*ptr),
1060 min_align_of_val(&*ptr))
1068 #[unstable(feature = "alloc",
1069 reason = "Weak pointers may not belong in this module.")]
1070 impl<T> Clone for Weak<T> {
1072 /// Makes a clone of the `Weak<T>`.
1074 /// This increases the weak reference count.
1079 /// # #![feature(alloc)]
1080 /// use std::rc::Rc;
1082 /// let weak_five = Rc::new(5).downgrade();
1084 /// weak_five.clone();
1087 fn clone(&self) -> Weak<T> {
1089 Weak { _ptr: self._ptr }
1093 #[unstable(feature = "alloc",
1094 reason = "Weak pointers may not belong in this module.")]
1095 impl<T: ?Sized> Clone for Weak<T> {
1097 /// Makes a clone of the `Weak<T>`.
1099 /// This increases the weak reference count.
1104 /// # #![feature(alloc)]
1105 /// use std::rc::Rc;
1107 /// let weak_five = Rc::new(5).downgrade();
1109 /// weak_five.clone();
1112 fn clone(&self) -> Weak<T> {
1114 Weak { _ptr: self._ptr }
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
1121 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
1128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1136 fn inner(&self) -> &RcBox<T>;
1139 fn strong(&self) -> usize { self.inner().strong.get() }
1142 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
1145 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
1148 fn weak(&self) -> usize { self.inner().weak.get() }
1151 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
1154 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
1158 trait RcBoxPtr<T: ?Sized> {
1159 fn inner(&self) -> &RcBox<T>;
1162 fn strong(&self) -> usize { self.inner().strong.get() }
1165 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
1168 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
1171 fn weak(&self) -> usize { self.inner().weak.get() }
1174 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
1177 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
1181 impl<T> RcBoxPtr<T> for Rc<T> {
1183 fn inner(&self) -> &RcBox<T> {
1185 // Safe to assume this here, as if it weren't true, we'd be breaking
1186 // the contract anyway.
1187 // This allows the null check to be elided in the destructor if we
1188 // manipulated the reference count in the same function.
1189 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1195 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1197 fn inner(&self) -> &RcBox<T> {
1199 // Safe to assume this here, as if it weren't true, we'd be breaking
1200 // the contract anyway.
1201 // This allows the null check to be elided in the destructor if we
1202 // manipulated the reference count in the same function.
1203 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1210 impl<T> RcBoxPtr<T> for Weak<T> {
1212 fn inner(&self) -> &RcBox<T> {
1214 // Safe to assume this here, as if it weren't true, we'd be breaking
1215 // the contract anyway.
1216 // This allows the null check to be elided in the destructor if we
1217 // manipulated the reference count in the same function.
1218 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1224 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1226 fn inner(&self) -> &RcBox<T> {
1228 // Safe to assume this here, as if it weren't true, we'd be breaking
1229 // the contract anyway.
1230 // This allows the null check to be elided in the destructor if we
1231 // manipulated the reference count in the same function.
1232 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1240 use super::{Rc, Weak, weak_count, strong_count};
1241 use std::boxed::Box;
1242 use std::cell::RefCell;
1243 use std::option::Option;
1244 use std::option::Option::{Some, None};
1245 use std::result::Result::{Err, Ok};
1247 use std::clone::Clone;
1251 let x = Rc::new(RefCell::new(5));
1253 *x.borrow_mut() = 20;
1254 assert_eq!(*y.borrow(), 20);
1264 fn test_simple_clone() {
1272 fn test_destructor() {
1273 let x: Rc<Box<_>> = Rc::new(box 5);
1280 let y = x.downgrade();
1281 assert!(y.upgrade().is_some());
1287 let y = x.downgrade();
1289 assert!(y.upgrade().is_none());
1293 fn weak_self_cyclic() {
1295 x: RefCell<Option<Weak<Cycle>>>
1298 let a = Rc::new(Cycle { x: RefCell::new(None) });
1299 let b = a.clone().downgrade();
1300 *a.x.borrow_mut() = Some(b);
1302 // hopefully we don't double-free (or leak)...
1308 assert!(super::is_unique(&x));
1310 assert!(!super::is_unique(&x));
1312 assert!(super::is_unique(&x));
1313 let w = x.downgrade();
1314 assert!(!super::is_unique(&x));
1316 assert!(super::is_unique(&x));
1320 fn test_strong_count() {
1321 let a = Rc::new(0u32);
1322 assert!(strong_count(&a) == 1);
1323 let w = a.downgrade();
1324 assert!(strong_count(&a) == 1);
1325 let b = w.upgrade().expect("upgrade of live rc failed");
1326 assert!(strong_count(&b) == 2);
1327 assert!(strong_count(&a) == 2);
1330 assert!(strong_count(&b) == 1);
1332 assert!(strong_count(&b) == 2);
1333 assert!(strong_count(&c) == 2);
1337 fn test_weak_count() {
1338 let a = Rc::new(0u32);
1339 assert!(strong_count(&a) == 1);
1340 assert!(weak_count(&a) == 0);
1341 let w = a.downgrade();
1342 assert!(strong_count(&a) == 1);
1343 assert!(weak_count(&a) == 1);
1345 assert!(strong_count(&a) == 1);
1346 assert!(weak_count(&a) == 0);
1348 assert!(strong_count(&a) == 2);
1349 assert!(weak_count(&a) == 0);
1356 assert_eq!(super::try_unwrap(x), Ok(3));
1359 assert_eq!(super::try_unwrap(x), Err(Rc::new(4)));
1361 let _w = x.downgrade();
1362 assert_eq!(super::try_unwrap(x), Err(Rc::new(5)));
1367 let mut x = Rc::new(3);
1368 *super::get_mut(&mut x).unwrap() = 4;
1371 assert!(super::get_mut(&mut x).is_none());
1373 assert!(super::get_mut(&mut x).is_some());
1374 let _w = x.downgrade();
1375 assert!(super::get_mut(&mut x).is_none());
1379 fn test_cowrc_clone_make_unique() {
1380 let mut cow0 = Rc::new(75);
1381 let mut cow1 = cow0.clone();
1382 let mut cow2 = cow1.clone();
1384 assert!(75 == *cow0.make_unique());
1385 assert!(75 == *cow1.make_unique());
1386 assert!(75 == *cow2.make_unique());
1388 *cow0.make_unique() += 1;
1389 *cow1.make_unique() += 2;
1390 *cow2.make_unique() += 3;
1392 assert!(76 == *cow0);
1393 assert!(77 == *cow1);
1394 assert!(78 == *cow2);
1396 // none should point to the same backing memory
1397 assert!(*cow0 != *cow1);
1398 assert!(*cow0 != *cow2);
1399 assert!(*cow1 != *cow2);
1403 fn test_cowrc_clone_unique2() {
1404 let mut cow0 = Rc::new(75);
1405 let cow1 = cow0.clone();
1406 let cow2 = cow1.clone();
1408 assert!(75 == *cow0);
1409 assert!(75 == *cow1);
1410 assert!(75 == *cow2);
1412 *cow0.make_unique() += 1;
1414 assert!(76 == *cow0);
1415 assert!(75 == *cow1);
1416 assert!(75 == *cow2);
1418 // cow1 and cow2 should share the same contents
1419 // cow0 should have a unique reference
1420 assert!(*cow0 != *cow1);
1421 assert!(*cow0 != *cow2);
1422 assert!(*cow1 == *cow2);
1426 fn test_cowrc_clone_weak() {
1427 let mut cow0 = Rc::new(75);
1428 let cow1_weak = cow0.downgrade();
1430 assert!(75 == *cow0);
1431 assert!(75 == *cow1_weak.upgrade().unwrap());
1433 *cow0.make_unique() += 1;
1435 assert!(76 == *cow0);
1436 assert!(cow1_weak.upgrade().is_none());
1441 let foo = Rc::new(75);
1442 assert_eq!(format!("{:?}", foo), "75");
1447 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1448 assert_eq!(foo, foo.clone());