1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Thread-local reference-counted boxes (the `Rc<T>` type).
13 //! The `Rc<T>` type provides shared ownership of an immutable value.
14 //! Destruction is deterministic, and will occur as soon as the last owner is
15 //! gone. It is marked as non-sendable because it avoids the overhead of atomic
16 //! reference counting.
18 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
19 //! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but
20 //! will return `None` if the value has already been dropped.
22 //! For example, a tree with parent pointers can be represented by putting the
23 //! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers
24 //! as `Weak<T>` pointers.
28 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
29 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
30 //! unique ownership, because more than one gadget may belong to the same
31 //! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s,
32 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
39 //! // ...other fields
45 //! // ...other fields
49 //! // Create a reference counted Owner.
50 //! let gadget_owner : Rc<Owner> = Rc::new(
51 //! Owner { name: String::from_str("Gadget Man") }
54 //! // Create Gadgets belonging to gadget_owner. To increment the reference
55 //! // count we clone the `Rc<T>` object.
56 //! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
57 //! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
59 //! drop(gadget_owner);
61 //! // Despite dropping gadget_owner, we're still able to print out the name of
62 //! // the Owner of the Gadgets. This is because we've only dropped the
63 //! // reference count object, not the Owner it wraps. As long as there are
64 //! // other `Rc<T>` objects pointing at the same Owner, it will remain allocated. Notice
65 //! // that the `Rc<T>` wrapper around Gadget.owner gets automatically dereferenced
67 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
68 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
70 //! // At the end of the method, gadget1 and gadget2 get destroyed, and with
71 //! // them the last counted references to our Owner. Gadget Man now gets
72 //! // destroyed as well.
76 //! If our requirements change, and we also need to be able to traverse from Owner → Gadget, we
77 //! will run into problems: an `Rc<T>` pointer from Owner → Gadget introduces a cycle between the
78 //! objects. This means that their reference counts can never reach 0, and the objects will remain
79 //! allocated: a memory leak. In order to get around this, we can use `Weak<T>` pointers. These
80 //! pointers don't contribute to the total count.
82 //! Rust actually makes it somewhat difficult to produce this loop in the first place: in order to
83 //! end up with two objects that point at each other, one of them needs to be mutable. This is
84 //! problematic because `Rc<T>` enforces memory safety by only giving out shared references to the
85 //! object it wraps, and these don't allow direct mutation. We need to wrap the part of the object
86 //! we wish to mutate in a `RefCell`, which provides *interior mutability*: a method to achieve
87 //! mutability through a shared reference. `RefCell` enforces Rust's borrowing rules at runtime.
88 //! Read the `Cell` documentation for more details on interior mutability.
92 //! use std::rc::Weak;
93 //! use std::cell::RefCell;
97 //! gadgets: RefCell<Vec<Weak<Gadget>>>
98 //! // ...other fields
104 //! // ...other fields
108 //! // Create a reference counted Owner. Note the fact that we've put the
109 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
110 //! // through a shared reference.
111 //! let gadget_owner : Rc<Owner> = Rc::new(
113 //! name: "Gadget Man".to_string(),
114 //! gadgets: RefCell::new(Vec::new())
118 //! // Create Gadgets belonging to gadget_owner as before.
119 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
120 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
122 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
123 //! // the RefCell holding the Owner's Gadgets.
124 //! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
125 //! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
127 //! // Iterate over our Gadgets, printing their details out
128 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
130 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
131 //! // that their object is still allocated, we need to call upgrade() on them
132 //! // to turn them into a strong reference. This returns an Option, which
133 //! // contains a reference to our object if it still exists.
134 //! let gadget = gadget_opt.upgrade().unwrap();
135 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
138 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
139 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
140 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
141 //! // reference count on Gadget Man, so he gets destroyed as well.
147 use core::borrow::BorrowFrom;
148 use core::cell::Cell;
149 use core::clone::Clone;
150 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
151 use core::default::Default;
153 use core::hash::{self, Hash};
155 use core::mem::{transmute, min_align_of, size_of, forget};
156 use core::nonzero::NonZero;
157 use core::ops::{Deref, Drop};
158 use core::option::Option;
159 use core::option::Option::{Some, None};
160 use core::ptr::{self, PtrExt};
161 use core::result::Result;
162 use core::result::Result::{Ok, Err};
163 use core::intrinsics::assume;
165 use heap::deallocate;
173 /// An immutable reference-counted pointer type.
175 /// See the [module level documentation](../index.html) for more details.
176 #[unsafe_no_drop_flag]
178 #[cfg(stage0)] // NOTE remove impl after next snapshot
180 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
182 _ptr: NonZero<*mut RcBox<T>>,
183 _nosend: marker::NoSend,
184 _noshare: marker::NoSync
187 /// An immutable reference-counted pointer type.
189 /// See the [module level documentation](../index.html) for more details.
190 #[unsafe_no_drop_flag]
192 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
194 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
196 _ptr: NonZero<*mut RcBox<T>>,
199 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
200 impl<T> !marker::Send for Rc<T> {}
202 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
203 impl<T> !marker::Sync for Rc<T> {}
206 /// Constructs a new `Rc<T>`.
213 /// let five = Rc::new(5i);
216 #[cfg(stage0)] // NOTE remove after next snapshot
217 pub fn new(value: T) -> Rc<T> {
220 // there is an implicit weak pointer owned by all the strong pointers, which
221 // ensures that the weak destructor never frees the allocation while the strong
222 // destructor is running, even if the weak pointer is stored inside the strong one.
223 _ptr: NonZero::new(transmute(box RcBox {
225 strong: Cell::new(1),
228 _nosend: marker::NoSend,
229 _noshare: marker::NoSync
234 /// Constructs a new `Rc<T>`.
241 /// let five = Rc::new(5i);
244 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
245 pub fn new(value: T) -> Rc<T> {
248 // there is an implicit weak pointer owned by all the strong pointers, which
249 // ensures that the weak destructor never frees the allocation while the strong
250 // destructor is running, even if the weak pointer is stored inside the strong one.
251 _ptr: NonZero::new(transmute(box RcBox {
253 strong: Cell::new(1),
260 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
267 /// let five = Rc::new(5i);
269 /// let weak_five = five.downgrade();
271 #[cfg(stage0)] // NOTE remove after next snapshot
272 #[unstable = "Weak pointers may not belong in this module"]
273 pub fn downgrade(&self) -> Weak<T> {
277 _nosend: marker::NoSend,
278 _noshare: marker::NoSync
282 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
289 /// let five = Rc::new(5i);
291 /// let weak_five = five.downgrade();
293 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
294 #[unstable = "Weak pointers may not belong in this module"]
295 pub fn downgrade(&self) -> Weak<T> {
297 Weak { _ptr: self._ptr }
301 /// Get the number of weak references to this value.
304 pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 }
306 /// Get the number of strong references to this value.
309 pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
311 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
319 /// let five = Rc::new(5i);
321 /// rc::is_unique(&five);
325 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
326 weak_count(rc) == 0 && strong_count(rc) == 1
329 /// Unwraps the contained value if the `Rc<T>` is unique.
331 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
336 /// use std::rc::{self, Rc};
338 /// let x = Rc::new(3u);
339 /// assert_eq!(rc::try_unwrap(x), Ok(3u));
341 /// let x = Rc::new(4u);
342 /// let _y = x.clone();
343 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u)));
347 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
350 let val = ptr::read(&*rc); // copy the contained object
351 // destruct the box and skip our Drop
352 // we can ignore the refcounts because we know we're unique
353 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
354 min_align_of::<RcBox<T>>());
363 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
365 /// Returns `None` if the `Rc<T>` is not unique.
370 /// use std::rc::{self, Rc};
372 /// let mut x = Rc::new(3u);
373 /// *rc::get_mut(&mut x).unwrap() = 4u;
374 /// assert_eq!(*x, 4u);
376 /// let _y = x.clone();
377 /// assert!(rc::get_mut(&mut x).is_none());
381 pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {
383 let inner = unsafe { &mut **rc._ptr };
384 Some(&mut inner.value)
390 impl<T: Clone> Rc<T> {
391 /// Make a mutable reference from the given `Rc<T>`.
393 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
394 /// the reference count is greater than one.
401 /// let mut five = Rc::new(5i);
403 /// let mut_five = five.make_unique();
407 pub fn make_unique(&mut self) -> &mut T {
408 if !is_unique(self) {
409 *self = Rc::new((**self).clone())
411 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
412 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
413 // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
414 // possible reference to the inner value.
415 let inner = unsafe { &mut **self._ptr };
420 impl<T> BorrowFrom<Rc<T>> for T {
421 fn borrow_from(owned: &Rc<T>) -> &T {
427 impl<T> Deref for Rc<T> {
431 fn deref(&self) -> &T {
438 impl<T> Drop for Rc<T> {
439 /// Drops the `Rc<T>`.
441 /// This will decrement the strong reference count. If the strong reference count becomes zero
442 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
450 /// let five = Rc::new(5i);
454 /// drop(five); // explict drop
457 /// let five = Rc::new(5i);
461 /// } // implicit drop
465 let ptr = *self._ptr;
468 if self.strong() == 0 {
469 ptr::read(&**self); // destroy the contained object
471 // remove the implicit "strong weak" pointer now that we've destroyed the
475 if self.weak() == 0 {
476 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
477 min_align_of::<RcBox<T>>())
486 impl<T> Clone for Rc<T> {
487 /// Makes a clone of the `Rc<T>`.
489 /// This increases the strong reference count.
496 /// let five = Rc::new(5i);
501 #[cfg(stage0)] // NOTE remove after next snapshot
502 fn clone(&self) -> Rc<T> {
504 Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
507 /// Makes a clone of the `Rc<T>`.
509 /// This increases the strong reference count.
516 /// let five = Rc::new(5i);
521 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
522 fn clone(&self) -> Rc<T> {
524 Rc { _ptr: self._ptr }
529 impl<T: Default> Default for Rc<T> {
530 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
536 /// use std::default::Default;
538 /// let x: Rc<int> = Default::default();
542 fn default() -> Rc<T> {
543 Rc::new(Default::default())
548 impl<T: PartialEq> PartialEq for Rc<T> {
549 /// Equality for two `Rc<T>`s.
551 /// Two `Rc<T>`s are equal if their inner value are equal.
558 /// let five = Rc::new(5i);
560 /// five == Rc::new(5i);
563 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
565 /// Inequality for two `Rc<T>`s.
567 /// Two `Rc<T>`s are unequal if their inner value are unequal.
574 /// let five = Rc::new(5i);
576 /// five != Rc::new(5i);
579 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
583 impl<T: Eq> Eq for Rc<T> {}
586 impl<T: PartialOrd> PartialOrd for Rc<T> {
587 /// Partial comparison for two `Rc<T>`s.
589 /// The two are compared by calling `partial_cmp()` on their inner values.
596 /// let five = Rc::new(5i);
598 /// five.partial_cmp(&Rc::new(5i));
601 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
602 (**self).partial_cmp(&**other)
605 /// Less-than comparison for two `Rc<T>`s.
607 /// The two are compared by calling `<` on their inner values.
614 /// let five = Rc::new(5i);
616 /// five < Rc::new(5i);
619 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
621 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
623 /// The two are compared by calling `<=` on their inner values.
630 /// let five = Rc::new(5i);
632 /// five <= Rc::new(5i);
635 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
637 /// Greater-than comparison for two `Rc<T>`s.
639 /// The two are compared by calling `>` on their inner values.
646 /// let five = Rc::new(5i);
648 /// five > Rc::new(5i);
651 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
653 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
655 /// The two are compared by calling `>=` on their inner values.
662 /// let five = Rc::new(5i);
664 /// five >= Rc::new(5i);
667 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
671 impl<T: Ord> Ord for Rc<T> {
672 /// Comparison for two `Rc<T>`s.
674 /// The two are compared by calling `cmp()` on their inner values.
681 /// let five = Rc::new(5i);
683 /// five.partial_cmp(&Rc::new(5i));
686 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
689 // FIXME (#18248) Make `T` `Sized?`
690 impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> {
692 fn hash(&self, state: &mut S) {
693 (**self).hash(state);
697 #[unstable = "Show is experimental."]
698 impl<T: fmt::Show> fmt::Show for Rc<T> {
699 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 write!(f, "Rc({:?})", **self)
705 impl<T: fmt::String> fmt::String for Rc<T> {
706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
707 fmt::String::fmt(&**self, f)
711 /// A weak version of `Rc<T>`.
713 /// Weak references do not count when determining if the inner value should be dropped.
715 /// See the [module level documentation](../index.html) for more.
716 #[unsafe_no_drop_flag]
717 #[unstable = "Weak pointers may not belong in this module."]
718 #[cfg(stage0)] // NOTE remove impl after next snapshot
720 // FIXME #12808: strange names to try to avoid interfering with
721 // field accesses of the contained type via Deref
722 _ptr: NonZero<*mut RcBox<T>>,
723 _nosend: marker::NoSend,
724 _noshare: marker::NoSync
727 /// A weak version of `Rc<T>`.
729 /// Weak references do not count when determining if the inner value should be dropped.
731 /// See the [module level documentation](../index.html) for more.
732 #[unsafe_no_drop_flag]
733 #[unstable = "Weak pointers may not belong in this module."]
734 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
736 // FIXME #12808: strange names to try to avoid interfering with
737 // field accesses of the contained type via Deref
738 _ptr: NonZero<*mut RcBox<T>>,
741 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
743 impl<T> !marker::Send for Weak<T> {}
745 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
747 impl<T> !marker::Sync for Weak<T> {}
750 #[unstable = "Weak pointers may not belong in this module."]
752 /// Upgrades a weak reference to a strong reference.
754 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
756 /// Returns `None` if there were no strong references and the data was destroyed.
763 /// let five = Rc::new(5i);
765 /// let weak_five = five.downgrade();
767 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
769 #[cfg(stage0)] // NOTE remove after next snapshot
770 pub fn upgrade(&self) -> Option<Rc<T>> {
771 if self.strong() == 0 {
775 Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync })
779 /// Upgrades a weak reference to a strong reference.
781 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
783 /// Returns `None` if there were no strong references and the data was destroyed.
790 /// let five = Rc::new(5i);
792 /// let weak_five = five.downgrade();
794 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
796 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
797 pub fn upgrade(&self) -> Option<Rc<T>> {
798 if self.strong() == 0 {
802 Some(Rc { _ptr: self._ptr })
809 impl<T> Drop for Weak<T> {
810 /// Drops the `Weak<T>`.
812 /// This will decrement the weak reference count.
820 /// let five = Rc::new(5i);
821 /// let weak_five = five.downgrade();
825 /// drop(weak_five); // explict drop
828 /// let five = Rc::new(5i);
829 /// let weak_five = five.downgrade();
833 /// } // implicit drop
837 let ptr = *self._ptr;
840 // the weak count starts at 1, and will only go to zero if all the strong pointers
842 if self.weak() == 0 {
843 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
844 min_align_of::<RcBox<T>>())
851 #[unstable = "Weak pointers may not belong in this module."]
852 impl<T> Clone for Weak<T> {
853 /// Makes a clone of the `Weak<T>`.
855 /// This increases the weak reference count.
862 /// let weak_five = Rc::new(5i).downgrade();
864 /// weak_five.clone();
867 #[cfg(stage0)] // NOTE remove after next snapshot
868 fn clone(&self) -> Weak<T> {
870 Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
873 /// Makes a clone of the `Weak<T>`.
875 /// This increases the weak reference count.
882 /// let weak_five = Rc::new(5i).downgrade();
884 /// weak_five.clone();
887 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
888 fn clone(&self) -> Weak<T> {
890 Weak { _ptr: self._ptr }
894 #[unstable = "Show is experimental."]
895 impl<T: fmt::Show> fmt::Show for Weak<T> {
896 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
903 fn inner(&self) -> &RcBox<T>;
906 fn strong(&self) -> uint { self.inner().strong.get() }
909 fn inc_strong(&self) {
910 let strong = self.strong();
911 // The reference count is always at least one unless we're about to drop the type
912 unsafe { assume(strong > 0); }
913 self.inner().strong.set(strong + 1);
917 fn dec_strong(&self) {
918 let strong = self.strong();
919 // The reference count is always at least one unless we're about to drop the type
920 unsafe { assume(strong > 0); }
921 self.inner().strong.set(strong - 1);
925 fn weak(&self) -> uint { self.inner().weak.get() }
928 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
931 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
934 impl<T> RcBoxPtr<T> for Rc<T> {
936 fn inner(&self) -> &RcBox<T> {
938 // Safe to assume this here, as if it weren't true, we'd be breaking
939 // the contract anyway
940 assume(!self._ptr.is_null());
946 impl<T> RcBoxPtr<T> for Weak<T> {
948 fn inner(&self) -> &RcBox<T> {
950 // Safe to assume this here, as if it weren't true, we'd be breaking
951 // the contract anyway
952 assume(!self._ptr.is_null());
961 use super::{Rc, Weak, weak_count, strong_count};
962 use std::cell::RefCell;
963 use std::option::Option;
964 use std::option::Option::{Some, None};
965 use std::result::Result::{Err, Ok};
967 use std::clone::Clone;
971 let x = Rc::new(RefCell::new(5i));
973 *x.borrow_mut() = 20;
974 assert_eq!(*y.borrow(), 20);
984 fn test_simple_clone() {
992 fn test_destructor() {
993 let x = Rc::new(box 5i);
1000 let y = x.downgrade();
1001 assert!(y.upgrade().is_some());
1006 let x = Rc::new(5i);
1007 let y = x.downgrade();
1009 assert!(y.upgrade().is_none());
1013 fn weak_self_cyclic() {
1015 x: RefCell<Option<Weak<Cycle>>>
1018 let a = Rc::new(Cycle { x: RefCell::new(None) });
1019 let b = a.clone().downgrade();
1020 *a.x.borrow_mut() = Some(b);
1022 // hopefully we don't double-free (or leak)...
1027 let x = Rc::new(3u);
1028 assert!(super::is_unique(&x));
1030 assert!(!super::is_unique(&x));
1032 assert!(super::is_unique(&x));
1033 let w = x.downgrade();
1034 assert!(!super::is_unique(&x));
1036 assert!(super::is_unique(&x));
1040 fn test_strong_count() {
1041 let a = Rc::new(0u32);
1042 assert!(strong_count(&a) == 1);
1043 let w = a.downgrade();
1044 assert!(strong_count(&a) == 1);
1045 let b = w.upgrade().expect("upgrade of live rc failed");
1046 assert!(strong_count(&b) == 2);
1047 assert!(strong_count(&a) == 2);
1050 assert!(strong_count(&b) == 1);
1052 assert!(strong_count(&b) == 2);
1053 assert!(strong_count(&c) == 2);
1057 fn test_weak_count() {
1058 let a = Rc::new(0u32);
1059 assert!(strong_count(&a) == 1);
1060 assert!(weak_count(&a) == 0);
1061 let w = a.downgrade();
1062 assert!(strong_count(&a) == 1);
1063 assert!(weak_count(&a) == 1);
1065 assert!(strong_count(&a) == 1);
1066 assert!(weak_count(&a) == 0);
1068 assert!(strong_count(&a) == 2);
1069 assert!(weak_count(&a) == 0);
1075 let x = Rc::new(3u);
1076 assert_eq!(super::try_unwrap(x), Ok(3u));
1077 let x = Rc::new(4u);
1079 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
1080 let x = Rc::new(5u);
1081 let _w = x.downgrade();
1082 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
1087 let mut x = Rc::new(3u);
1088 *super::get_mut(&mut x).unwrap() = 4u;
1091 assert!(super::get_mut(&mut x).is_none());
1093 assert!(super::get_mut(&mut x).is_some());
1094 let _w = x.downgrade();
1095 assert!(super::get_mut(&mut x).is_none());
1099 fn test_cowrc_clone_make_unique() {
1100 let mut cow0 = Rc::new(75u);
1101 let mut cow1 = cow0.clone();
1102 let mut cow2 = cow1.clone();
1104 assert!(75 == *cow0.make_unique());
1105 assert!(75 == *cow1.make_unique());
1106 assert!(75 == *cow2.make_unique());
1108 *cow0.make_unique() += 1;
1109 *cow1.make_unique() += 2;
1110 *cow2.make_unique() += 3;
1112 assert!(76 == *cow0);
1113 assert!(77 == *cow1);
1114 assert!(78 == *cow2);
1116 // none should point to the same backing memory
1117 assert!(*cow0 != *cow1);
1118 assert!(*cow0 != *cow2);
1119 assert!(*cow1 != *cow2);
1123 fn test_cowrc_clone_unique2() {
1124 let mut cow0 = Rc::new(75u);
1125 let cow1 = cow0.clone();
1126 let cow2 = cow1.clone();
1128 assert!(75 == *cow0);
1129 assert!(75 == *cow1);
1130 assert!(75 == *cow2);
1132 *cow0.make_unique() += 1;
1134 assert!(76 == *cow0);
1135 assert!(75 == *cow1);
1136 assert!(75 == *cow2);
1138 // cow1 and cow2 should share the same contents
1139 // cow0 should have a unique reference
1140 assert!(*cow0 != *cow1);
1141 assert!(*cow0 != *cow2);
1142 assert!(*cow1 == *cow2);
1146 fn test_cowrc_clone_weak() {
1147 let mut cow0 = Rc::new(75u);
1148 let cow1_weak = cow0.downgrade();
1150 assert!(75 == *cow0);
1151 assert!(75 == *cow1_weak.upgrade().unwrap());
1153 *cow0.make_unique() += 1;
1155 assert!(76 == *cow0);
1156 assert!(cow1_weak.upgrade().is_none());
1161 let foo = Rc::new(75u);
1162 assert!(format!("{:?}", foo) == "Rc(75u)")