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)]
96 //! use std::rc::Weak;
97 //! use std::cell::RefCell;
101 //! gadgets: RefCell<Vec<Weak<Gadget>>>
102 //! // ...other fields
108 //! // ...other fields
112 //! // Create a reference counted Owner. Note the fact that we've put the
113 //! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
114 //! // through a shared reference.
115 //! let gadget_owner : Rc<Owner> = Rc::new(
117 //! name: "Gadget Man".to_string(),
118 //! gadgets: RefCell::new(Vec::new())
122 //! // Create Gadgets belonging to gadget_owner as before.
123 //! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
124 //! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
126 //! // Add the Gadgets to their Owner. To do this we mutably borrow from
127 //! // the RefCell holding the Owner's Gadgets.
128 //! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
129 //! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
131 //! // Iterate over our Gadgets, printing their details out
132 //! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
134 //! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
135 //! // that their object is still allocated, we need to call upgrade()
136 //! // on them to turn them into a strong reference. This returns an
137 //! // Option, which contains a reference to our object if it still
139 //! let gadget = gadget_opt.upgrade().unwrap();
140 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
143 //! // At the end of the method, gadget_owner, gadget1 and gadget2 get
144 //! // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
145 //! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
146 //! // reference count on Gadget Man, they get destroyed as well.
150 #![stable(feature = "rust1", since = "1.0.0")]
152 use core::prelude::*;
159 use core::cell::Cell;
160 use core::cmp::Ordering;
162 use core::hash::{Hasher, Hash};
163 use core::intrinsics::{assume, drop_in_place};
164 use core::marker::{self, Unsize};
165 use core::mem::{self, align_of, size_of, align_of_val, size_of_val, forget};
166 use core::nonzero::NonZero;
167 use core::ops::{CoerceUnsized, Deref};
170 use heap::deallocate;
172 struct RcBox<T: ?Sized> {
179 /// A reference-counted pointer type over an immutable value.
181 /// See the [module level documentation](./index.html) for more details.
182 #[unsafe_no_drop_flag]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub struct Rc<T: ?Sized> {
185 // FIXME #12808: strange names to try to avoid interfering with field
186 // accesses of the contained type via Deref
187 _ptr: NonZero<*mut RcBox<T>>,
190 impl<T: ?Sized> !marker::Send for Rc<T> {}
191 impl<T: ?Sized> !marker::Sync for Rc<T> {}
193 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
196 /// Constructs a new `Rc<T>`.
203 /// let five = Rc::new(5);
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn new(value: T) -> Rc<T> {
209 // there is an implicit weak pointer owned by all the strong
210 // pointers, which ensures that the weak destructor never frees
211 // the allocation while the strong destructor is running, even
212 // if the weak pointer is stored inside the strong one.
213 _ptr: NonZero::new(Box::into_raw(box RcBox {
214 strong: Cell::new(1),
222 /// Unwraps the contained value if the `Rc<T>` is unique.
224 /// If the `Rc<T>` is not unique, an `Err` is returned with the same
230 /// # #![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")]
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)]
268 /// let five = Rc::new(5);
270 /// let weak_five = five.downgrade();
272 #[unstable(feature = "rc_weak",
273 reason = "Weak pointers may not belong in this module")]
274 pub fn downgrade(&self) -> Weak<T> {
276 Weak { _ptr: self._ptr }
279 /// Get the number of weak references to this value.
281 #[unstable(feature = "rc_counts")]
282 pub fn weak_count(this: &Rc<T>) -> usize { this.weak() - 1 }
284 /// Get the number of strong references to this value.
286 #[unstable(feature = "rc_counts")]
287 pub fn strong_count(this: &Rc<T>) -> usize { this.strong() }
289 /// Returns true if there are no other `Rc` or `Weak<T>` values that share
290 /// the same inner value.
295 /// # #![feature(rc_unique)]
298 /// let five = Rc::new(5);
300 /// assert!(Rc::is_unique(&five));
303 #[unstable(feature = "rc_unique")]
304 pub fn is_unique(rc: &Rc<T>) -> bool {
305 Rc::weak_count(rc) == 0 && Rc::strong_count(rc) == 1
308 /// Returns a mutable reference to the contained value if the `Rc<T>` is
311 /// Returns `None` if the `Rc<T>` is not unique.
316 /// # #![feature(rc_unique)]
319 /// let mut x = Rc::new(3);
320 /// *Rc::get_mut(&mut x).unwrap() = 4;
321 /// assert_eq!(*x, 4);
323 /// let _y = x.clone();
324 /// assert!(Rc::get_mut(&mut x).is_none());
327 #[unstable(feature = "rc_unique")]
328 pub fn get_mut(rc: &mut Rc<T>) -> Option<&mut T> {
329 if Rc::is_unique(rc) {
330 let inner = unsafe { &mut **rc._ptr };
331 Some(&mut inner.value)
338 /// Get the number of weak references to this value.
340 #[unstable(feature = "rc_counts")]
341 #[deprecated(since = "1.2.0", reason = "renamed to Rc::weak_count")]
342 pub fn weak_count<T: ?Sized>(this: &Rc<T>) -> usize { Rc::weak_count(this) }
344 /// Get the number of strong references to this value.
346 #[unstable(feature = "rc_counts")]
347 #[deprecated(since = "1.2.0", reason = "renamed to Rc::strong_count")]
348 pub fn strong_count<T: ?Sized>(this: &Rc<T>) -> usize { Rc::strong_count(this) }
350 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the
351 /// same inner value.
356 /// # #![feature(rc_unique)]
360 /// let five = Rc::new(5);
362 /// rc::is_unique(&five);
365 #[unstable(feature = "rc_unique")]
366 #[deprecated(since = "1.2.0", reason = "renamed to Rc::is_unique")]
367 pub fn is_unique<T>(rc: &Rc<T>) -> bool { Rc::is_unique(rc) }
369 /// Unwraps the contained value if the `Rc<T>` is unique.
371 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
376 /// # #![feature(rc_unique)]
377 /// use std::rc::{self, Rc};
379 /// let x = Rc::new(3);
380 /// assert_eq!(rc::try_unwrap(x), Ok(3));
382 /// let x = Rc::new(4);
383 /// let _y = x.clone();
384 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4)));
387 #[unstable(feature = "rc_unique")]
388 #[deprecated(since = "1.2.0", reason = "renamed to Rc::try_unwrap")]
389 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> { Rc::try_unwrap(rc) }
391 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
393 /// Returns `None` if the `Rc<T>` is not unique.
398 /// # #![feature(rc_unique)]
399 /// use std::rc::{self, Rc};
401 /// let mut x = Rc::new(3);
402 /// *rc::get_mut(&mut x).unwrap() = 4;
403 /// assert_eq!(*x, 4);
405 /// let _y = x.clone();
406 /// assert!(rc::get_mut(&mut x).is_none());
409 #[unstable(feature = "rc_unique")]
410 #[deprecated(since = "1.2.0", reason = "renamed to Rc::get_mut")]
411 pub fn get_mut<T>(rc: &mut Rc<T>) -> Option<&mut T> { Rc::get_mut(rc) }
413 impl<T: Clone> Rc<T> {
414 /// Make a mutable reference from the given `Rc<T>`.
416 /// This is also referred to as a copy-on-write operation because the inner
417 /// data is cloned if the reference count is greater than one.
422 /// # #![feature(rc_unique)]
425 /// let mut five = Rc::new(5);
427 /// let mut_five = five.make_unique();
430 #[unstable(feature = "rc_unique")]
431 pub fn make_unique(&mut self) -> &mut T {
432 if !Rc::is_unique(self) {
433 *self = Rc::new((**self).clone())
435 // This unsafety is ok because we're guaranteed that the pointer
436 // returned is the *only* pointer that will ever be returned to T. Our
437 // reference count is guaranteed to be 1 at this point, and we required
438 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
439 // reference to the inner value.
440 let inner = unsafe { &mut **self._ptr };
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<T: ?Sized> Deref for Rc<T> {
450 fn deref(&self) -> &T {
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl<T: ?Sized> Drop for Rc<T> {
457 /// Drops the `Rc<T>`.
459 /// This will decrement the strong reference count. If the strong reference
460 /// count becomes zero and the only other references are `Weak<T>` ones,
461 /// `drop`s the inner value.
469 /// let five = Rc::new(5);
473 /// drop(five); // explicit drop
476 /// let five = Rc::new(5);
480 /// } // implicit drop
484 let ptr = *self._ptr;
485 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
486 ptr as *const () as usize != mem::POST_DROP_USIZE {
488 if self.strong() == 0 {
489 // destroy the contained object
490 drop_in_place(&mut (*ptr).value);
492 // remove the implicit "strong weak" pointer now that we've
493 // destroyed the contents.
496 if self.weak() == 0 {
497 deallocate(ptr as *mut u8,
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl<T: ?Sized> Clone for Rc<T> {
510 /// Makes a clone of the `Rc<T>`.
512 /// When you clone an `Rc<T>`, it will create another pointer to the data and
513 /// increase the strong reference counter.
520 /// let five = Rc::new(5);
525 fn clone(&self) -> Rc<T> {
527 Rc { _ptr: self._ptr }
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl<T: Default> Default for Rc<T> {
533 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
540 /// let x: Rc<i32> = Default::default();
543 #[stable(feature = "rust1", since = "1.0.0")]
544 fn default() -> Rc<T> {
545 Rc::new(Default::default())
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
551 /// Equality for two `Rc<T>`s.
553 /// Two `Rc<T>`s are equal if their inner value are equal.
560 /// let five = Rc::new(5);
562 /// five == Rc::new(5);
565 fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
567 /// Inequality for two `Rc<T>`s.
569 /// Two `Rc<T>`s are unequal if their inner value are unequal.
576 /// let five = Rc::new(5);
578 /// five != Rc::new(5);
581 fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl<T: ?Sized + Eq> Eq for Rc<T> {}
587 #[stable(feature = "rust1", since = "1.0.0")]
588 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
589 /// Partial comparison for two `Rc<T>`s.
591 /// The two are compared by calling `partial_cmp()` on their inner values.
598 /// let five = Rc::new(5);
600 /// five.partial_cmp(&Rc::new(5));
603 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
604 (**self).partial_cmp(&**other)
607 /// Less-than comparison for two `Rc<T>`s.
609 /// The two are compared by calling `<` on their inner values.
616 /// let five = Rc::new(5);
618 /// five < Rc::new(5);
621 fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
623 /// 'Less-than or equal to' comparison for two `Rc<T>`s.
625 /// The two are compared by calling `<=` on their inner values.
632 /// let five = Rc::new(5);
634 /// five <= Rc::new(5);
637 fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
639 /// Greater-than comparison for two `Rc<T>`s.
641 /// The two are compared by calling `>` on their inner values.
648 /// let five = Rc::new(5);
650 /// five > Rc::new(5);
653 fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
655 /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
657 /// The two are compared by calling `>=` on their inner values.
664 /// let five = Rc::new(5);
666 /// five >= Rc::new(5);
669 fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T: ?Sized + Ord> Ord for Rc<T> {
674 /// Comparison for two `Rc<T>`s.
676 /// The two are compared by calling `cmp()` on their inner values.
683 /// let five = Rc::new(5);
685 /// five.partial_cmp(&Rc::new(5));
688 fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T: ?Sized+Hash> Hash for Rc<T> {
693 fn hash<H: Hasher>(&self, state: &mut H) {
694 (**self).hash(state);
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701 fmt::Display::fmt(&**self, f)
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
708 fmt::Debug::fmt(&**self, f)
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T> fmt::Pointer for Rc<T> {
714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
715 fmt::Pointer::fmt(&*self._ptr, f)
719 /// A weak version of `Rc<T>`.
721 /// Weak references do not count when determining if the inner value should be
724 /// See the [module level documentation](./index.html) for more.
725 #[unsafe_no_drop_flag]
726 #[unstable(feature = "rc_weak",
727 reason = "Weak pointers may not belong in this module.")]
728 pub struct Weak<T: ?Sized> {
729 // FIXME #12808: strange names to try to avoid interfering with
730 // field accesses of the contained type via Deref
731 _ptr: NonZero<*mut RcBox<T>>,
734 impl<T: ?Sized> !marker::Send for Weak<T> {}
735 impl<T: ?Sized> !marker::Sync for Weak<T> {}
737 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
739 #[unstable(feature = "rc_weak",
740 reason = "Weak pointers may not belong in this module.")]
741 impl<T: ?Sized> Weak<T> {
743 /// Upgrades a weak reference to a strong reference.
745 /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
747 /// Returns `None` if there were no strong references and the data was
753 /// # #![feature(rc_weak)]
756 /// let five = Rc::new(5);
758 /// let weak_five = five.downgrade();
760 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
762 pub fn upgrade(&self) -> Option<Rc<T>> {
763 if self.strong() == 0 {
767 Some(Rc { _ptr: self._ptr })
772 #[stable(feature = "rust1", since = "1.0.0")]
773 impl<T: ?Sized> Drop for Weak<T> {
774 /// Drops the `Weak<T>`.
776 /// This will decrement the weak reference count.
781 /// # #![feature(rc_weak)]
785 /// let five = Rc::new(5);
786 /// let weak_five = five.downgrade();
790 /// drop(weak_five); // explicit drop
793 /// let five = Rc::new(5);
794 /// let weak_five = five.downgrade();
798 /// } // implicit drop
802 let ptr = *self._ptr;
803 if !(*(&ptr as *const _ as *const *const ())).is_null() &&
804 ptr as *const () as usize != mem::POST_DROP_USIZE {
806 // the weak count starts at 1, and will only go to zero if all
807 // the strong pointers have disappeared.
808 if self.weak() == 0 {
809 deallocate(ptr as *mut u8, size_of_val(&*ptr),
817 #[unstable(feature = "rc_weak",
818 reason = "Weak pointers may not belong in this module.")]
819 impl<T: ?Sized> Clone for Weak<T> {
821 /// Makes a clone of the `Weak<T>`.
823 /// This increases the weak reference count.
828 /// # #![feature(rc_weak)]
831 /// let weak_five = Rc::new(5).downgrade();
833 /// weak_five.clone();
836 fn clone(&self) -> Weak<T> {
838 Weak { _ptr: self._ptr }
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 trait RcBoxPtr<T: ?Sized> {
851 fn inner(&self) -> &RcBox<T>;
854 fn strong(&self) -> usize { self.inner().strong.get() }
857 fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
860 fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
863 fn weak(&self) -> usize { self.inner().weak.get() }
866 fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
869 fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
872 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
874 fn inner(&self) -> &RcBox<T> {
876 // Safe to assume this here, as if it weren't true, we'd be breaking
877 // the contract anyway.
878 // This allows the null check to be elided in the destructor if we
879 // manipulated the reference count in the same function.
880 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
886 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
888 fn inner(&self) -> &RcBox<T> {
890 // Safe to assume this here, as if it weren't true, we'd be breaking
891 // the contract anyway.
892 // This allows the null check to be elided in the destructor if we
893 // manipulated the reference count in the same function.
894 assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
902 use super::{Rc, Weak, weak_count, strong_count};
904 use std::cell::RefCell;
905 use std::option::Option;
906 use std::option::Option::{Some, None};
907 use std::result::Result::{Err, Ok};
909 use std::clone::Clone;
913 let x = Rc::new(RefCell::new(5));
915 *x.borrow_mut() = 20;
916 assert_eq!(*y.borrow(), 20);
926 fn test_simple_clone() {
934 fn test_destructor() {
935 let x: Rc<Box<_>> = Rc::new(box 5);
942 let y = x.downgrade();
943 assert!(y.upgrade().is_some());
949 let y = x.downgrade();
951 assert!(y.upgrade().is_none());
955 fn weak_self_cyclic() {
957 x: RefCell<Option<Weak<Cycle>>>
960 let a = Rc::new(Cycle { x: RefCell::new(None) });
961 let b = a.clone().downgrade();
962 *a.x.borrow_mut() = Some(b);
964 // hopefully we don't double-free (or leak)...
970 assert!(super::is_unique(&x));
972 assert!(!super::is_unique(&x));
974 assert!(super::is_unique(&x));
975 let w = x.downgrade();
976 assert!(!super::is_unique(&x));
978 assert!(super::is_unique(&x));
982 fn test_strong_count() {
983 let a = Rc::new(0u32);
984 assert!(strong_count(&a) == 1);
985 let w = a.downgrade();
986 assert!(strong_count(&a) == 1);
987 let b = w.upgrade().expect("upgrade of live rc failed");
988 assert!(strong_count(&b) == 2);
989 assert!(strong_count(&a) == 2);
992 assert!(strong_count(&b) == 1);
994 assert!(strong_count(&b) == 2);
995 assert!(strong_count(&c) == 2);
999 fn test_weak_count() {
1000 let a = Rc::new(0u32);
1001 assert!(strong_count(&a) == 1);
1002 assert!(weak_count(&a) == 0);
1003 let w = a.downgrade();
1004 assert!(strong_count(&a) == 1);
1005 assert!(weak_count(&a) == 1);
1007 assert!(strong_count(&a) == 1);
1008 assert!(weak_count(&a) == 0);
1010 assert!(strong_count(&a) == 2);
1011 assert!(weak_count(&a) == 0);
1018 assert_eq!(super::try_unwrap(x), Ok(3));
1021 assert_eq!(super::try_unwrap(x), Err(Rc::new(4)));
1023 let _w = x.downgrade();
1024 assert_eq!(super::try_unwrap(x), Err(Rc::new(5)));
1029 let mut x = Rc::new(3);
1030 *super::get_mut(&mut x).unwrap() = 4;
1033 assert!(super::get_mut(&mut x).is_none());
1035 assert!(super::get_mut(&mut x).is_some());
1036 let _w = x.downgrade();
1037 assert!(super::get_mut(&mut x).is_none());
1041 fn test_cowrc_clone_make_unique() {
1042 let mut cow0 = Rc::new(75);
1043 let mut cow1 = cow0.clone();
1044 let mut cow2 = cow1.clone();
1046 assert!(75 == *cow0.make_unique());
1047 assert!(75 == *cow1.make_unique());
1048 assert!(75 == *cow2.make_unique());
1050 *cow0.make_unique() += 1;
1051 *cow1.make_unique() += 2;
1052 *cow2.make_unique() += 3;
1054 assert!(76 == *cow0);
1055 assert!(77 == *cow1);
1056 assert!(78 == *cow2);
1058 // none should point to the same backing memory
1059 assert!(*cow0 != *cow1);
1060 assert!(*cow0 != *cow2);
1061 assert!(*cow1 != *cow2);
1065 fn test_cowrc_clone_unique2() {
1066 let mut cow0 = Rc::new(75);
1067 let cow1 = cow0.clone();
1068 let cow2 = cow1.clone();
1070 assert!(75 == *cow0);
1071 assert!(75 == *cow1);
1072 assert!(75 == *cow2);
1074 *cow0.make_unique() += 1;
1076 assert!(76 == *cow0);
1077 assert!(75 == *cow1);
1078 assert!(75 == *cow2);
1080 // cow1 and cow2 should share the same contents
1081 // cow0 should have a unique reference
1082 assert!(*cow0 != *cow1);
1083 assert!(*cow0 != *cow2);
1084 assert!(*cow1 == *cow2);
1088 fn test_cowrc_clone_weak() {
1089 let mut cow0 = Rc::new(75);
1090 let cow1_weak = cow0.downgrade();
1092 assert!(75 == *cow0);
1093 assert!(75 == *cow1_weak.upgrade().unwrap());
1095 *cow0.make_unique() += 1;
1097 assert!(76 == *cow0);
1098 assert!(cow1_weak.upgrade().is_none());
1103 let foo = Rc::new(75);
1104 assert_eq!(format!("{:?}", foo), "75");
1109 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1110 assert_eq!(foo, foo.clone());