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.
13 //! Single-threaded reference-counting pointers.
15 //! The type [`Rc<T>`][rc] provides shared ownership of a value of type `T`,
16 //! allocated in the heap. Invoking [`clone`][clone] on `Rc` produces a new
17 //! pointer to the same value in the heap. When the last `Rc` pointer to a
18 //! given value is destroyed, the pointed-to value is also destroyed.
20 //! Shared references in Rust disallow mutation by default, and `Rc` is no
21 //! exception. If you need to mutate through an `Rc`, use [`Cell`][cell] or
22 //! [`RefCell`][refcell].
24 //! `Rc` uses non-atomic reference counting. This means that overhead is very
25 //! low, but an `Rc` cannot be sent between threads, and consequently `Rc`
26 //! does not implement [`Send`][send]. As a result, the Rust compiler
27 //! will check *at compile time* that you are not sending `Rc`s between
28 //! threads. If you need multi-threaded, atomic reference counting, use
29 //! [`sync::Arc`][arc].
31 //! The [`downgrade`][downgrade] method can be used to create a non-owning
32 //! [`Weak`][weak] pointer. A `Weak` pointer can be [`upgrade`][upgrade]d
33 //! to an `Rc`, but this will return [`None`][option] if the value has
34 //! already been dropped.
36 //! A cycle between `Rc` pointers will never be deallocated. For this reason,
37 //! `Weak` is used to break cycles. For example, a tree could have strong
38 //! `Rc` pointers from parent nodes to children, and `Weak` pointers from
39 //! children back to their parents.
41 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
42 //! so you can call `T`'s methods on a value of type `Rc<T>`. To avoid name
43 //! clashes with `T`'s methods, the methods of `Rc<T>` itself are [associated
44 //! functions][assoc], called using function-like syntax:
48 //! let my_rc = Rc::new(());
50 //! Rc::downgrade(&my_rc);
53 //! `Weak<T>` does not auto-dereference to `T`, because the value may have
54 //! already been destroyed.
56 //! [rc]: struct.Rc.html
57 //! [weak]: struct.Weak.html
58 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
59 //! [cell]: ../../std/cell/struct.Cell.html
60 //! [refcell]: ../../std/cell/struct.RefCell.html
61 //! [send]: ../../std/marker/trait.Send.html
62 //! [arc]: ../../std/sync/struct.Arc.html
63 //! [deref]: ../../std/ops/trait.Deref.html
64 //! [downgrade]: struct.Rc.html#method.downgrade
65 //! [upgrade]: struct.Weak.html#method.upgrade
66 //! [option]: ../../std/option/enum.Option.html
67 //! [assoc]: ../../book/method-syntax.html#associated-functions
71 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
72 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
73 //! unique ownership, because more than one gadget may belong to the same
74 //! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s,
75 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
82 //! // ...other fields
88 //! // ...other fields
92 //! // Create a reference-counted `Owner`.
93 //! let gadget_owner: Rc<Owner> = Rc::new(
95 //! name: "Gadget Man".to_string(),
99 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
100 //! // value gives us a new pointer to the same `Owner` value, incrementing
101 //! // the reference count in the process.
102 //! let gadget1 = Gadget {
104 //! owner: gadget_owner.clone(),
106 //! let gadget2 = Gadget {
108 //! owner: gadget_owner.clone(),
111 //! // Dispose of our local variable `gadget_owner`.
112 //! drop(gadget_owner);
114 //! // Despite dropping `gadget_owner`, we're still able to print out the name
115 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
116 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
117 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
118 //! // allocated. The field projection `gadget1.owner.name` works because
119 //! // `Rc<Owner>` automatically dereferences to `Owner`.
120 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
121 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
123 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
124 //! // with them the last counted references to our `Owner`. Gadget Man now
125 //! // gets destroyed as well.
129 //! If our requirements change, and we also need to be able to traverse from
130 //! `Owner` to `Gadget`, we will run into problems. An `Rc` pointer from `Owner`
131 //! to `Gadget` introduces a cycle between the values. This means that their
132 //! reference counts can never reach 0, and the values will remain allocated
133 //! forever: a memory leak. In order to get around this, we can use `Weak`
136 //! Rust actually makes it somewhat difficult to produce this loop in the first
137 //! place. In order to end up with two values that point at each other, one of
138 //! them needs to be mutable. This is difficult because `Rc` enforces
139 //! memory safety by only giving out shared references to the value it wraps,
140 //! and these don't allow direct mutation. We need to wrap the part of the
141 //! value we wish to mutate in a [`RefCell`][refcell], which provides *interior
142 //! mutability*: a method to achieve mutability through a shared reference.
143 //! `RefCell` enforces Rust's borrowing rules at runtime.
147 //! use std::rc::Weak;
148 //! use std::cell::RefCell;
152 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
153 //! // ...other fields
158 //! owner: Rc<Owner>,
159 //! // ...other fields
163 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
164 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
165 //! // a shared reference.
166 //! let gadget_owner: Rc<Owner> = Rc::new(
168 //! name: "Gadget Man".to_string(),
169 //! gadgets: RefCell::new(vec![]),
173 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
174 //! let gadget1 = Rc::new(
177 //! owner: gadget_owner.clone(),
180 //! let gadget2 = Rc::new(
183 //! owner: gadget_owner.clone(),
187 //! // Add the `Gadget`s to their `Owner`.
189 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
190 //! gadgets.push(Rc::downgrade(&gadget1));
191 //! gadgets.push(Rc::downgrade(&gadget2));
193 //! // `RefCell` dynamic borrow ends here.
196 //! // Iterate over our `Gadget`s, printing their details out.
197 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
199 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
200 //! // guarantee the value is still allocated, we need to call
201 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
203 //! // In this case we know the value still exists, so we simply
204 //! // `unwrap` the `Option`. In a more complicated program, you might
205 //! // need graceful error handling for a `None` result.
207 //! let gadget = gadget_weak.upgrade().unwrap();
208 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
211 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
212 //! // are destroyed. There are now no strong (`Rc`) pointers to the
213 //! // gadgets, so they are destroyed. This zeroes the reference count on
214 //! // Gadget Man, so he gets destroyed as well.
218 #![stable(feature = "rust1", since = "1.0.0")]
226 use core::cell::Cell;
227 use core::cmp::Ordering;
229 use core::hash::{Hash, Hasher};
230 use core::intrinsics::{abort, assume};
232 use core::marker::Unsize;
233 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
234 use core::ops::Deref;
235 use core::ops::CoerceUnsized;
236 use core::ptr::{self, Shared};
237 use core::convert::From;
239 use heap::deallocate;
242 struct RcBox<T: ?Sized> {
249 /// A single-threaded reference-counting pointer.
251 /// See the [module-level documentation](./index.html) for more details.
253 /// The inherent methods of `Rc` are all associated functions, which means
254 /// that you have to call them as e.g. `Rc::get_mut(&value)` instead of
255 /// `value.get_mut()`. This avoids conflicts with methods of the inner
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub struct Rc<T: ?Sized> {
259 ptr: Shared<RcBox<T>>,
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T: ?Sized> !marker::Send for Rc<T> {}
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<T: ?Sized> !marker::Sync for Rc<T> {}
267 #[unstable(feature = "coerce_unsized", issue = "27732")]
268 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
271 /// Constructs a new `Rc<T>`.
278 /// let five = Rc::new(5);
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn new(value: T) -> Rc<T> {
284 // there is an implicit weak pointer owned by all the strong
285 // pointers, which ensures that the weak destructor never frees
286 // the allocation while the strong destructor is running, even
287 // if the weak pointer is stored inside the strong one.
288 ptr: Shared::new(Box::into_raw(box RcBox {
289 strong: Cell::new(1),
297 /// Returns the contained value, if the `Rc` has exactly one strong reference.
299 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
302 /// This will succeed even if there are outstanding weak references.
304 /// [result]: ../../std/result/enum.Result.html
311 /// let x = Rc::new(3);
312 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
314 /// let x = Rc::new(4);
315 /// let _y = x.clone();
316 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
319 #[stable(feature = "rc_unique", since = "1.4.0")]
320 pub fn try_unwrap(this: Self) -> Result<T, Self> {
321 if Rc::would_unwrap(&this) {
323 let val = ptr::read(&*this); // copy the contained object
325 // Indicate to Weaks that they can't be promoted by decrememting
326 // the strong count, and then remove the implicit "strong weak"
327 // pointer while also handling drop logic by just crafting a
330 let _weak = Weak { ptr: this.ptr };
339 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
342 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
343 /// [result]: ../../std/result/enum.Result.html
348 /// #![feature(rc_would_unwrap)]
352 /// let x = Rc::new(3);
353 /// assert!(Rc::would_unwrap(&x));
354 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
356 /// let x = Rc::new(4);
357 /// let _y = x.clone();
358 /// assert!(!Rc::would_unwrap(&x));
359 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
361 #[unstable(feature = "rc_would_unwrap",
362 reason = "just added for niche usecase",
364 pub fn would_unwrap(this: &Self) -> bool {
365 Rc::strong_count(&this) == 1
368 /// Consumes the `Rc`, returning the wrapped pointer.
370 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
371 /// [`Rc::from_raw`][from_raw].
373 /// [from_raw]: struct.Rc.html#method.from_raw
378 /// #![feature(rc_raw)]
382 /// let x = Rc::new(10);
383 /// let x_ptr = Rc::into_raw(x);
384 /// assert_eq!(unsafe { *x_ptr }, 10);
386 #[unstable(feature = "rc_raw", issue = "37197")]
387 pub fn into_raw(this: Self) -> *mut T {
388 let ptr = unsafe { &mut (**this.ptr).value as *mut _ };
393 /// Constructs an `Rc` from a raw pointer.
395 /// The raw pointer must have been previously returned by a call to a
396 /// [`Rc::into_raw`][into_raw].
398 /// This function is unsafe because improper use may lead to memory problems. For example, a
399 /// double-free may occur if the function is called twice on the same raw pointer.
401 /// [into_raw]: struct.Rc.html#method.into_raw
406 /// #![feature(rc_raw)]
410 /// let x = Rc::new(10);
411 /// let x_ptr = Rc::into_raw(x);
414 /// // Convert back to an `Rc` to prevent leak.
415 /// let x = Rc::from_raw(x_ptr);
416 /// assert_eq!(*x, 10);
418 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
421 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
423 #[unstable(feature = "rc_raw", issue = "37197")]
424 pub unsafe fn from_raw(ptr: *mut T) -> Self {
425 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
426 // `value` field from the pointer.
427 Rc { ptr: Shared::new((ptr as *mut u8).offset(-offset_of!(RcBox<T>, value)) as *mut _) }
432 /// Constructs a new `Rc<str>` from a string slice.
434 #[unstable(feature = "rustc_private",
435 reason = "for internal use in rustc",
437 pub fn __from_str(value: &str) -> Rc<str> {
439 // Allocate enough space for `RcBox<str>`.
440 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
441 let vec = RawVec::<usize>::with_capacity(aligned_len);
444 // Initialize fields of `RcBox<str>`.
445 *ptr.offset(0) = 1; // strong: Cell::new(1)
446 *ptr.offset(1) = 1; // weak: Cell::new(1)
447 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
448 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
449 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
450 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
451 Rc { ptr: Shared::new(rcbox_ptr) }
456 impl<T: ?Sized> Rc<T> {
457 /// Creates a new [`Weak`][weak] pointer to this value.
459 /// [weak]: struct.Weak.html
466 /// let five = Rc::new(5);
468 /// let weak_five = Rc::downgrade(&five);
470 #[stable(feature = "rc_weak", since = "1.4.0")]
471 pub fn downgrade(this: &Self) -> Weak<T> {
473 Weak { ptr: this.ptr }
476 /// Gets the number of [`Weak`][weak] pointers to this value.
478 /// [weak]: struct.Weak.html
483 /// #![feature(rc_counts)]
487 /// let five = Rc::new(5);
488 /// let _weak_five = Rc::downgrade(&five);
490 /// assert_eq!(1, Rc::weak_count(&five));
493 #[unstable(feature = "rc_counts", reason = "not clearly useful",
495 pub fn weak_count(this: &Self) -> usize {
499 /// Gets the number of strong (`Rc`) pointers to this value.
504 /// #![feature(rc_counts)]
508 /// let five = Rc::new(5);
509 /// let _also_five = five.clone();
511 /// assert_eq!(2, Rc::strong_count(&five));
514 #[unstable(feature = "rc_counts", reason = "not clearly useful",
516 pub fn strong_count(this: &Self) -> usize {
520 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
521 /// this inner value.
523 /// [weak]: struct.Weak.html
528 /// #![feature(rc_counts)]
532 /// let five = Rc::new(5);
534 /// assert!(Rc::is_unique(&five));
537 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
539 pub fn is_unique(this: &Self) -> bool {
540 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
543 /// Returns a mutable reference to the inner value, if there are
544 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
546 /// Returns [`None`][option] otherwise, because it is not safe to
547 /// mutate a shared value.
549 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
550 /// the inner value when it's shared.
552 /// [weak]: struct.Weak.html
553 /// [option]: ../../std/option/enum.Option.html
554 /// [make_mut]: struct.Rc.html#method.make_mut
555 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
562 /// let mut x = Rc::new(3);
563 /// *Rc::get_mut(&mut x).unwrap() = 4;
564 /// assert_eq!(*x, 4);
566 /// let _y = x.clone();
567 /// assert!(Rc::get_mut(&mut x).is_none());
570 #[stable(feature = "rc_unique", since = "1.4.0")]
571 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
572 if Rc::is_unique(this) {
573 let inner = unsafe { &mut **this.ptr };
574 Some(&mut inner.value)
581 #[unstable(feature = "ptr_eq",
582 reason = "newly added",
584 /// Returns true if the two `Rc`s point to the same value (not
585 /// just values that compare as equal).
590 /// #![feature(ptr_eq)]
594 /// let five = Rc::new(5);
595 /// let same_five = five.clone();
596 /// let other_five = Rc::new(5);
598 /// assert!(Rc::ptr_eq(&five, &same_five));
599 /// assert!(!Rc::ptr_eq(&five, &other_five));
601 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
602 let this_ptr: *const RcBox<T> = *this.ptr;
603 let other_ptr: *const RcBox<T> = *other.ptr;
604 this_ptr == other_ptr
608 impl<T: Clone> Rc<T> {
609 /// Makes a mutable reference into the given `Rc`.
611 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
612 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
613 /// ensure unique ownership. This is also referred to as clone-on-write.
615 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
617 /// [weak]: struct.Weak.html
618 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
619 /// [get_mut]: struct.Rc.html#method.get_mut
626 /// let mut data = Rc::new(5);
628 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
629 /// let mut other_data = data.clone(); // Won't clone inner data
630 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
631 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
632 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
634 /// // Now `data` and `other_data` point to different values.
635 /// assert_eq!(*data, 8);
636 /// assert_eq!(*other_data, 12);
639 #[stable(feature = "rc_unique", since = "1.4.0")]
640 pub fn make_mut(this: &mut Self) -> &mut T {
641 if Rc::strong_count(this) != 1 {
642 // Gotta clone the data, there are other Rcs
643 *this = Rc::new((**this).clone())
644 } else if Rc::weak_count(this) != 0 {
645 // Can just steal the data, all that's left is Weaks
647 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
648 mem::swap(this, &mut swap);
650 // Remove implicit strong-weak ref (no need to craft a fake
651 // Weak here -- we know other Weaks can clean up for us)
656 // This unsafety is ok because we're guaranteed that the pointer
657 // returned is the *only* pointer that will ever be returned to T. Our
658 // reference count is guaranteed to be 1 at this point, and we required
659 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
660 // reference to the inner value.
661 let inner = unsafe { &mut **this.ptr };
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<T: ?Sized> Deref for Rc<T> {
671 fn deref(&self) -> &T {
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl<T: ?Sized> Drop for Rc<T> {
680 /// This will decrement the strong reference count. If the strong reference
681 /// count reaches zero then the only other references (if any) are
682 /// [`Weak`][weak], so we `drop` the inner value.
684 /// [weak]: struct.Weak.html
693 /// impl Drop for Foo {
694 /// fn drop(&mut self) {
695 /// println!("dropped!");
699 /// let foo = Rc::new(Foo);
700 /// let foo2 = foo.clone();
702 /// drop(foo); // Doesn't print anything
703 /// drop(foo2); // Prints "dropped!"
705 #[unsafe_destructor_blind_to_params]
711 if self.strong() == 0 {
712 // destroy the contained object
713 ptr::drop_in_place(&mut (*ptr).value);
715 // remove the implicit "strong weak" pointer now that we've
716 // destroyed the contents.
719 if self.weak() == 0 {
720 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
727 #[stable(feature = "rust1", since = "1.0.0")]
728 impl<T: ?Sized> Clone for Rc<T> {
729 /// Makes a clone of the `Rc` pointer.
731 /// This creates another pointer to the same inner value, increasing the
732 /// strong reference count.
739 /// let five = Rc::new(5);
744 fn clone(&self) -> Rc<T> {
750 #[stable(feature = "rust1", since = "1.0.0")]
751 impl<T: Default> Default for Rc<T> {
752 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
759 /// let x: Rc<i32> = Default::default();
760 /// assert_eq!(*x, 0);
763 fn default() -> Rc<T> {
764 Rc::new(Default::default())
768 #[stable(feature = "rust1", since = "1.0.0")]
769 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
770 /// Equality for two `Rc`s.
772 /// Two `Rc`s are equal if their inner values are equal.
779 /// let five = Rc::new(5);
781 /// assert!(five == Rc::new(5));
784 fn eq(&self, other: &Rc<T>) -> bool {
788 /// Inequality for two `Rc`s.
790 /// Two `Rc`s are unequal if their inner values are unequal.
797 /// let five = Rc::new(5);
799 /// assert!(five != Rc::new(6));
802 fn ne(&self, other: &Rc<T>) -> bool {
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<T: ?Sized + Eq> Eq for Rc<T> {}
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
812 /// Partial comparison for two `Rc`s.
814 /// The two are compared by calling `partial_cmp()` on their inner values.
820 /// use std::cmp::Ordering;
822 /// let five = Rc::new(5);
824 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
827 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
828 (**self).partial_cmp(&**other)
831 /// Less-than comparison for two `Rc`s.
833 /// The two are compared by calling `<` on their inner values.
840 /// let five = Rc::new(5);
842 /// assert!(five < Rc::new(6));
845 fn lt(&self, other: &Rc<T>) -> bool {
849 /// 'Less than or equal to' comparison for two `Rc`s.
851 /// The two are compared by calling `<=` on their inner values.
858 /// let five = Rc::new(5);
860 /// assert!(five <= Rc::new(5));
863 fn le(&self, other: &Rc<T>) -> bool {
867 /// Greater-than comparison for two `Rc`s.
869 /// The two are compared by calling `>` on their inner values.
876 /// let five = Rc::new(5);
878 /// assert!(five > Rc::new(4));
881 fn gt(&self, other: &Rc<T>) -> bool {
885 /// 'Greater than or equal to' comparison for two `Rc`s.
887 /// The two are compared by calling `>=` on their inner values.
894 /// let five = Rc::new(5);
896 /// assert!(five >= Rc::new(5));
899 fn ge(&self, other: &Rc<T>) -> bool {
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T: ?Sized + Ord> Ord for Rc<T> {
906 /// Comparison for two `Rc`s.
908 /// The two are compared by calling `cmp()` on their inner values.
914 /// use std::cmp::Ordering;
916 /// let five = Rc::new(5);
918 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
921 fn cmp(&self, other: &Rc<T>) -> Ordering {
922 (**self).cmp(&**other)
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<T: ?Sized + Hash> Hash for Rc<T> {
928 fn hash<H: Hasher>(&self, state: &mut H) {
929 (**self).hash(state);
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
935 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
936 fmt::Display::fmt(&**self, f)
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
942 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
943 fmt::Debug::fmt(&**self, f)
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<T: ?Sized> fmt::Pointer for Rc<T> {
949 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
950 fmt::Pointer::fmt(&*self.ptr, f)
954 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
955 impl<T> From<T> for Rc<T> {
956 fn from(t: T) -> Self {
961 /// A weak version of [`Rc`][rc].
963 /// `Weak` pointers do not count towards determining if the inner value
964 /// should be dropped.
966 /// The typical way to obtain a `Weak` pointer is to call
967 /// [`Rc::downgrade`][downgrade].
969 /// See the [module-level documentation](./index.html) for more details.
971 /// [rc]: struct.Rc.html
972 /// [downgrade]: struct.Rc.html#method.downgrade
973 #[stable(feature = "rc_weak", since = "1.4.0")]
974 pub struct Weak<T: ?Sized> {
975 ptr: Shared<RcBox<T>>,
978 #[stable(feature = "rc_weak", since = "1.4.0")]
979 impl<T: ?Sized> !marker::Send for Weak<T> {}
980 #[stable(feature = "rc_weak", since = "1.4.0")]
981 impl<T: ?Sized> !marker::Sync for Weak<T> {}
983 #[unstable(feature = "coerce_unsized", issue = "27732")]
984 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
987 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
989 /// This allocates memory for `T`, but does not initialize it. Calling
990 /// [`upgrade`][upgrade] on the return value always gives
991 /// [`None`][option].
993 /// [upgrade]: struct.Weak.html#method.upgrade
994 /// [option]: ../../std/option/enum.Option.html
999 /// use std::rc::Weak;
1001 /// let empty: Weak<i64> = Weak::new();
1002 /// assert!(empty.upgrade().is_none());
1004 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1005 pub fn new() -> Weak<T> {
1008 ptr: Shared::new(Box::into_raw(box RcBox {
1009 strong: Cell::new(0),
1011 value: uninitialized(),
1018 impl<T: ?Sized> Weak<T> {
1019 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
1021 /// Returns [`None`][option] if the strong count has reached zero and the
1022 /// inner value was destroyed.
1024 /// [rc]: struct.Rc.html
1025 /// [option]: ../../std/option/enum.Option.html
1030 /// use std::rc::Rc;
1032 /// let five = Rc::new(5);
1034 /// let weak_five = Rc::downgrade(&five);
1036 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1037 /// assert!(strong_five.is_some());
1039 /// // Destroy all strong pointers.
1040 /// drop(strong_five);
1043 /// assert!(weak_five.upgrade().is_none());
1045 #[stable(feature = "rc_weak", since = "1.4.0")]
1046 pub fn upgrade(&self) -> Option<Rc<T>> {
1047 if self.strong() == 0 {
1051 Some(Rc { ptr: self.ptr })
1056 #[stable(feature = "rc_weak", since = "1.4.0")]
1057 impl<T: ?Sized> Drop for Weak<T> {
1058 /// Drops the `Weak` pointer.
1060 /// This will decrement the weak reference count.
1065 /// use std::rc::Rc;
1069 /// impl Drop for Foo {
1070 /// fn drop(&mut self) {
1071 /// println!("dropped!");
1075 /// let foo = Rc::new(Foo);
1076 /// let weak_foo = Rc::downgrade(&foo);
1077 /// let other_weak_foo = weak_foo.clone();
1079 /// drop(weak_foo); // Doesn't print anything
1080 /// drop(foo); // Prints "dropped!"
1082 /// assert!(other_weak_foo.upgrade().is_none());
1084 fn drop(&mut self) {
1086 let ptr = *self.ptr;
1089 // the weak count starts at 1, and will only go to zero if all
1090 // the strong pointers have disappeared.
1091 if self.weak() == 0 {
1092 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1098 #[stable(feature = "rc_weak", since = "1.4.0")]
1099 impl<T: ?Sized> Clone for Weak<T> {
1100 /// Makes a clone of the `Weak` pointer.
1102 /// This creates another pointer to the same inner value, increasing the
1103 /// weak reference count.
1108 /// use std::rc::Rc;
1110 /// let weak_five = Rc::downgrade(&Rc::new(5));
1112 /// weak_five.clone();
1115 fn clone(&self) -> Weak<T> {
1117 Weak { ptr: self.ptr }
1121 #[stable(feature = "rc_weak", since = "1.4.0")]
1122 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1129 impl<T> Default for Weak<T> {
1130 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1132 /// This allocates memory for `T`, but does not initialize it. Calling
1133 /// [`upgrade`][upgrade] on the return value always gives
1134 /// [`None`][option].
1136 /// [upgrade]: struct.Weak.html#method.upgrade
1137 /// [option]: ../../std/option/enum.Option.html
1142 /// use std::rc::Weak;
1144 /// let empty: Weak<i64> = Default::default();
1145 /// assert!(empty.upgrade().is_none());
1147 fn default() -> Weak<T> {
1152 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1153 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1154 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1155 // We abort because this is such a degenerate scenario that we don't care about
1156 // what happens -- no real program should ever experience this.
1158 // This should have negligible overhead since you don't actually need to
1159 // clone these much in Rust thanks to ownership and move-semantics.
1162 trait RcBoxPtr<T: ?Sized> {
1163 fn inner(&self) -> &RcBox<T>;
1166 fn strong(&self) -> usize {
1167 self.inner().strong.get()
1171 fn inc_strong(&self) {
1172 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1176 fn dec_strong(&self) {
1177 self.inner().strong.set(self.strong() - 1);
1181 fn weak(&self) -> usize {
1182 self.inner().weak.get()
1186 fn inc_weak(&self) {
1187 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1191 fn dec_weak(&self) {
1192 self.inner().weak.set(self.weak() - 1);
1196 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1198 fn inner(&self) -> &RcBox<T> {
1200 // Safe to assume this here, as if it weren't true, we'd be breaking
1201 // the contract anyway.
1202 // This allows the null check to be elided in the destructor if we
1203 // manipulated the reference count in the same function.
1204 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1210 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1212 fn inner(&self) -> &RcBox<T> {
1214 // Safe to assume this here, as if it weren't true, we'd be breaking
1215 // the contract anyway.
1216 // This allows the null check to be elided in the destructor if we
1217 // manipulated the reference count in the same function.
1218 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1226 use super::{Rc, Weak};
1227 use std::boxed::Box;
1228 use std::cell::RefCell;
1229 use std::option::Option;
1230 use std::option::Option::{None, Some};
1231 use std::result::Result::{Err, Ok};
1233 use std::clone::Clone;
1234 use std::convert::From;
1238 let x = Rc::new(RefCell::new(5));
1240 *x.borrow_mut() = 20;
1241 assert_eq!(*y.borrow(), 20);
1251 fn test_simple_clone() {
1259 fn test_destructor() {
1260 let x: Rc<Box<_>> = Rc::new(box 5);
1267 let y = Rc::downgrade(&x);
1268 assert!(y.upgrade().is_some());
1274 let y = Rc::downgrade(&x);
1276 assert!(y.upgrade().is_none());
1280 fn weak_self_cyclic() {
1282 x: RefCell<Option<Weak<Cycle>>>,
1285 let a = Rc::new(Cycle { x: RefCell::new(None) });
1286 let b = Rc::downgrade(&a.clone());
1287 *a.x.borrow_mut() = Some(b);
1289 // hopefully we don't double-free (or leak)...
1295 assert!(Rc::is_unique(&x));
1297 assert!(!Rc::is_unique(&x));
1299 assert!(Rc::is_unique(&x));
1300 let w = Rc::downgrade(&x);
1301 assert!(!Rc::is_unique(&x));
1303 assert!(Rc::is_unique(&x));
1307 fn test_strong_count() {
1309 assert!(Rc::strong_count(&a) == 1);
1310 let w = Rc::downgrade(&a);
1311 assert!(Rc::strong_count(&a) == 1);
1312 let b = w.upgrade().expect("upgrade of live rc failed");
1313 assert!(Rc::strong_count(&b) == 2);
1314 assert!(Rc::strong_count(&a) == 2);
1317 assert!(Rc::strong_count(&b) == 1);
1319 assert!(Rc::strong_count(&b) == 2);
1320 assert!(Rc::strong_count(&c) == 2);
1324 fn test_weak_count() {
1326 assert!(Rc::strong_count(&a) == 1);
1327 assert!(Rc::weak_count(&a) == 0);
1328 let w = Rc::downgrade(&a);
1329 assert!(Rc::strong_count(&a) == 1);
1330 assert!(Rc::weak_count(&a) == 1);
1332 assert!(Rc::strong_count(&a) == 1);
1333 assert!(Rc::weak_count(&a) == 0);
1335 assert!(Rc::strong_count(&a) == 2);
1336 assert!(Rc::weak_count(&a) == 0);
1343 assert_eq!(Rc::try_unwrap(x), Ok(3));
1346 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1348 let _w = Rc::downgrade(&x);
1349 assert_eq!(Rc::try_unwrap(x), Ok(5));
1353 fn into_from_raw() {
1354 let x = Rc::new(box "hello");
1357 let x_ptr = Rc::into_raw(x);
1360 assert_eq!(**x_ptr, "hello");
1362 let x = Rc::from_raw(x_ptr);
1363 assert_eq!(**x, "hello");
1365 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1371 let mut x = Rc::new(3);
1372 *Rc::get_mut(&mut x).unwrap() = 4;
1375 assert!(Rc::get_mut(&mut x).is_none());
1377 assert!(Rc::get_mut(&mut x).is_some());
1378 let _w = Rc::downgrade(&x);
1379 assert!(Rc::get_mut(&mut x).is_none());
1383 fn test_cowrc_clone_make_unique() {
1384 let mut cow0 = Rc::new(75);
1385 let mut cow1 = cow0.clone();
1386 let mut cow2 = cow1.clone();
1388 assert!(75 == *Rc::make_mut(&mut cow0));
1389 assert!(75 == *Rc::make_mut(&mut cow1));
1390 assert!(75 == *Rc::make_mut(&mut cow2));
1392 *Rc::make_mut(&mut cow0) += 1;
1393 *Rc::make_mut(&mut cow1) += 2;
1394 *Rc::make_mut(&mut cow2) += 3;
1396 assert!(76 == *cow0);
1397 assert!(77 == *cow1);
1398 assert!(78 == *cow2);
1400 // none should point to the same backing memory
1401 assert!(*cow0 != *cow1);
1402 assert!(*cow0 != *cow2);
1403 assert!(*cow1 != *cow2);
1407 fn test_cowrc_clone_unique2() {
1408 let mut cow0 = Rc::new(75);
1409 let cow1 = cow0.clone();
1410 let cow2 = cow1.clone();
1412 assert!(75 == *cow0);
1413 assert!(75 == *cow1);
1414 assert!(75 == *cow2);
1416 *Rc::make_mut(&mut cow0) += 1;
1418 assert!(76 == *cow0);
1419 assert!(75 == *cow1);
1420 assert!(75 == *cow2);
1422 // cow1 and cow2 should share the same contents
1423 // cow0 should have a unique reference
1424 assert!(*cow0 != *cow1);
1425 assert!(*cow0 != *cow2);
1426 assert!(*cow1 == *cow2);
1430 fn test_cowrc_clone_weak() {
1431 let mut cow0 = Rc::new(75);
1432 let cow1_weak = Rc::downgrade(&cow0);
1434 assert!(75 == *cow0);
1435 assert!(75 == *cow1_weak.upgrade().unwrap());
1437 *Rc::make_mut(&mut cow0) += 1;
1439 assert!(76 == *cow0);
1440 assert!(cow1_weak.upgrade().is_none());
1445 let foo = Rc::new(75);
1446 assert_eq!(format!("{:?}", foo), "75");
1451 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1452 assert_eq!(foo, foo.clone());
1456 fn test_from_owned() {
1458 let foo_rc = Rc::from(foo);
1459 assert!(123 == *foo_rc);
1463 fn test_new_weak() {
1464 let foo: Weak<usize> = Weak::new();
1465 assert!(foo.upgrade().is_none());
1470 let five = Rc::new(5);
1471 let same_five = five.clone();
1472 let other_five = Rc::new(5);
1474 assert!(Rc::ptr_eq(&five, &same_five));
1475 assert!(!Rc::ptr_eq(&five, &other_five));
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1481 fn borrow(&self) -> &T {
1486 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1487 impl<T: ?Sized> AsRef<T> for Rc<T> {
1488 fn as_ref(&self) -> &T {