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, they get 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::intrinsics::{assume, drop_in_place};
163 use core::marker::{self, Sized, Unsize};
164 use core::mem::{self, min_align_of, size_of, min_align_of_val, size_of_val, forget};
165 use core::nonzero::NonZero;
166 use core::ops::{CoerceUnsized, Deref, Drop};
167 use core::option::Option;
168 use core::option::Option::{Some, None};
170 use core::result::Result;
171 use core::result::Result::{Ok, Err};
173 use heap::deallocate;
175 struct RcBox<T: ?Sized> {
182 /// A reference-counted pointer type over an immutable value.
184 /// See the [module level documentation](./index.html) for more details.
185 #[unsafe_no_drop_flag]
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub struct Rc<T: ?Sized> {
188 // FIXME #12808: strange names to try to avoid interfering with field
189 // accesses of the contained type via Deref
190 _ptr: NonZero<*mut RcBox<T>>,
193 impl<T: ?Sized> !marker::Send for Rc<T> {}
194 impl<T: ?Sized> !marker::Sync for Rc<T> {}
196 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
199 /// Constructs a new `Rc<T>`.
206 /// let five = Rc::new(5);
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn new(value: T) -> Rc<T> {
212 // there is an implicit weak pointer owned by all the strong
213 // pointers, which ensures that the weak destructor never frees
214 // the allocation while the strong destructor is running, even
215 // if the weak pointer is stored inside the strong one.
216 _ptr: NonZero::new(boxed::into_raw(box RcBox {
217 strong: Cell::new(1),
226 impl<T: ?Sized> Rc<T> {
227 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
232 /// # #![feature(alloc)]
235 /// let five = Rc::new(5);
237 /// let weak_five = five.downgrade();
239 #[unstable(feature = "alloc",
240 reason = "Weak pointers may not belong in this module")]
241 pub fn downgrade(&self) -> Weak<T> {
243 Weak { _ptr: self._ptr }
247 /// Get the number of weak references to this value.
249 #[unstable(feature = "alloc")]
250 pub fn weak_count<T: ?Sized>(this: &Rc<T>) -> usize { this.weak() - 1 }
252 /// Get the number of strong references to this value.
254 #[unstable(feature = "alloc")]
255 pub fn strong_count<T: ?Sized>(this: &Rc<T>) -> usize { this.strong() }
257 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the
258 /// same inner value.
263 /// # #![feature(alloc)]
267 /// let five = Rc::new(5);
269 /// rc::is_unique(&five);
272 #[unstable(feature = "alloc")]
273 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
274 weak_count(rc) == 0 && strong_count(rc) == 1
277 /// Unwraps the contained value if the `Rc<T>` is unique.
279 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
284 /// # #![feature(alloc)]
285 /// use std::rc::{self, Rc};
287 /// let x = Rc::new(3);
288 /// assert_eq!(rc::try_unwrap(x), Ok(3));
290 /// let x = Rc::new(4);
291 /// let _y = x.clone();
292 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4)));
295 #[unstable(feature = "alloc")]
296 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
299 let val = ptr::read(&*rc); // copy the contained object
300 // destruct the box and skip our Drop
301 // we can ignore the refcounts because we know we're unique
302 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
303 min_align_of::<RcBox<T>>());
312 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
314 /// Returns `None` if the `Rc<T>` is not unique.
319 /// # #![feature(alloc)]
320 /// use std::rc::{self, Rc};
322 /// let mut x = Rc::new(3);
323 /// *rc::get_mut(&mut x).unwrap() = 4;
324 /// assert_eq!(*x, 4);
326 /// let _y = x.clone();
327 /// assert!(rc::get_mut(&mut x).is_none());
330 #[unstable(feature = "alloc")]
331 pub fn get_mut<T>(rc: &mut Rc<T>) -> Option<&mut T> {
333 let inner = unsafe { &mut **rc._ptr };
334 Some(&mut inner.value)
340 impl<T: Clone> Rc<T> {
341 /// Make a mutable reference from the given `Rc<T>`.
343 /// This is also referred to as a copy-on-write operation because the inner
344 /// data is cloned if the reference count is greater than one.
349 /// # #![feature(alloc)]
352 /// let mut five = Rc::new(5);
354 /// let mut_five = five.make_unique();
357 #[unstable(feature = "alloc")]
358 pub fn make_unique(&mut self) -> &mut T {
359 if !is_unique(self) {
360 *self = Rc::new((**self).clone())
362 // This unsafety is ok because we're guaranteed that the pointer
363 // returned is the *only* pointer that will ever be returned to T. Our
364 // reference count is guaranteed to be 1 at this point, and we required
365 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
366 // reference to the inner value.
367 let inner = unsafe { &mut **self._ptr };
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl<T: ?Sized> Deref for Rc<T> {
377 fn deref(&self) -> &T {
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<T: ?Sized> Drop for Rc<T> {
384 /// Drops the `Rc<T>`.
386 /// This will decrement the strong reference count. If the strong reference
387 /// count becomes zero and the only other references are `Weak<T>` ones,
388 /// `drop`s the inner value.
393 /// # #![feature(alloc)]
397 /// let five = Rc::new(5);
401 /// drop(five); // explicit drop
404 /// let five = Rc::new(5);
408 /// } // implicit drop
412 let ptr = *self._ptr;
413 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
414 ptr as *const () as usize != mem::POST_DROP_USIZE {
416 if self.strong() == 0 {
417 // destroy the contained object
418 drop_in_place(&mut (*ptr).value);
420 // remove the implicit "strong weak" pointer now that we've
421 // destroyed the contents.
424 if self.weak() == 0 {
425 deallocate(ptr as *mut u8,
427 min_align_of_val(&*ptr))
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl<T: ?Sized> Clone for Rc<T> {
438 /// Makes a clone of the `Rc<T>`.
440 /// When you clone an `Rc<T>`, it will create another pointer to the data and
441 /// increase the strong reference counter.
446 /// # #![feature(alloc)]
449 /// let five = Rc::new(5);
454 fn clone(&self) -> Rc<T> {
456 Rc { _ptr: self._ptr }
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<T: Default> Default for Rc<T> {
462 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
469 /// let x: Rc<i32> = Default::default();
472 #[stable(feature = "rust1", since = "1.0.0")]
473 fn default() -> Rc<T> {
474 Rc::new(Default::default())
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
480 /// Equality for two `Rc<T>`s.
482 /// Two `Rc<T>`s are equal if their inner value are equal.
489 /// let five = Rc::new(5);
491 /// five == Rc::new(5);
494 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
496 /// Inequality for two `Rc<T>`s.
498 /// Two `Rc<T>`s are unequal if their inner value are unequal.
505 /// let five = Rc::new(5);
507 /// five != Rc::new(5);
510 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<T: ?Sized + Eq> Eq for Rc<T> {}
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
518 /// Partial comparison for two `Rc<T>`s.
520 /// The two are compared by calling `partial_cmp()` on their inner values.
527 /// let five = Rc::new(5);
529 /// five.partial_cmp(&Rc::new(5));
532 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
533 (**self).partial_cmp(&**other)
536 /// Less-than comparison for two `Rc<T>`s.
538 /// The two are compared by calling `<` on their inner values.
545 /// let five = Rc::new(5);
547 /// five < Rc::new(5);
550 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
552 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
554 /// The two are compared by calling `<=` on their inner values.
561 /// let five = Rc::new(5);
563 /// five <= Rc::new(5);
566 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
568 /// Greater-than comparison for two `Rc<T>`s.
570 /// The two are compared by calling `>` on their inner values.
577 /// let five = Rc::new(5);
579 /// five > Rc::new(5);
582 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
584 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
586 /// The two are compared by calling `>=` on their inner values.
593 /// let five = Rc::new(5);
595 /// five >= Rc::new(5);
598 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<T: ?Sized + Ord> Ord for Rc<T> {
603 /// Comparison for two `Rc<T>`s.
605 /// The two are compared by calling `cmp()` on their inner values.
612 /// let five = Rc::new(5);
614 /// five.partial_cmp(&Rc::new(5));
617 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl<T: ?Sized+Hash> Hash for Rc<T> {
622 fn hash<H: Hasher>(&self, state: &mut H) {
623 (**self).hash(state);
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630 fmt::Display::fmt(&**self, f)
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 fmt::Debug::fmt(&**self, f)
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl<T> fmt::Pointer for Rc<T> {
643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644 fmt::Pointer::fmt(&*self._ptr, f)
648 /// A weak version of `Rc<T>`.
650 /// Weak references do not count when determining if the inner value should be
653 /// See the [module level documentation](./index.html) for more.
654 #[unsafe_no_drop_flag]
655 #[unstable(feature = "alloc",
656 reason = "Weak pointers may not belong in this module.")]
657 pub struct Weak<T: ?Sized> {
658 // FIXME #12808: strange names to try to avoid interfering with
659 // field accesses of the contained type via Deref
660 _ptr: NonZero<*mut RcBox<T>>,
663 impl<T: ?Sized> !marker::Send for Weak<T> {}
664 impl<T: ?Sized> !marker::Sync for Weak<T> {}
666 #[unstable(feature = "alloc",
667 reason = "Weak pointers may not belong in this module.")]
668 impl<T: ?Sized> Weak<T> {
670 /// Upgrades a weak reference to a strong reference.
672 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
674 /// Returns `None` if there were no strong references and the data was
680 /// # #![feature(alloc)]
683 /// let five = Rc::new(5);
685 /// let weak_five = five.downgrade();
687 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
689 pub fn upgrade(&self) -> Option<Rc<T>> {
690 if self.strong() == 0 {
694 Some(Rc { _ptr: self._ptr })
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<T: ?Sized> Drop for Weak<T> {
701 /// Drops the `Weak<T>`.
703 /// This will decrement the weak reference count.
708 /// # #![feature(alloc)]
712 /// let five = Rc::new(5);
713 /// let weak_five = five.downgrade();
717 /// drop(weak_five); // explicit drop
720 /// let five = Rc::new(5);
721 /// let weak_five = five.downgrade();
725 /// } // implicit drop
729 let ptr = *self._ptr;
730 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
731 ptr as *const () as usize != mem::POST_DROP_USIZE {
733 // the weak count starts at 1, and will only go to zero if all
734 // the strong pointers have disappeared.
735 if self.weak() == 0 {
736 deallocate(ptr as *mut u8, size_of_val(&*ptr),
737 min_align_of_val(&*ptr))
744 #[unstable(feature = "alloc",
745 reason = "Weak pointers may not belong in this module.")]
746 impl<T: ?Sized> Clone for Weak<T> {
748 /// Makes a clone of the `Weak<T>`.
750 /// This increases the weak reference count.
755 /// # #![feature(alloc)]
758 /// let weak_five = Rc::new(5).downgrade();
760 /// weak_five.clone();
763 fn clone(&self) -> Weak<T> {
765 Weak { _ptr: self._ptr }
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
771 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 trait RcBoxPtr<T: ?Sized> {
778 fn inner(&self) -> &RcBox<T>;
781 fn strong(&self) -> usize { self.inner().strong.get() }
784 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
787 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
790 fn weak(&self) -> usize { self.inner().weak.get() }
793 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
796 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
799 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
801 fn inner(&self) -> &RcBox<T> {
803 // Safe to assume this here, as if it weren't true, we'd be breaking
804 // the contract anyway.
805 // This allows the null check to be elided in the destructor if we
806 // manipulated the reference count in the same function.
807 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
813 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
815 fn inner(&self) -> &RcBox<T> {
817 // Safe to assume this here, as if it weren't true, we'd be breaking
818 // the contract anyway.
819 // This allows the null check to be elided in the destructor if we
820 // manipulated the reference count in the same function.
821 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
829 use super::{Rc, Weak, weak_count, strong_count};
831 use std::cell::RefCell;
832 use std::option::Option;
833 use std::option::Option::{Some, None};
834 use std::result::Result::{Err, Ok};
836 use std::clone::Clone;
840 let x = Rc::new(RefCell::new(5));
842 *x.borrow_mut() = 20;
843 assert_eq!(*y.borrow(), 20);
853 fn test_simple_clone() {
861 fn test_destructor() {
862 let x: Rc<Box<_>> = Rc::new(box 5);
869 let y = x.downgrade();
870 assert!(y.upgrade().is_some());
876 let y = x.downgrade();
878 assert!(y.upgrade().is_none());
882 fn weak_self_cyclic() {
884 x: RefCell<Option<Weak<Cycle>>>
887 let a = Rc::new(Cycle { x: RefCell::new(None) });
888 let b = a.clone().downgrade();
889 *a.x.borrow_mut() = Some(b);
891 // hopefully we don't double-free (or leak)...
897 assert!(super::is_unique(&x));
899 assert!(!super::is_unique(&x));
901 assert!(super::is_unique(&x));
902 let w = x.downgrade();
903 assert!(!super::is_unique(&x));
905 assert!(super::is_unique(&x));
909 fn test_strong_count() {
910 let a = Rc::new(0u32);
911 assert!(strong_count(&a) == 1);
912 let w = a.downgrade();
913 assert!(strong_count(&a) == 1);
914 let b = w.upgrade().expect("upgrade of live rc failed");
915 assert!(strong_count(&b) == 2);
916 assert!(strong_count(&a) == 2);
919 assert!(strong_count(&b) == 1);
921 assert!(strong_count(&b) == 2);
922 assert!(strong_count(&c) == 2);
926 fn test_weak_count() {
927 let a = Rc::new(0u32);
928 assert!(strong_count(&a) == 1);
929 assert!(weak_count(&a) == 0);
930 let w = a.downgrade();
931 assert!(strong_count(&a) == 1);
932 assert!(weak_count(&a) == 1);
934 assert!(strong_count(&a) == 1);
935 assert!(weak_count(&a) == 0);
937 assert!(strong_count(&a) == 2);
938 assert!(weak_count(&a) == 0);
945 assert_eq!(super::try_unwrap(x), Ok(3));
948 assert_eq!(super::try_unwrap(x), Err(Rc::new(4)));
950 let _w = x.downgrade();
951 assert_eq!(super::try_unwrap(x), Err(Rc::new(5)));
956 let mut x = Rc::new(3);
957 *super::get_mut(&mut x).unwrap() = 4;
960 assert!(super::get_mut(&mut x).is_none());
962 assert!(super::get_mut(&mut x).is_some());
963 let _w = x.downgrade();
964 assert!(super::get_mut(&mut x).is_none());
968 fn test_cowrc_clone_make_unique() {
969 let mut cow0 = Rc::new(75);
970 let mut cow1 = cow0.clone();
971 let mut cow2 = cow1.clone();
973 assert!(75 == *cow0.make_unique());
974 assert!(75 == *cow1.make_unique());
975 assert!(75 == *cow2.make_unique());
977 *cow0.make_unique() += 1;
978 *cow1.make_unique() += 2;
979 *cow2.make_unique() += 3;
981 assert!(76 == *cow0);
982 assert!(77 == *cow1);
983 assert!(78 == *cow2);
985 // none should point to the same backing memory
986 assert!(*cow0 != *cow1);
987 assert!(*cow0 != *cow2);
988 assert!(*cow1 != *cow2);
992 fn test_cowrc_clone_unique2() {
993 let mut cow0 = Rc::new(75);
994 let cow1 = cow0.clone();
995 let cow2 = cow1.clone();
997 assert!(75 == *cow0);
998 assert!(75 == *cow1);
999 assert!(75 == *cow2);
1001 *cow0.make_unique() += 1;
1003 assert!(76 == *cow0);
1004 assert!(75 == *cow1);
1005 assert!(75 == *cow2);
1007 // cow1 and cow2 should share the same contents
1008 // cow0 should have a unique reference
1009 assert!(*cow0 != *cow1);
1010 assert!(*cow0 != *cow2);
1011 assert!(*cow1 == *cow2);
1015 fn test_cowrc_clone_weak() {
1016 let mut cow0 = Rc::new(75);
1017 let cow1_weak = cow0.downgrade();
1019 assert!(75 == *cow0);
1020 assert!(75 == *cow1_weak.upgrade().unwrap());
1022 *cow0.make_unique() += 1;
1024 assert!(76 == *cow0);
1025 assert!(cow1_weak.upgrade().is_none());
1030 let foo = Rc::new(75);
1031 assert_eq!(format!("{:?}", foo), "75");
1036 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1037 assert_eq!(foo, foo.clone());