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("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
62 //! // of 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
65 //! // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
66 //! // automatically dereferenced for us.
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
77 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
78 //! → Gadget introduces a cycle between the objects. This means that their
79 //! reference counts can never reach 0, and the objects will remain allocated: a
80 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
81 //! These pointers don't contribute to the total count.
83 //! Rust actually makes it somewhat difficult to produce this loop in the first
84 //! place: in order to end up with two objects that point at each other, one of
85 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
86 //! memory safety by only giving out shared references to the object it wraps,
87 //! and these don't allow direct mutation. We need to wrap the part of the
88 //! object we wish to mutate in a `RefCell`, which provides *interior
89 //! mutability*: a method to achieve mutability through a shared reference.
90 //! `RefCell` enforces Rust's borrowing rules at runtime. Read the `Cell`
91 //! documentation for more details on interior mutability.
94 //! #![feature(rc_weak)]
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")]
158 use core::cell::Cell;
159 use core::cmp::Ordering;
161 use core::hash::{Hasher, Hash};
162 use core::intrinsics::{assume, drop_in_place, abort};
163 use core::marker::{self, Unsize};
164 use core::mem::{self, align_of, size_of, align_of_val, size_of_val, forget};
165 use core::nonzero::NonZero;
166 use core::ops::{CoerceUnsized, Deref};
169 use heap::deallocate;
171 struct RcBox<T: ?Sized> {
178 /// A reference-counted pointer type over an immutable value.
180 /// See the [module level documentation](./index.html) for more details.
181 #[unsafe_no_drop_flag]
182 #[stable(feature = "rust1", since = "1.0.0")]
183 pub struct Rc<T: ?Sized> {
184 // FIXME #12808: strange names to try to avoid interfering with field
185 // accesses of the contained type via Deref
186 _ptr: NonZero<*mut RcBox<T>>,
189 impl<T: ?Sized> !marker::Send for Rc<T> {}
190 impl<T: ?Sized> !marker::Sync for Rc<T> {}
192 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
195 /// Constructs a new `Rc<T>`.
202 /// let five = Rc::new(5);
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn new(value: T) -> Rc<T> {
208 // there is an implicit weak pointer owned by all the strong
209 // pointers, which ensures that the weak destructor never frees
210 // the allocation while the strong destructor is running, even
211 // if the weak pointer is stored inside the strong one.
212 _ptr: NonZero::new(Box::into_raw(box RcBox {
213 strong: Cell::new(1),
221 /// Unwraps the contained value if the `Rc<T>` is unique.
223 /// If the `Rc<T>` is not unique, an `Err` is returned with the same
229 /// #![feature(rc_unique)]
233 /// let x = Rc::new(3);
234 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
236 /// let x = Rc::new(4);
237 /// let _y = x.clone();
238 /// assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
241 #[unstable(feature = "rc_unique", issue = "27718")]
242 pub fn try_unwrap(rc: Rc<T>) -> Result<T, Rc<T>> {
243 if Rc::is_unique(&rc) {
245 let val = ptr::read(&*rc); // copy the contained object
246 // destruct the box and skip our Drop
247 // we can ignore the refcounts because we know we're unique
248 deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
249 align_of::<RcBox<T>>());
259 impl<T: ?Sized> Rc<T> {
260 /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
265 /// #![feature(rc_weak)]
269 /// let five = Rc::new(5);
271 /// let weak_five = five.downgrade();
273 #[unstable(feature = "rc_weak",
274 reason = "Weak pointers may not belong in this module",
276 pub fn downgrade(&self) -> Weak<T> {
278 Weak { _ptr: self._ptr }
281 /// Get the number of weak references to this value.
283 #[unstable(feature = "rc_counts", issue = "27718")]
284 pub fn weak_count(this: &Rc<T>) -> usize { this.weak() - 1 }
286 /// Get the number of strong references to this value.
288 #[unstable(feature = "rc_counts", issue= "27718")]
289 pub fn strong_count(this: &Rc<T>) -> usize { this.strong() }
291 /// Returns true if there are no other `Rc` or `Weak<T>` values that share
292 /// the same inner value.
297 /// #![feature(rc_unique)]
301 /// let five = Rc::new(5);
303 /// assert!(Rc::is_unique(&five));
306 #[unstable(feature = "rc_unique", issue = "27718")]
307 pub fn is_unique(rc: &Rc<T>) -> bool {
308 Rc::weak_count(rc) == 0 && Rc::strong_count(rc) == 1
311 /// Returns a mutable reference to the contained value if the `Rc<T>` is
314 /// Returns `None` if the `Rc<T>` is not unique.
319 /// #![feature(rc_unique)]
323 /// let mut x = Rc::new(3);
324 /// *Rc::get_mut(&mut x).unwrap() = 4;
325 /// assert_eq!(*x, 4);
327 /// let _y = x.clone();
328 /// assert!(Rc::get_mut(&mut x).is_none());
331 #[unstable(feature = "rc_unique", issue = "27718")]
332 pub fn get_mut(rc: &mut Rc<T>) -> Option<&mut T> {
333 if Rc::is_unique(rc) {
334 let inner = unsafe { &mut **rc._ptr };
335 Some(&mut inner.value)
342 impl<T: Clone> Rc<T> {
343 /// Make a mutable reference from the given `Rc<T>`.
345 /// This is also referred to as a copy-on-write operation because the inner
346 /// data is cloned if the reference count is greater than one.
351 /// #![feature(rc_unique)]
355 /// let mut five = Rc::new(5);
357 /// let mut_five = five.make_unique();
360 #[unstable(feature = "rc_unique", issue = "27718")]
361 pub fn make_unique(&mut self) -> &mut T {
362 if !Rc::is_unique(self) {
363 *self = Rc::new((**self).clone())
365 // This unsafety is ok because we're guaranteed that the pointer
366 // returned is the *only* pointer that will ever be returned to T. Our
367 // reference count is guaranteed to be 1 at this point, and we required
368 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
369 // reference to the inner value.
370 let inner = unsafe { &mut **self._ptr };
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl<T: ?Sized> Deref for Rc<T> {
380 fn deref(&self) -> &T {
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl<T: ?Sized> Drop for Rc<T> {
387 /// Drops the `Rc<T>`.
389 /// This will decrement the strong reference count. If the strong reference
390 /// count becomes zero and the only other references are `Weak<T>` ones,
391 /// `drop`s the inner value.
399 /// let five = Rc::new(5);
403 /// drop(five); // explicit drop
406 /// let five = Rc::new(5);
410 /// } // implicit drop
414 let ptr = *self._ptr;
415 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
416 ptr as *const () as usize != mem::POST_DROP_USIZE {
418 if self.strong() == 0 {
419 // destroy the contained object
420 drop_in_place(&mut (*ptr).value);
422 // remove the implicit "strong weak" pointer now that we've
423 // destroyed the contents.
426 if self.weak() == 0 {
427 deallocate(ptr as *mut u8,
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<T: ?Sized> Clone for Rc<T> {
440 /// Makes a clone of the `Rc<T>`.
442 /// When you clone an `Rc<T>`, it will create another pointer to the data and
443 /// increase the strong reference counter.
450 /// let five = Rc::new(5);
455 fn clone(&self) -> Rc<T> {
457 Rc { _ptr: self._ptr }
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl<T: Default> Default for Rc<T> {
463 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
470 /// let x: Rc<i32> = Default::default();
473 #[stable(feature = "rust1", since = "1.0.0")]
474 fn default() -> Rc<T> {
475 Rc::new(Default::default())
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
481 /// Equality for two `Rc<T>`s.
483 /// Two `Rc<T>`s are equal if their inner value are equal.
490 /// let five = Rc::new(5);
492 /// five == Rc::new(5);
495 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
497 /// Inequality for two `Rc<T>`s.
499 /// Two `Rc<T>`s are unequal if their inner value are unequal.
506 /// let five = Rc::new(5);
508 /// five != Rc::new(5);
511 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T: ?Sized + Eq> Eq for Rc<T> {}
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
519 /// Partial comparison for two `Rc<T>`s.
521 /// The two are compared by calling `partial_cmp()` on their inner values.
528 /// let five = Rc::new(5);
530 /// five.partial_cmp(&Rc::new(5));
533 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
534 (**self).partial_cmp(&**other)
537 /// Less-than comparison for two `Rc<T>`s.
539 /// The two are compared by calling `<` on their inner values.
546 /// let five = Rc::new(5);
548 /// five < Rc::new(5);
551 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
553 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
555 /// The two are compared by calling `<=` on their inner values.
562 /// let five = Rc::new(5);
564 /// five <= Rc::new(5);
567 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
569 /// Greater-than comparison for two `Rc<T>`s.
571 /// The two are compared by calling `>` on their inner values.
578 /// let five = Rc::new(5);
580 /// five > Rc::new(5);
583 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
585 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
587 /// The two are compared by calling `>=` on their inner values.
594 /// let five = Rc::new(5);
596 /// five >= Rc::new(5);
599 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl<T: ?Sized + Ord> Ord for Rc<T> {
604 /// Comparison for two `Rc<T>`s.
606 /// The two are compared by calling `cmp()` on their inner values.
613 /// let five = Rc::new(5);
615 /// five.partial_cmp(&Rc::new(5));
618 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl<T: ?Sized+Hash> Hash for Rc<T> {
623 fn hash<H: Hasher>(&self, state: &mut H) {
624 (**self).hash(state);
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 fmt::Display::fmt(&**self, f)
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
638 fmt::Debug::fmt(&**self, f)
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<T> fmt::Pointer for Rc<T> {
644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
645 fmt::Pointer::fmt(&*self._ptr, f)
649 /// A weak version of `Rc<T>`.
651 /// Weak references do not count when determining if the inner value should be
654 /// See the [module level documentation](./index.html) for more.
655 #[unsafe_no_drop_flag]
656 #[unstable(feature = "rc_weak",
657 reason = "Weak pointers may not belong in this module.",
659 pub struct Weak<T: ?Sized> {
660 // FIXME #12808: strange names to try to avoid interfering with
661 // field accesses of the contained type via Deref
662 _ptr: NonZero<*mut RcBox<T>>,
665 impl<T: ?Sized> !marker::Send for Weak<T> {}
666 impl<T: ?Sized> !marker::Sync for Weak<T> {}
668 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
670 #[unstable(feature = "rc_weak",
671 reason = "Weak pointers may not belong in this module.",
673 impl<T: ?Sized> Weak<T> {
675 /// Upgrades a weak reference to a strong reference.
677 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
679 /// Returns `None` if there were no strong references and the data was
685 /// #![feature(rc_weak)]
689 /// let five = Rc::new(5);
691 /// let weak_five = five.downgrade();
693 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
695 pub fn upgrade(&self) -> Option<Rc<T>> {
696 if self.strong() == 0 {
700 Some(Rc { _ptr: self._ptr })
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl<T: ?Sized> Drop for Weak<T> {
707 /// Drops the `Weak<T>`.
709 /// This will decrement the weak reference count.
714 /// #![feature(rc_weak)]
719 /// let five = Rc::new(5);
720 /// let weak_five = five.downgrade();
724 /// drop(weak_five); // explicit drop
727 /// let five = Rc::new(5);
728 /// let weak_five = five.downgrade();
732 /// } // implicit drop
736 let ptr = *self._ptr;
737 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
738 ptr as *const () as usize != mem::POST_DROP_USIZE {
740 // the weak count starts at 1, and will only go to zero if all
741 // the strong pointers have disappeared.
742 if self.weak() == 0 {
743 deallocate(ptr as *mut u8, size_of_val(&*ptr),
751 #[unstable(feature = "rc_weak",
752 reason = "Weak pointers may not belong in this module.",
754 impl<T: ?Sized> Clone for Weak<T> {
756 /// Makes a clone of the `Weak<T>`.
758 /// This increases the weak reference count.
763 /// #![feature(rc_weak)]
767 /// let weak_five = Rc::new(5).downgrade();
769 /// weak_five.clone();
772 fn clone(&self) -> Weak<T> {
774 Weak { _ptr: self._ptr }
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
785 // NOTE: We checked_add here to deal with mem::forget safety. In particular
786 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
787 // you can free the allocation while outstanding Rcs (or Weaks) exist.
788 // We abort because this is such a degenerate scenario that we don't care about
789 // what happens -- no real program should ever experience this.
791 // This should have negligible overhead since you don't actually need to
792 // clone these much in Rust thanks to ownership and move-semantics.
795 trait RcBoxPtr<T: ?Sized> {
796 fn inner(&self) -> &RcBox<T>;
799 fn strong(&self) -> usize { self.inner().strong.get() }
802 fn inc_strong(&self) {
803 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
807 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
810 fn weak(&self) -> usize { self.inner().weak.get() }
814 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
818 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
821 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
823 fn inner(&self) -> &RcBox<T> {
825 // Safe to assume this here, as if it weren't true, we'd be breaking
826 // the contract anyway.
827 // This allows the null check to be elided in the destructor if we
828 // manipulated the reference count in the same function.
829 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
835 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
837 fn inner(&self) -> &RcBox<T> {
839 // Safe to assume this here, as if it weren't true, we'd be breaking
840 // the contract anyway.
841 // This allows the null check to be elided in the destructor if we
842 // manipulated the reference count in the same function.
843 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
851 use super::{Rc, Weak};
853 use std::cell::RefCell;
854 use std::option::Option;
855 use std::option::Option::{Some, None};
856 use std::result::Result::{Err, Ok};
858 use std::clone::Clone;
862 let x = Rc::new(RefCell::new(5));
864 *x.borrow_mut() = 20;
865 assert_eq!(*y.borrow(), 20);
875 fn test_simple_clone() {
883 fn test_destructor() {
884 let x: Rc<Box<_>> = Rc::new(box 5);
891 let y = x.downgrade();
892 assert!(y.upgrade().is_some());
898 let y = x.downgrade();
900 assert!(y.upgrade().is_none());
904 fn weak_self_cyclic() {
906 x: RefCell<Option<Weak<Cycle>>>
909 let a = Rc::new(Cycle { x: RefCell::new(None) });
910 let b = a.clone().downgrade();
911 *a.x.borrow_mut() = Some(b);
913 // hopefully we don't double-free (or leak)...
919 assert!(Rc::is_unique(&x));
921 assert!(!Rc::is_unique(&x));
923 assert!(Rc::is_unique(&x));
924 let w = x.downgrade();
925 assert!(!Rc::is_unique(&x));
927 assert!(Rc::is_unique(&x));
931 fn test_strong_count() {
932 let a = Rc::new(0u32);
933 assert!(Rc::strong_count(&a) == 1);
934 let w = a.downgrade();
935 assert!(Rc::strong_count(&a) == 1);
936 let b = w.upgrade().expect("upgrade of live rc failed");
937 assert!(Rc::strong_count(&b) == 2);
938 assert!(Rc::strong_count(&a) == 2);
941 assert!(Rc::strong_count(&b) == 1);
943 assert!(Rc::strong_count(&b) == 2);
944 assert!(Rc::strong_count(&c) == 2);
948 fn test_weak_count() {
949 let a = Rc::new(0u32);
950 assert!(Rc::strong_count(&a) == 1);
951 assert!(Rc::weak_count(&a) == 0);
952 let w = a.downgrade();
953 assert!(Rc::strong_count(&a) == 1);
954 assert!(Rc::weak_count(&a) == 1);
956 assert!(Rc::strong_count(&a) == 1);
957 assert!(Rc::weak_count(&a) == 0);
959 assert!(Rc::strong_count(&a) == 2);
960 assert!(Rc::weak_count(&a) == 0);
967 assert_eq!(Rc::try_unwrap(x), Ok(3));
970 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
972 let _w = x.downgrade();
973 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(5)));
978 let mut x = Rc::new(3);
979 *Rc::get_mut(&mut x).unwrap() = 4;
982 assert!(Rc::get_mut(&mut x).is_none());
984 assert!(Rc::get_mut(&mut x).is_some());
985 let _w = x.downgrade();
986 assert!(Rc::get_mut(&mut x).is_none());
990 fn test_cowrc_clone_make_unique() {
991 let mut cow0 = Rc::new(75);
992 let mut cow1 = cow0.clone();
993 let mut cow2 = cow1.clone();
995 assert!(75 == *cow0.make_unique());
996 assert!(75 == *cow1.make_unique());
997 assert!(75 == *cow2.make_unique());
999 *cow0.make_unique() += 1;
1000 *cow1.make_unique() += 2;
1001 *cow2.make_unique() += 3;
1003 assert!(76 == *cow0);
1004 assert!(77 == *cow1);
1005 assert!(78 == *cow2);
1007 // none should point to the same backing memory
1008 assert!(*cow0 != *cow1);
1009 assert!(*cow0 != *cow2);
1010 assert!(*cow1 != *cow2);
1014 fn test_cowrc_clone_unique2() {
1015 let mut cow0 = Rc::new(75);
1016 let cow1 = cow0.clone();
1017 let cow2 = cow1.clone();
1019 assert!(75 == *cow0);
1020 assert!(75 == *cow1);
1021 assert!(75 == *cow2);
1023 *cow0.make_unique() += 1;
1025 assert!(76 == *cow0);
1026 assert!(75 == *cow1);
1027 assert!(75 == *cow2);
1029 // cow1 and cow2 should share the same contents
1030 // cow0 should have a unique reference
1031 assert!(*cow0 != *cow1);
1032 assert!(*cow0 != *cow2);
1033 assert!(*cow1 == *cow2);
1037 fn test_cowrc_clone_weak() {
1038 let mut cow0 = Rc::new(75);
1039 let cow1_weak = cow0.downgrade();
1041 assert!(75 == *cow0);
1042 assert!(75 == *cow1_weak.upgrade().unwrap());
1044 *cow0.make_unique() += 1;
1046 assert!(76 == *cow0);
1047 assert!(cow1_weak.upgrade().is_none());
1052 let foo = Rc::new(75);
1053 assert_eq!(format!("{:?}", foo), "75");
1058 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1059 assert_eq!(foo, foo.clone());