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`]
21 //! is no exception: you cannot obtain a mutable reference to
22 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
23 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
24 //! inside an Rc][mutability].
26 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
27 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
28 //! does not implement [`Send`][send]. As a result, the Rust compiler
29 //! will check *at compile time* that you are not sending [`Rc`]s between
30 //! threads. If you need multi-threaded, atomic reference counting, use
31 //! [`sync::Arc`][arc].
33 //! The [`downgrade`][downgrade] method can be used to create a non-owning
34 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
35 //! to an [`Rc`], but this will return [`None`] if the value has
36 //! already been dropped.
38 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
39 //! [`Weak`] is used to break cycles. For example, a tree could have strong
40 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
41 //! children back to their parents.
43 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
44 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
45 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
46 //! functions][assoc], called using function-like syntax:
50 //! let my_rc = Rc::new(());
52 //! Rc::downgrade(&my_rc);
55 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
56 //! already been destroyed.
60 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
61 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
62 //! unique ownership, because more than one gadget may belong to the same
63 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
64 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
71 //! // ...other fields
77 //! // ...other fields
81 //! // Create a reference-counted `Owner`.
82 //! let gadget_owner: Rc<Owner> = Rc::new(
84 //! name: "Gadget Man".to_string(),
88 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
89 //! // value gives us a new pointer to the same `Owner` value, incrementing
90 //! // the reference count in the process.
91 //! let gadget1 = Gadget {
93 //! owner: gadget_owner.clone(),
95 //! let gadget2 = Gadget {
97 //! owner: gadget_owner.clone(),
100 //! // Dispose of our local variable `gadget_owner`.
101 //! drop(gadget_owner);
103 //! // Despite dropping `gadget_owner`, we're still able to print out the name
104 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
105 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
106 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
107 //! // allocated. The field projection `gadget1.owner.name` works because
108 //! // `Rc<Owner>` automatically dereferences to `Owner`.
109 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
110 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
112 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
113 //! // with them the last counted references to our `Owner`. Gadget Man now
114 //! // gets destroyed as well.
118 //! If our requirements change, and we also need to be able to traverse from
119 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
120 //! to `Gadget` introduces a cycle between the values. This means that their
121 //! reference counts can never reach 0, and the values will remain allocated
122 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
125 //! Rust actually makes it somewhat difficult to produce this loop in the first
126 //! place. In order to end up with two values that point at each other, one of
127 //! them needs to be mutable. This is difficult because [`Rc`] enforces
128 //! memory safety by only giving out shared references to the value it wraps,
129 //! and these don't allow direct mutation. We need to wrap the part of the
130 //! value we wish to mutate in a [`RefCell`], which provides *interior
131 //! mutability*: a method to achieve mutability through a shared reference.
132 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
136 //! use std::rc::Weak;
137 //! use std::cell::RefCell;
141 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
142 //! // ...other fields
147 //! owner: Rc<Owner>,
148 //! // ...other fields
152 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
153 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
154 //! // a shared reference.
155 //! let gadget_owner: Rc<Owner> = Rc::new(
157 //! name: "Gadget Man".to_string(),
158 //! gadgets: RefCell::new(vec![]),
162 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
163 //! let gadget1 = Rc::new(
166 //! owner: gadget_owner.clone(),
169 //! let gadget2 = Rc::new(
172 //! owner: gadget_owner.clone(),
176 //! // Add the `Gadget`s to their `Owner`.
178 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
179 //! gadgets.push(Rc::downgrade(&gadget1));
180 //! gadgets.push(Rc::downgrade(&gadget2));
182 //! // `RefCell` dynamic borrow ends here.
185 //! // Iterate over our `Gadget`s, printing their details out.
186 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
188 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
189 //! // guarantee the value is still allocated, we need to call
190 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
192 //! // In this case we know the value still exists, so we simply
193 //! // `unwrap` the `Option`. In a more complicated program, you might
194 //! // need graceful error handling for a `None` result.
196 //! let gadget = gadget_weak.upgrade().unwrap();
197 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
200 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
201 //! // are destroyed. There are now no strong (`Rc`) pointers to the
202 //! // gadgets, so they are destroyed. This zeroes the reference count on
203 //! // Gadget Man, so he gets destroyed as well.
207 //! [`Rc`]: struct.Rc.html
208 //! [`Weak`]: struct.Weak.html
209 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
210 //! [`Cell`]: ../../std/cell/struct.Cell.html
211 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
212 //! [send]: ../../std/marker/trait.Send.html
213 //! [arc]: ../../std/sync/struct.Arc.html
214 //! [`Deref`]: ../../std/ops/trait.Deref.html
215 //! [downgrade]: struct.Rc.html#method.downgrade
216 //! [upgrade]: struct.Weak.html#method.upgrade
217 //! [`None`]: ../../std/option/enum.Option.html#variant.None
218 //! [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
219 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
221 #![stable(feature = "rust1", since = "1.0.0")]
229 use core::cell::Cell;
230 use core::cmp::Ordering;
232 use core::hash::{Hash, Hasher};
233 use core::intrinsics::{abort, assume};
235 use core::marker::Unsize;
236 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
237 use core::ops::Deref;
238 use core::ops::CoerceUnsized;
239 use core::ptr::{self, Shared};
240 use core::convert::From;
242 use heap::deallocate;
245 struct RcBox<T: ?Sized> {
252 /// A single-threaded reference-counting pointer.
254 /// See the [module-level documentation](./index.html) for more details.
256 /// The inherent methods of `Rc` are all associated functions, which means
257 /// that you have to call them as e.g. [`Rc::get_mut(&value)`][get_mut] instead of
258 /// `value.get_mut()`. This avoids conflicts with methods of the inner
261 /// [get_mut]: #method.get_mut
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub struct Rc<T: ?Sized> {
264 ptr: Shared<RcBox<T>>,
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T: ?Sized> !marker::Send for Rc<T> {}
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T: ?Sized> !marker::Sync for Rc<T> {}
272 #[unstable(feature = "coerce_unsized", issue = "27732")]
273 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
276 /// Constructs a new `Rc<T>`.
283 /// let five = Rc::new(5);
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn new(value: T) -> Rc<T> {
289 // there is an implicit weak pointer owned by all the strong
290 // pointers, which ensures that the weak destructor never frees
291 // the allocation while the strong destructor is running, even
292 // if the weak pointer is stored inside the strong one.
293 ptr: Shared::new(Box::into_raw(box RcBox {
294 strong: Cell::new(1),
302 /// Returns the contained value, if the `Rc` has exactly one strong reference.
304 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
307 /// This will succeed even if there are outstanding weak references.
309 /// [result]: ../../std/result/enum.Result.html
316 /// let x = Rc::new(3);
317 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
319 /// let x = Rc::new(4);
320 /// let _y = x.clone();
321 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
324 #[stable(feature = "rc_unique", since = "1.4.0")]
325 pub fn try_unwrap(this: Self) -> Result<T, Self> {
326 if Rc::strong_count(&this) == 1 {
328 let val = ptr::read(&*this); // copy the contained object
330 // Indicate to Weaks that they can't be promoted by decrememting
331 // the strong count, and then remove the implicit "strong weak"
332 // pointer while also handling drop logic by just crafting a
335 let _weak = Weak { ptr: this.ptr };
344 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
347 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
348 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
349 #[unstable(feature = "rc_would_unwrap",
350 reason = "just added for niche usecase",
352 #[rustc_deprecated(since = "1.15.0", reason = "too niche; use `strong_count` instead")]
353 pub fn would_unwrap(this: &Self) -> bool {
354 Rc::strong_count(&this) == 1
357 /// Consumes the `Rc`, returning the wrapped pointer.
359 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
360 /// [`Rc::from_raw`][from_raw].
362 /// [from_raw]: struct.Rc.html#method.from_raw
369 /// let x = Rc::new(10);
370 /// let x_ptr = Rc::into_raw(x);
371 /// assert_eq!(unsafe { *x_ptr }, 10);
373 #[stable(feature = "rc_raw", since = "1.17.0")]
374 pub fn into_raw(this: Self) -> *const T {
375 let ptr = unsafe { &mut (*this.ptr.as_mut_ptr()).value as *const _ };
380 /// Constructs an `Rc` from a raw pointer.
382 /// The raw pointer must have been previously returned by a call to a
383 /// [`Rc::into_raw`][into_raw].
385 /// This function is unsafe because improper use may lead to memory problems. For example, a
386 /// double-free may occur if the function is called twice on the same raw pointer.
388 /// [into_raw]: struct.Rc.html#method.into_raw
395 /// let x = Rc::new(10);
396 /// let x_ptr = Rc::into_raw(x);
399 /// // Convert back to an `Rc` to prevent leak.
400 /// let x = Rc::from_raw(x_ptr);
401 /// assert_eq!(*x, 10);
403 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
406 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
408 #[stable(feature = "rc_raw", since = "1.17.0")]
409 pub unsafe fn from_raw(ptr: *const T) -> Self {
410 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
411 // `value` field from the pointer.
412 Rc { ptr: Shared::new((ptr as *const u8).offset(-offset_of!(RcBox<T>, value)) as *const _) }
417 /// Constructs a new `Rc<str>` from a string slice.
419 #[unstable(feature = "rustc_private",
420 reason = "for internal use in rustc",
422 pub fn __from_str(value: &str) -> Rc<str> {
424 // Allocate enough space for `RcBox<str>`.
425 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
426 let vec = RawVec::<usize>::with_capacity(aligned_len);
429 // Initialize fields of `RcBox<str>`.
430 *ptr.offset(0) = 1; // strong: Cell::new(1)
431 *ptr.offset(1) = 1; // weak: Cell::new(1)
432 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
433 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
434 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
435 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
436 Rc { ptr: Shared::new(rcbox_ptr) }
441 impl<T: ?Sized> Rc<T> {
442 /// Creates a new [`Weak`][weak] pointer to this value.
444 /// [weak]: struct.Weak.html
451 /// let five = Rc::new(5);
453 /// let weak_five = Rc::downgrade(&five);
455 #[stable(feature = "rc_weak", since = "1.4.0")]
456 pub fn downgrade(this: &Self) -> Weak<T> {
458 Weak { ptr: this.ptr }
461 /// Gets the number of [`Weak`][weak] pointers to this value.
463 /// [weak]: struct.Weak.html
470 /// let five = Rc::new(5);
471 /// let _weak_five = Rc::downgrade(&five);
473 /// assert_eq!(1, Rc::weak_count(&five));
476 #[stable(feature = "rc_counts", since = "1.15.0")]
477 pub fn weak_count(this: &Self) -> usize {
481 /// Gets the number of strong (`Rc`) pointers to this value.
488 /// let five = Rc::new(5);
489 /// let _also_five = five.clone();
491 /// assert_eq!(2, Rc::strong_count(&five));
494 #[stable(feature = "rc_counts", since = "1.15.0")]
495 pub fn strong_count(this: &Self) -> usize {
499 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
500 /// this inner value.
502 /// [weak]: struct.Weak.html
504 #[unstable(feature = "is_unique", reason = "uniqueness has unclear meaning",
506 #[rustc_deprecated(since = "1.15.0",
507 reason = "too niche; use `strong_count` and `weak_count` instead")]
508 pub fn is_unique(this: &Self) -> bool {
509 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
512 /// Returns a mutable reference to the inner value, if there are
513 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
515 /// Returns [`None`] otherwise, because it is not safe to
516 /// mutate a shared value.
518 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
519 /// the inner value when it's shared.
521 /// [weak]: struct.Weak.html
522 /// [`None`]: ../../std/option/enum.Option.html#variant.None
523 /// [make_mut]: struct.Rc.html#method.make_mut
524 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
531 /// let mut x = Rc::new(3);
532 /// *Rc::get_mut(&mut x).unwrap() = 4;
533 /// assert_eq!(*x, 4);
535 /// let _y = x.clone();
536 /// assert!(Rc::get_mut(&mut x).is_none());
539 #[stable(feature = "rc_unique", since = "1.4.0")]
540 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
541 if Rc::is_unique(this) {
542 let inner = unsafe { &mut *this.ptr.as_mut_ptr() };
543 Some(&mut inner.value)
550 #[stable(feature = "ptr_eq", since = "1.17.0")]
551 /// Returns true if the two `Rc`s point to the same value (not
552 /// just values that compare as equal).
559 /// let five = Rc::new(5);
560 /// let same_five = five.clone();
561 /// let other_five = Rc::new(5);
563 /// assert!(Rc::ptr_eq(&five, &same_five));
564 /// assert!(!Rc::ptr_eq(&five, &other_five));
566 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
567 let this_ptr: *const RcBox<T> = *this.ptr;
568 let other_ptr: *const RcBox<T> = *other.ptr;
569 this_ptr == other_ptr
573 impl<T: Clone> Rc<T> {
574 /// Makes a mutable reference into the given `Rc`.
576 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
577 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
578 /// ensure unique ownership. This is also referred to as clone-on-write.
580 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
582 /// [weak]: struct.Weak.html
583 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
584 /// [get_mut]: struct.Rc.html#method.get_mut
591 /// let mut data = Rc::new(5);
593 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
594 /// let mut other_data = data.clone(); // Won't clone inner data
595 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
596 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
597 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
599 /// // Now `data` and `other_data` point to different values.
600 /// assert_eq!(*data, 8);
601 /// assert_eq!(*other_data, 12);
604 #[stable(feature = "rc_unique", since = "1.4.0")]
605 pub fn make_mut(this: &mut Self) -> &mut T {
606 if Rc::strong_count(this) != 1 {
607 // Gotta clone the data, there are other Rcs
608 *this = Rc::new((**this).clone())
609 } else if Rc::weak_count(this) != 0 {
610 // Can just steal the data, all that's left is Weaks
612 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
613 mem::swap(this, &mut swap);
615 // Remove implicit strong-weak ref (no need to craft a fake
616 // Weak here -- we know other Weaks can clean up for us)
621 // This unsafety is ok because we're guaranteed that the pointer
622 // returned is the *only* pointer that will ever be returned to T. Our
623 // reference count is guaranteed to be 1 at this point, and we required
624 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
625 // reference to the inner value.
626 let inner = unsafe { &mut *this.ptr.as_mut_ptr() };
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<T: ?Sized> Deref for Rc<T> {
636 fn deref(&self) -> &T {
641 #[stable(feature = "rust1", since = "1.0.0")]
642 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
645 /// This will decrement the strong reference count. If the strong reference
646 /// count reaches zero then the only other references (if any) are
647 /// [`Weak`][weak], so we `drop` the inner value.
649 /// [weak]: struct.Weak.html
658 /// impl Drop for Foo {
659 /// fn drop(&mut self) {
660 /// println!("dropped!");
664 /// let foo = Rc::new(Foo);
665 /// let foo2 = foo.clone();
667 /// drop(foo); // Doesn't print anything
668 /// drop(foo2); // Prints "dropped!"
672 let ptr = self.ptr.as_mut_ptr();
675 if self.strong() == 0 {
676 // destroy the contained object
677 ptr::drop_in_place(&mut (*ptr).value);
679 // remove the implicit "strong weak" pointer now that we've
680 // destroyed the contents.
683 if self.weak() == 0 {
684 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T: ?Sized> Clone for Rc<T> {
693 /// Makes a clone of the `Rc` pointer.
695 /// This creates another pointer to the same inner value, increasing the
696 /// strong reference count.
703 /// let five = Rc::new(5);
708 fn clone(&self) -> Rc<T> {
714 #[stable(feature = "rust1", since = "1.0.0")]
715 impl<T: Default> Default for Rc<T> {
716 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
723 /// let x: Rc<i32> = Default::default();
724 /// assert_eq!(*x, 0);
727 fn default() -> Rc<T> {
728 Rc::new(Default::default())
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
734 /// Equality for two `Rc`s.
736 /// Two `Rc`s are equal if their inner values are equal.
743 /// let five = Rc::new(5);
745 /// assert!(five == Rc::new(5));
748 fn eq(&self, other: &Rc<T>) -> bool {
752 /// Inequality for two `Rc`s.
754 /// Two `Rc`s are unequal if their inner values are unequal.
761 /// let five = Rc::new(5);
763 /// assert!(five != Rc::new(6));
766 fn ne(&self, other: &Rc<T>) -> bool {
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<T: ?Sized + Eq> Eq for Rc<T> {}
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
776 /// Partial comparison for two `Rc`s.
778 /// The two are compared by calling `partial_cmp()` on their inner values.
784 /// use std::cmp::Ordering;
786 /// let five = Rc::new(5);
788 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
791 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
792 (**self).partial_cmp(&**other)
795 /// Less-than comparison for two `Rc`s.
797 /// The two are compared by calling `<` on their inner values.
804 /// let five = Rc::new(5);
806 /// assert!(five < Rc::new(6));
809 fn lt(&self, other: &Rc<T>) -> bool {
813 /// 'Less than or equal to' comparison for two `Rc`s.
815 /// The two are compared by calling `<=` on their inner values.
822 /// let five = Rc::new(5);
824 /// assert!(five <= Rc::new(5));
827 fn le(&self, other: &Rc<T>) -> bool {
831 /// Greater-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(4));
845 fn gt(&self, other: &Rc<T>) -> bool {
849 /// 'Greater 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 ge(&self, other: &Rc<T>) -> bool {
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<T: ?Sized + Ord> Ord for Rc<T> {
870 /// Comparison for two `Rc`s.
872 /// The two are compared by calling `cmp()` on their inner values.
878 /// use std::cmp::Ordering;
880 /// let five = Rc::new(5);
882 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
885 fn cmp(&self, other: &Rc<T>) -> Ordering {
886 (**self).cmp(&**other)
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<T: ?Sized + Hash> Hash for Rc<T> {
892 fn hash<H: Hasher>(&self, state: &mut H) {
893 (**self).hash(state);
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
899 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
900 fmt::Display::fmt(&**self, f)
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
906 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
907 fmt::Debug::fmt(&**self, f)
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<T: ?Sized> fmt::Pointer for Rc<T> {
913 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
914 fmt::Pointer::fmt(&*self.ptr, f)
918 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
919 impl<T> From<T> for Rc<T> {
920 fn from(t: T) -> Self {
925 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
926 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
927 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
929 /// Since a `Weak` reference does not count towards ownership, it will not
930 /// prevent the inner value from being dropped, and `Weak` itself makes no
931 /// guarantees about the value still being present and may return [`None`]
932 /// when [`upgrade`]d.
934 /// A `Weak` pointer is useful for keeping a temporary reference to the value
935 /// within [`Rc`] without extending its lifetime. It is also used to prevent
936 /// circular references between [`Rc`] pointers, since mutual owning references
937 /// would never allow either [`Arc`] to be dropped. For example, a tree could
938 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
939 /// pointers from children back to their parents.
941 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
943 /// [`Rc`]: struct.Rc.html
944 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
945 /// [`upgrade`]: struct.Weak.html#method.upgrade
946 /// [`Option`]: ../../std/option/enum.Option.html
947 /// [`None`]: ../../std/option/enum.Option.html#variant.None
948 #[stable(feature = "rc_weak", since = "1.4.0")]
949 pub struct Weak<T: ?Sized> {
950 ptr: Shared<RcBox<T>>,
953 #[stable(feature = "rc_weak", since = "1.4.0")]
954 impl<T: ?Sized> !marker::Send for Weak<T> {}
955 #[stable(feature = "rc_weak", since = "1.4.0")]
956 impl<T: ?Sized> !marker::Sync for Weak<T> {}
958 #[unstable(feature = "coerce_unsized", issue = "27732")]
959 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
962 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
963 /// it. Calling [`upgrade`] on the return value always gives [`None`].
965 /// [`upgrade`]: struct.Weak.html#method.upgrade
966 /// [`None`]: ../../std/option/enum.Option.html
971 /// use std::rc::Weak;
973 /// let empty: Weak<i64> = Weak::new();
974 /// assert!(empty.upgrade().is_none());
976 #[stable(feature = "downgraded_weak", since = "1.10.0")]
977 pub fn new() -> Weak<T> {
980 ptr: Shared::new(Box::into_raw(box RcBox {
981 strong: Cell::new(0),
983 value: uninitialized(),
990 impl<T: ?Sized> Weak<T> {
991 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
992 /// the lifetime of the value if successful.
994 /// Returns [`None`] if the value has since been dropped.
996 /// [`Rc`]: struct.Rc.html
997 /// [`None`]: ../../std/option/enum.Option.html
1002 /// use std::rc::Rc;
1004 /// let five = Rc::new(5);
1006 /// let weak_five = Rc::downgrade(&five);
1008 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1009 /// assert!(strong_five.is_some());
1011 /// // Destroy all strong pointers.
1012 /// drop(strong_five);
1015 /// assert!(weak_five.upgrade().is_none());
1017 #[stable(feature = "rc_weak", since = "1.4.0")]
1018 pub fn upgrade(&self) -> Option<Rc<T>> {
1019 if self.strong() == 0 {
1023 Some(Rc { ptr: self.ptr })
1028 #[stable(feature = "rc_weak", since = "1.4.0")]
1029 impl<T: ?Sized> Drop for Weak<T> {
1030 /// Drops the `Weak` pointer.
1035 /// use std::rc::Rc;
1039 /// impl Drop for Foo {
1040 /// fn drop(&mut self) {
1041 /// println!("dropped!");
1045 /// let foo = Rc::new(Foo);
1046 /// let weak_foo = Rc::downgrade(&foo);
1047 /// let other_weak_foo = weak_foo.clone();
1049 /// drop(weak_foo); // Doesn't print anything
1050 /// drop(foo); // Prints "dropped!"
1052 /// assert!(other_weak_foo.upgrade().is_none());
1054 fn drop(&mut self) {
1056 let ptr = *self.ptr;
1059 // the weak count starts at 1, and will only go to zero if all
1060 // the strong pointers have disappeared.
1061 if self.weak() == 0 {
1062 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1068 #[stable(feature = "rc_weak", since = "1.4.0")]
1069 impl<T: ?Sized> Clone for Weak<T> {
1070 /// Makes a clone of the `Weak` pointer that points to the same value.
1075 /// use std::rc::Rc;
1077 /// let weak_five = Rc::downgrade(&Rc::new(5));
1079 /// weak_five.clone();
1082 fn clone(&self) -> Weak<T> {
1084 Weak { ptr: self.ptr }
1088 #[stable(feature = "rc_weak", since = "1.4.0")]
1089 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1090 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1095 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1096 impl<T> Default for Weak<T> {
1097 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1098 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1100 /// [`upgrade`]: struct.Weak.html#method.upgrade
1101 /// [`None`]: ../../std/option/enum.Option.html
1106 /// use std::rc::Weak;
1108 /// let empty: Weak<i64> = Default::default();
1109 /// assert!(empty.upgrade().is_none());
1111 fn default() -> Weak<T> {
1116 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1117 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1118 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1119 // We abort because this is such a degenerate scenario that we don't care about
1120 // what happens -- no real program should ever experience this.
1122 // This should have negligible overhead since you don't actually need to
1123 // clone these much in Rust thanks to ownership and move-semantics.
1126 trait RcBoxPtr<T: ?Sized> {
1127 fn inner(&self) -> &RcBox<T>;
1130 fn strong(&self) -> usize {
1131 self.inner().strong.get()
1135 fn inc_strong(&self) {
1136 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1140 fn dec_strong(&self) {
1141 self.inner().strong.set(self.strong() - 1);
1145 fn weak(&self) -> usize {
1146 self.inner().weak.get()
1150 fn inc_weak(&self) {
1151 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1155 fn dec_weak(&self) {
1156 self.inner().weak.set(self.weak() - 1);
1160 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1162 fn inner(&self) -> &RcBox<T> {
1164 // Safe to assume this here, as if it weren't true, we'd be breaking
1165 // the contract anyway.
1166 // This allows the null check to be elided in the destructor if we
1167 // manipulated the reference count in the same function.
1168 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1174 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1176 fn inner(&self) -> &RcBox<T> {
1178 // Safe to assume this here, as if it weren't true, we'd be breaking
1179 // the contract anyway.
1180 // This allows the null check to be elided in the destructor if we
1181 // manipulated the reference count in the same function.
1182 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1190 use super::{Rc, Weak};
1191 use std::boxed::Box;
1192 use std::cell::RefCell;
1193 use std::option::Option;
1194 use std::option::Option::{None, Some};
1195 use std::result::Result::{Err, Ok};
1197 use std::clone::Clone;
1198 use std::convert::From;
1202 let x = Rc::new(RefCell::new(5));
1204 *x.borrow_mut() = 20;
1205 assert_eq!(*y.borrow(), 20);
1215 fn test_simple_clone() {
1223 fn test_destructor() {
1224 let x: Rc<Box<_>> = Rc::new(box 5);
1231 let y = Rc::downgrade(&x);
1232 assert!(y.upgrade().is_some());
1238 let y = Rc::downgrade(&x);
1240 assert!(y.upgrade().is_none());
1244 fn weak_self_cyclic() {
1246 x: RefCell<Option<Weak<Cycle>>>,
1249 let a = Rc::new(Cycle { x: RefCell::new(None) });
1250 let b = Rc::downgrade(&a.clone());
1251 *a.x.borrow_mut() = Some(b);
1253 // hopefully we don't double-free (or leak)...
1259 assert!(Rc::is_unique(&x));
1261 assert!(!Rc::is_unique(&x));
1263 assert!(Rc::is_unique(&x));
1264 let w = Rc::downgrade(&x);
1265 assert!(!Rc::is_unique(&x));
1267 assert!(Rc::is_unique(&x));
1271 fn test_strong_count() {
1273 assert!(Rc::strong_count(&a) == 1);
1274 let w = Rc::downgrade(&a);
1275 assert!(Rc::strong_count(&a) == 1);
1276 let b = w.upgrade().expect("upgrade of live rc failed");
1277 assert!(Rc::strong_count(&b) == 2);
1278 assert!(Rc::strong_count(&a) == 2);
1281 assert!(Rc::strong_count(&b) == 1);
1283 assert!(Rc::strong_count(&b) == 2);
1284 assert!(Rc::strong_count(&c) == 2);
1288 fn test_weak_count() {
1290 assert!(Rc::strong_count(&a) == 1);
1291 assert!(Rc::weak_count(&a) == 0);
1292 let w = Rc::downgrade(&a);
1293 assert!(Rc::strong_count(&a) == 1);
1294 assert!(Rc::weak_count(&a) == 1);
1296 assert!(Rc::strong_count(&a) == 1);
1297 assert!(Rc::weak_count(&a) == 0);
1299 assert!(Rc::strong_count(&a) == 2);
1300 assert!(Rc::weak_count(&a) == 0);
1307 assert_eq!(Rc::try_unwrap(x), Ok(3));
1310 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1312 let _w = Rc::downgrade(&x);
1313 assert_eq!(Rc::try_unwrap(x), Ok(5));
1317 fn into_from_raw() {
1318 let x = Rc::new(box "hello");
1321 let x_ptr = Rc::into_raw(x);
1324 assert_eq!(**x_ptr, "hello");
1326 let x = Rc::from_raw(x_ptr);
1327 assert_eq!(**x, "hello");
1329 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1335 let mut x = Rc::new(3);
1336 *Rc::get_mut(&mut x).unwrap() = 4;
1339 assert!(Rc::get_mut(&mut x).is_none());
1341 assert!(Rc::get_mut(&mut x).is_some());
1342 let _w = Rc::downgrade(&x);
1343 assert!(Rc::get_mut(&mut x).is_none());
1347 fn test_cowrc_clone_make_unique() {
1348 let mut cow0 = Rc::new(75);
1349 let mut cow1 = cow0.clone();
1350 let mut cow2 = cow1.clone();
1352 assert!(75 == *Rc::make_mut(&mut cow0));
1353 assert!(75 == *Rc::make_mut(&mut cow1));
1354 assert!(75 == *Rc::make_mut(&mut cow2));
1356 *Rc::make_mut(&mut cow0) += 1;
1357 *Rc::make_mut(&mut cow1) += 2;
1358 *Rc::make_mut(&mut cow2) += 3;
1360 assert!(76 == *cow0);
1361 assert!(77 == *cow1);
1362 assert!(78 == *cow2);
1364 // none should point to the same backing memory
1365 assert!(*cow0 != *cow1);
1366 assert!(*cow0 != *cow2);
1367 assert!(*cow1 != *cow2);
1371 fn test_cowrc_clone_unique2() {
1372 let mut cow0 = Rc::new(75);
1373 let cow1 = cow0.clone();
1374 let cow2 = cow1.clone();
1376 assert!(75 == *cow0);
1377 assert!(75 == *cow1);
1378 assert!(75 == *cow2);
1380 *Rc::make_mut(&mut cow0) += 1;
1382 assert!(76 == *cow0);
1383 assert!(75 == *cow1);
1384 assert!(75 == *cow2);
1386 // cow1 and cow2 should share the same contents
1387 // cow0 should have a unique reference
1388 assert!(*cow0 != *cow1);
1389 assert!(*cow0 != *cow2);
1390 assert!(*cow1 == *cow2);
1394 fn test_cowrc_clone_weak() {
1395 let mut cow0 = Rc::new(75);
1396 let cow1_weak = Rc::downgrade(&cow0);
1398 assert!(75 == *cow0);
1399 assert!(75 == *cow1_weak.upgrade().unwrap());
1401 *Rc::make_mut(&mut cow0) += 1;
1403 assert!(76 == *cow0);
1404 assert!(cow1_weak.upgrade().is_none());
1409 let foo = Rc::new(75);
1410 assert_eq!(format!("{:?}", foo), "75");
1415 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1416 assert_eq!(foo, foo.clone());
1420 fn test_from_owned() {
1422 let foo_rc = Rc::from(foo);
1423 assert!(123 == *foo_rc);
1427 fn test_new_weak() {
1428 let foo: Weak<usize> = Weak::new();
1429 assert!(foo.upgrade().is_none());
1434 let five = Rc::new(5);
1435 let same_five = five.clone();
1436 let other_five = Rc::new(5);
1438 assert!(Rc::ptr_eq(&five, &same_five));
1439 assert!(!Rc::ptr_eq(&five, &other_five));
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1445 fn borrow(&self) -> &T {
1450 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1451 impl<T: ?Sized> AsRef<T> for Rc<T> {
1452 fn as_ref(&self) -> &T {