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};
164 use heap::deallocate;
172 /// An immutable reference-counted pointer type.
174 /// See the [module level documentation](../index.html) for more details.
175 #[unsafe_no_drop_flag]
177 #[cfg(stage0)] // NOTE remove impl after next snapshot
179 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
181 _ptr: NonZero<*mut RcBox<T>>,
182 _nosend: marker::NoSend,
183 _noshare: marker::NoSync
186 /// An immutable reference-counted pointer type.
188 /// See the [module level documentation](../index.html) for more details.
189 #[unsafe_no_drop_flag]
191 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
193 // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
195 _ptr: NonZero<*mut RcBox<T>>,
198 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
199 impl<T> !marker::Send for Rc<T> {}
201 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
202 impl<T> !marker::Sync for Rc<T> {}
205 /// Constructs a new `Rc<T>`.
212 /// let five = Rc::new(5i);
215 #[cfg(stage0)] // NOTE remove after next snapshot
216 pub fn new(value: T) -> Rc<T> {
219 // there is an implicit weak pointer owned by all the strong pointers, which
220 // ensures that the weak destructor never frees the allocation while the strong
221 // destructor is running, even if the weak pointer is stored inside the strong one.
222 _ptr: NonZero::new(transmute(box RcBox {
224 strong: Cell::new(1),
227 _nosend: marker::NoSend,
228 _noshare: marker::NoSync
233 /// Constructs a new `Rc<T>`.
240 /// let five = Rc::new(5i);
243 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
244 pub fn new(value: T) -> Rc<T> {
247 // there is an implicit weak pointer owned by all the strong pointers, which
248 // ensures that the weak destructor never frees the allocation while the strong
249 // destructor is running, even if the weak pointer is stored inside the strong one.
250 _ptr: NonZero::new(transmute(box RcBox {
252 strong: Cell::new(1),
259 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
266 /// let five = Rc::new(5i);
268 /// let weak_five = five.downgrade();
270 #[cfg(stage0)] // NOTE remove after next snapshot
271 #[unstable = "Weak pointers may not belong in this module"]
272 pub fn downgrade(&self) -> Weak<T> {
276 _nosend: marker::NoSend,
277 _noshare: marker::NoSync
281 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
288 /// let five = Rc::new(5i);
290 /// let weak_five = five.downgrade();
292 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
293 #[unstable = "Weak pointers may not belong in this module"]
294 pub fn downgrade(&self) -> Weak<T> {
296 Weak { _ptr: self._ptr }
300 /// Get the number of weak references to this value.
303 pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 }
305 /// Get the number of strong references to this value.
308 pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() }
310 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
318 /// let five = Rc::new(5i);
320 /// rc::is_unique(&five);
324 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
325 weak_count(rc) == 0 && strong_count(rc) == 1
328 /// Unwraps the contained value if the `Rc<T>` is unique.
330 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
335 /// use std::rc::{self, Rc};
337 /// let x = Rc::new(3u);
338 /// assert_eq!(rc::try_unwrap(x), Ok(3u));
340 /// let x = Rc::new(4u);
341 /// let _y = x.clone();
342 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u)));
346 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
349 let val = ptr::read(&*rc); // copy the contained object
350 // destruct the box and skip our Drop
351 // we can ignore the refcounts because we know we're unique
352 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
353 min_align_of::<RcBox<T>>());
362 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
364 /// Returns `None` if the `Rc<T>` is not unique.
369 /// use std::rc::{self, Rc};
371 /// let mut x = Rc::new(3u);
372 /// *rc::get_mut(&mut x).unwrap() = 4u;
373 /// assert_eq!(*x, 4u);
375 /// let _y = x.clone();
376 /// assert!(rc::get_mut(&mut x).is_none());
380 pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> {
382 let inner = unsafe { &mut **rc._ptr };
383 Some(&mut inner.value)
389 impl<T: Clone> Rc<T> {
390 /// Make a mutable reference from the given `Rc<T>`.
392 /// This is also referred to as a copy-on-write operation because the inner data is cloned if
393 /// the reference count is greater than one.
400 /// let mut five = Rc::new(5i);
402 /// let mut_five = five.make_unique();
406 pub fn make_unique(&mut self) -> &mut T {
407 if !is_unique(self) {
408 *self = Rc::new((**self).clone())
410 // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
411 // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
412 // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
413 // possible reference to the inner value.
414 let inner = unsafe { &mut **self._ptr };
419 impl<T> BorrowFrom<Rc<T>> for T {
420 fn borrow_from(owned: &Rc<T>) -> &T {
426 impl<T> Deref for Rc<T> {
430 fn deref(&self) -> &T {
437 impl<T> Drop for Rc<T> {
438 /// Drops the `Rc<T>`.
440 /// This will decrement the strong reference count. If the strong reference count becomes zero
441 /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
449 /// let five = Rc::new(5i);
453 /// drop(five); // explict drop
456 /// let five = Rc::new(5i);
460 /// } // implicit drop
464 let ptr = *self._ptr;
467 if self.strong() == 0 {
468 ptr::read(&**self); // destroy the contained object
470 // remove the implicit "strong weak" pointer now that we've destroyed the
474 if self.weak() == 0 {
475 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
476 min_align_of::<RcBox<T>>())
485 impl<T> Clone for Rc<T> {
486 /// Makes a clone of the `Rc<T>`.
488 /// This increases the strong reference count.
495 /// let five = Rc::new(5i);
500 #[cfg(stage0)] // NOTE remove after next snapshot
501 fn clone(&self) -> Rc<T> {
503 Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
506 /// Makes a clone of the `Rc<T>`.
508 /// This increases the strong reference count.
515 /// let five = Rc::new(5i);
520 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
521 fn clone(&self) -> Rc<T> {
523 Rc { _ptr: self._ptr }
528 impl<T: Default> Default for Rc<T> {
529 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
535 /// use std::default::Default;
537 /// let x: Rc<int> = Default::default();
541 fn default() -> Rc<T> {
542 Rc::new(Default::default())
547 impl<T: PartialEq> PartialEq for Rc<T> {
548 /// Equality for two `Rc<T>`s.
550 /// Two `Rc<T>`s are equal if their inner value are equal.
557 /// let five = Rc::new(5i);
559 /// five == Rc::new(5i);
562 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
564 /// Inequality for two `Rc<T>`s.
566 /// Two `Rc<T>`s are unequal if their inner value are unequal.
573 /// let five = Rc::new(5i);
575 /// five != Rc::new(5i);
578 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
582 impl<T: Eq> Eq for Rc<T> {}
585 impl<T: PartialOrd> PartialOrd for Rc<T> {
586 /// Partial comparison for two `Rc<T>`s.
588 /// The two are compared by calling `partial_cmp()` on their inner values.
595 /// let five = Rc::new(5i);
597 /// five.partial_cmp(&Rc::new(5i));
600 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
601 (**self).partial_cmp(&**other)
604 /// Less-than comparison for two `Rc<T>`s.
606 /// The two are compared by calling `<` on their inner values.
613 /// let five = Rc::new(5i);
615 /// five < Rc::new(5i);
618 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
620 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
622 /// The two are compared by calling `<=` on their inner values.
629 /// let five = Rc::new(5i);
631 /// five <= Rc::new(5i);
634 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
636 /// Greater-than comparison for two `Rc<T>`s.
638 /// The two are compared by calling `>` on their inner values.
645 /// let five = Rc::new(5i);
647 /// five > Rc::new(5i);
650 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
652 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
654 /// The two are compared by calling `>=` on their inner values.
661 /// let five = Rc::new(5i);
663 /// five >= Rc::new(5i);
666 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
670 impl<T: Ord> Ord for Rc<T> {
671 /// Comparison for two `Rc<T>`s.
673 /// The two are compared by calling `cmp()` on their inner values.
680 /// let five = Rc::new(5i);
682 /// five.partial_cmp(&Rc::new(5i));
685 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
688 // FIXME (#18248) Make `T` `Sized?`
689 impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> {
691 fn hash(&self, state: &mut S) {
692 (**self).hash(state);
697 impl<T: fmt::Display> fmt::Display for Rc<T> {
698 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699 fmt::Display::fmt(&**self, f)
704 impl<T: fmt::Debug> fmt::Debug for Rc<T> {
705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
706 fmt::Debug::fmt(&**self, f)
710 /// A weak version of `Rc<T>`.
712 /// Weak references do not count when determining if the inner value should be dropped.
714 /// See the [module level documentation](../index.html) for more.
715 #[unsafe_no_drop_flag]
716 #[unstable = "Weak pointers may not belong in this module."]
717 #[cfg(stage0)] // NOTE remove impl after next snapshot
719 // FIXME #12808: strange names to try to avoid interfering with
720 // field accesses of the contained type via Deref
721 _ptr: NonZero<*mut RcBox<T>>,
722 _nosend: marker::NoSend,
723 _noshare: marker::NoSync
726 /// A weak version of `Rc<T>`.
728 /// Weak references do not count when determining if the inner value should be dropped.
730 /// See the [module level documentation](../index.html) for more.
731 #[unsafe_no_drop_flag]
732 #[unstable = "Weak pointers may not belong in this module."]
733 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
735 // FIXME #12808: strange names to try to avoid interfering with
736 // field accesses of the contained type via Deref
737 _ptr: NonZero<*mut RcBox<T>>,
740 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
742 impl<T> !marker::Send for Weak<T> {}
744 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
746 impl<T> !marker::Sync for Weak<T> {}
749 #[unstable = "Weak pointers may not belong in this module."]
751 /// Upgrades a weak reference to a strong reference.
753 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
755 /// Returns `None` if there were no strong references and the data was destroyed.
762 /// let five = Rc::new(5i);
764 /// let weak_five = five.downgrade();
766 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
768 #[cfg(stage0)] // NOTE remove after next snapshot
769 pub fn upgrade(&self) -> Option<Rc<T>> {
770 if self.strong() == 0 {
774 Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync })
778 /// Upgrades a weak reference to a strong reference.
780 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
782 /// Returns `None` if there were no strong references and the data was destroyed.
789 /// let five = Rc::new(5i);
791 /// let weak_five = five.downgrade();
793 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
795 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
796 pub fn upgrade(&self) -> Option<Rc<T>> {
797 if self.strong() == 0 {
801 Some(Rc { _ptr: self._ptr })
808 impl<T> Drop for Weak<T> {
809 /// Drops the `Weak<T>`.
811 /// This will decrement the weak reference count.
819 /// let five = Rc::new(5i);
820 /// let weak_five = five.downgrade();
824 /// drop(weak_five); // explict drop
827 /// let five = Rc::new(5i);
828 /// let weak_five = five.downgrade();
832 /// } // implicit drop
836 let ptr = *self._ptr;
839 // the weak count starts at 1, and will only go to zero if all the strong pointers
841 if self.weak() == 0 {
842 deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
843 min_align_of::<RcBox<T>>())
850 #[unstable = "Weak pointers may not belong in this module."]
851 impl<T> Clone for Weak<T> {
852 /// Makes a clone of the `Weak<T>`.
854 /// This increases the weak reference count.
861 /// let weak_five = Rc::new(5i).downgrade();
863 /// weak_five.clone();
866 #[cfg(stage0)] // NOTE remove after next snapshot
867 fn clone(&self) -> Weak<T> {
869 Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }
872 /// Makes a clone of the `Weak<T>`.
874 /// This increases the weak reference count.
881 /// let weak_five = Rc::new(5i).downgrade();
883 /// weak_five.clone();
886 #[cfg(not(stage0))] // NOTE remove cfg after next snapshot
887 fn clone(&self) -> Weak<T> {
889 Weak { _ptr: self._ptr }
894 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
895 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
902 fn inner(&self) -> &RcBox<T>;
905 fn strong(&self) -> uint { self.inner().strong.get() }
908 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
911 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
914 fn weak(&self) -> uint { self.inner().weak.get() }
917 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
920 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
923 impl<T> RcBoxPtr<T> for Rc<T> {
925 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
928 impl<T> RcBoxPtr<T> for Weak<T> {
930 fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
936 use super::{Rc, Weak, weak_count, strong_count};
937 use std::cell::RefCell;
938 use std::option::Option;
939 use std::option::Option::{Some, None};
940 use std::result::Result::{Err, Ok};
942 use std::clone::Clone;
946 let x = Rc::new(RefCell::new(5i));
948 *x.borrow_mut() = 20;
949 assert_eq!(*y.borrow(), 20);
959 fn test_simple_clone() {
967 fn test_destructor() {
968 let x = Rc::new(box 5i);
975 let y = x.downgrade();
976 assert!(y.upgrade().is_some());
982 let y = x.downgrade();
984 assert!(y.upgrade().is_none());
988 fn weak_self_cyclic() {
990 x: RefCell<Option<Weak<Cycle>>>
993 let a = Rc::new(Cycle { x: RefCell::new(None) });
994 let b = a.clone().downgrade();
995 *a.x.borrow_mut() = Some(b);
997 // hopefully we don't double-free (or leak)...
1002 let x = Rc::new(3u);
1003 assert!(super::is_unique(&x));
1005 assert!(!super::is_unique(&x));
1007 assert!(super::is_unique(&x));
1008 let w = x.downgrade();
1009 assert!(!super::is_unique(&x));
1011 assert!(super::is_unique(&x));
1015 fn test_strong_count() {
1016 let a = Rc::new(0u32);
1017 assert!(strong_count(&a) == 1);
1018 let w = a.downgrade();
1019 assert!(strong_count(&a) == 1);
1020 let b = w.upgrade().expect("upgrade of live rc failed");
1021 assert!(strong_count(&b) == 2);
1022 assert!(strong_count(&a) == 2);
1025 assert!(strong_count(&b) == 1);
1027 assert!(strong_count(&b) == 2);
1028 assert!(strong_count(&c) == 2);
1032 fn test_weak_count() {
1033 let a = Rc::new(0u32);
1034 assert!(strong_count(&a) == 1);
1035 assert!(weak_count(&a) == 0);
1036 let w = a.downgrade();
1037 assert!(strong_count(&a) == 1);
1038 assert!(weak_count(&a) == 1);
1040 assert!(strong_count(&a) == 1);
1041 assert!(weak_count(&a) == 0);
1043 assert!(strong_count(&a) == 2);
1044 assert!(weak_count(&a) == 0);
1050 let x = Rc::new(3u);
1051 assert_eq!(super::try_unwrap(x), Ok(3u));
1052 let x = Rc::new(4u);
1054 assert_eq!(super::try_unwrap(x), Err(Rc::new(4u)));
1055 let x = Rc::new(5u);
1056 let _w = x.downgrade();
1057 assert_eq!(super::try_unwrap(x), Err(Rc::new(5u)));
1062 let mut x = Rc::new(3u);
1063 *super::get_mut(&mut x).unwrap() = 4u;
1066 assert!(super::get_mut(&mut x).is_none());
1068 assert!(super::get_mut(&mut x).is_some());
1069 let _w = x.downgrade();
1070 assert!(super::get_mut(&mut x).is_none());
1074 fn test_cowrc_clone_make_unique() {
1075 let mut cow0 = Rc::new(75u);
1076 let mut cow1 = cow0.clone();
1077 let mut cow2 = cow1.clone();
1079 assert!(75 == *cow0.make_unique());
1080 assert!(75 == *cow1.make_unique());
1081 assert!(75 == *cow2.make_unique());
1083 *cow0.make_unique() += 1;
1084 *cow1.make_unique() += 2;
1085 *cow2.make_unique() += 3;
1087 assert!(76 == *cow0);
1088 assert!(77 == *cow1);
1089 assert!(78 == *cow2);
1091 // none should point to the same backing memory
1092 assert!(*cow0 != *cow1);
1093 assert!(*cow0 != *cow2);
1094 assert!(*cow1 != *cow2);
1098 fn test_cowrc_clone_unique2() {
1099 let mut cow0 = Rc::new(75u);
1100 let cow1 = cow0.clone();
1101 let cow2 = cow1.clone();
1103 assert!(75 == *cow0);
1104 assert!(75 == *cow1);
1105 assert!(75 == *cow2);
1107 *cow0.make_unique() += 1;
1109 assert!(76 == *cow0);
1110 assert!(75 == *cow1);
1111 assert!(75 == *cow2);
1113 // cow1 and cow2 should share the same contents
1114 // cow0 should have a unique reference
1115 assert!(*cow0 != *cow1);
1116 assert!(*cow0 != *cow2);
1117 assert!(*cow1 == *cow2);
1121 fn test_cowrc_clone_weak() {
1122 let mut cow0 = Rc::new(75u);
1123 let cow1_weak = cow0.downgrade();
1125 assert!(75 == *cow0);
1126 assert!(75 == *cow1_weak.upgrade().unwrap());
1128 *cow0.make_unique() += 1;
1130 assert!(76 == *cow0);
1131 assert!(cow1_weak.upgrade().is_none());
1136 let foo = Rc::new(75u);
1137 assert_eq!(format!("{:?}", foo), "75");