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. 'Rc' stands for 'Reference
16 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
17 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
18 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
19 //! given value is destroyed, the pointed-to value is also destroyed.
21 //! Shared references in Rust disallow mutation by default, and [`Rc`]
22 //! is no exception: you cannot obtain a mutable reference to
23 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
24 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
25 //! inside an Rc][mutability].
27 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
28 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
29 //! does not implement [`Send`][send]. As a result, the Rust compiler
30 //! will check *at compile time* that you are not sending [`Rc`]s between
31 //! threads. If you need multi-threaded, atomic reference counting, use
32 //! [`sync::Arc`][arc].
34 //! The [`downgrade`][downgrade] method can be used to create a non-owning
35 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
36 //! to an [`Rc`], but this will return [`None`] if the value has
37 //! already been dropped.
39 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
40 //! [`Weak`] is used to break cycles. For example, a tree could have strong
41 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
42 //! children back to their parents.
44 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
45 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
46 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
47 //! functions][assoc], called using function-like syntax:
51 //! let my_rc = Rc::new(());
53 //! Rc::downgrade(&my_rc);
56 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
57 //! already been destroyed.
59 //! # Cloning references
61 //! Creating a new reference from an existing reference counted pointer is done using the
62 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
66 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
67 //! // The two syntaxes below are equivalent.
68 //! let a = foo.clone();
69 //! let b = Rc::clone(&foo);
70 //! // a and b both point to the same memory location as foo.
73 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
74 //! the meaning of the code. In the example above, this syntax makes it easier to see that
75 //! this code is creating a new reference rather than copying the whole content of foo.
79 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
80 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
81 //! unique ownership, because more than one gadget may belong to the same
82 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
83 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
90 //! // ...other fields
96 //! // ...other fields
100 //! // Create a reference-counted `Owner`.
101 //! let gadget_owner: Rc<Owner> = Rc::new(
103 //! name: "Gadget Man".to_string(),
107 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
108 //! // value gives us a new pointer to the same `Owner` value, incrementing
109 //! // the reference count in the process.
110 //! let gadget1 = Gadget {
112 //! owner: Rc::clone(&gadget_owner),
114 //! let gadget2 = Gadget {
116 //! owner: Rc::clone(&gadget_owner),
119 //! // Dispose of our local variable `gadget_owner`.
120 //! drop(gadget_owner);
122 //! // Despite dropping `gadget_owner`, we're still able to print out the name
123 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
124 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
125 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
126 //! // allocated. The field projection `gadget1.owner.name` works because
127 //! // `Rc<Owner>` automatically dereferences to `Owner`.
128 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
129 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
131 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
132 //! // with them the last counted references to our `Owner`. Gadget Man now
133 //! // gets destroyed as well.
137 //! If our requirements change, and we also need to be able to traverse from
138 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
139 //! to `Gadget` introduces a cycle between the values. This means that their
140 //! reference counts can never reach 0, and the values will remain allocated
141 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
144 //! Rust actually makes it somewhat difficult to produce this loop in the first
145 //! place. In order to end up with two values that point at each other, one of
146 //! them needs to be mutable. This is difficult because [`Rc`] enforces
147 //! memory safety by only giving out shared references to the value it wraps,
148 //! and these don't allow direct mutation. We need to wrap the part of the
149 //! value we wish to mutate in a [`RefCell`], which provides *interior
150 //! mutability*: a method to achieve mutability through a shared reference.
151 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
155 //! use std::rc::Weak;
156 //! use std::cell::RefCell;
160 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
161 //! // ...other fields
166 //! owner: Rc<Owner>,
167 //! // ...other fields
171 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
172 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
173 //! // a shared reference.
174 //! let gadget_owner: Rc<Owner> = Rc::new(
176 //! name: "Gadget Man".to_string(),
177 //! gadgets: RefCell::new(vec![]),
181 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
182 //! let gadget1 = Rc::new(
185 //! owner: Rc::clone(&gadget_owner),
188 //! let gadget2 = Rc::new(
191 //! owner: Rc::clone(&gadget_owner),
195 //! // Add the `Gadget`s to their `Owner`.
197 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
198 //! gadgets.push(Rc::downgrade(&gadget1));
199 //! gadgets.push(Rc::downgrade(&gadget2));
201 //! // `RefCell` dynamic borrow ends here.
204 //! // Iterate over our `Gadget`s, printing their details out.
205 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
207 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
208 //! // guarantee the value is still allocated, we need to call
209 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
211 //! // In this case we know the value still exists, so we simply
212 //! // `unwrap` the `Option`. In a more complicated program, you might
213 //! // need graceful error handling for a `None` result.
215 //! let gadget = gadget_weak.upgrade().unwrap();
216 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
219 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
220 //! // are destroyed. There are now no strong (`Rc`) pointers to the
221 //! // gadgets, so they are destroyed. This zeroes the reference count on
222 //! // Gadget Man, so he gets destroyed as well.
226 //! [`Rc`]: struct.Rc.html
227 //! [`Weak`]: struct.Weak.html
228 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
229 //! [`Cell`]: ../../std/cell/struct.Cell.html
230 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
231 //! [send]: ../../std/marker/trait.Send.html
232 //! [arc]: ../../std/sync/struct.Arc.html
233 //! [`Deref`]: ../../std/ops/trait.Deref.html
234 //! [downgrade]: struct.Rc.html#method.downgrade
235 //! [upgrade]: struct.Weak.html#method.upgrade
236 //! [`None`]: ../../std/option/enum.Option.html#variant.None
237 //! [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
238 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
240 #![stable(feature = "rust1", since = "1.0.0")]
248 use core::cell::Cell;
249 use core::cmp::Ordering;
251 use core::hash::{Hash, Hasher};
252 use core::intrinsics::abort;
254 use core::marker::Unsize;
255 use core::mem::{self, forget, size_of, size_of_val, uninitialized};
256 use core::ops::Deref;
257 use core::ops::CoerceUnsized;
258 use core::ptr::{self, Shared};
259 use core::convert::From;
261 use heap::{Heap, Alloc, Layout, box_free};
264 struct RcBox<T: ?Sized> {
270 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
273 /// See the [module-level documentation](./index.html) for more details.
275 /// The inherent methods of `Rc` are all associated functions, which means
276 /// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
277 /// `value.get_mut()`. This avoids conflicts with methods of the inner
280 /// [get_mut]: #method.get_mut
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub struct Rc<T: ?Sized> {
283 ptr: Shared<RcBox<T>>,
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T: ?Sized> !marker::Send for Rc<T> {}
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T: ?Sized> !marker::Sync for Rc<T> {}
291 #[unstable(feature = "coerce_unsized", issue = "27732")]
292 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
295 /// Constructs a new `Rc<T>`.
302 /// let five = Rc::new(5);
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub fn new(value: T) -> Rc<T> {
308 // there is an implicit weak pointer owned by all the strong
309 // pointers, which ensures that the weak destructor never frees
310 // the allocation while the strong destructor is running, even
311 // if the weak pointer is stored inside the strong one.
312 ptr: Shared::new(Box::into_raw(box RcBox {
313 strong: Cell::new(1),
321 /// Returns the contained value, if the `Rc` has exactly one strong reference.
323 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
326 /// This will succeed even if there are outstanding weak references.
328 /// [result]: ../../std/result/enum.Result.html
335 /// let x = Rc::new(3);
336 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
338 /// let x = Rc::new(4);
339 /// let _y = Rc::clone(&x);
340 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
343 #[stable(feature = "rc_unique", since = "1.4.0")]
344 pub fn try_unwrap(this: Self) -> Result<T, Self> {
345 if Rc::strong_count(&this) == 1 {
347 let val = ptr::read(&*this); // copy the contained object
349 // Indicate to Weaks that they can't be promoted by decrememting
350 // the strong count, and then remove the implicit "strong weak"
351 // pointer while also handling drop logic by just crafting a
354 let _weak = Weak { ptr: this.ptr };
363 /// Consumes the `Rc`, returning the wrapped pointer.
365 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
366 /// [`Rc::from_raw`][from_raw].
368 /// [from_raw]: struct.Rc.html#method.from_raw
375 /// let x = Rc::new(10);
376 /// let x_ptr = Rc::into_raw(x);
377 /// assert_eq!(unsafe { *x_ptr }, 10);
379 #[stable(feature = "rc_raw", since = "1.17.0")]
380 pub fn into_raw(this: Self) -> *const T {
381 let ptr: *const T = &*this;
386 /// Constructs an `Rc` from a raw pointer.
388 /// The raw pointer must have been previously returned by a call to a
389 /// [`Rc::into_raw`][into_raw].
391 /// This function is unsafe because improper use may lead to memory problems. For example, a
392 /// double-free may occur if the function is called twice on the same raw pointer.
394 /// [into_raw]: struct.Rc.html#method.into_raw
401 /// let x = Rc::new(10);
402 /// let x_ptr = Rc::into_raw(x);
405 /// // Convert back to an `Rc` to prevent leak.
406 /// let x = Rc::from_raw(x_ptr);
407 /// assert_eq!(*x, 10);
409 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
412 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
414 #[stable(feature = "rc_raw", since = "1.17.0")]
415 pub unsafe fn from_raw(ptr: *const T) -> Self {
416 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
417 // `value` field from the pointer.
419 let ptr = (ptr as *const u8).offset(-offset_of!(RcBox<T>, value));
421 ptr: Shared::new(ptr as *mut u8 as *mut _)
427 /// Constructs a new `Rc<str>` from a string slice.
429 #[unstable(feature = "rustc_private",
430 reason = "for internal use in rustc",
432 pub fn __from_str(value: &str) -> Rc<str> {
434 // Allocate enough space for `RcBox<str>`.
435 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
436 let vec = RawVec::<usize>::with_capacity(aligned_len);
439 // Initialize fields of `RcBox<str>`.
440 *ptr.offset(0) = 1; // strong: Cell::new(1)
441 *ptr.offset(1) = 1; // weak: Cell::new(1)
442 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
443 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
444 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
445 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
446 Rc { ptr: Shared::new(rcbox_ptr) }
452 /// Constructs a new `Rc<[T]>` from a `Box<[T]>`.
454 #[unstable(feature = "rustc_private",
455 reason = "for internal use in rustc",
457 pub fn __from_array(value: Box<[T]>) -> Rc<[T]> {
459 let ptr: *mut RcBox<[T]> =
460 mem::transmute([mem::align_of::<RcBox<[T; 1]>>(), value.len()]);
461 // FIXME(custom-DST): creating this invalid &[T] is dubiously defined,
462 // we should have a better way of getting the size/align
463 // of a DST from its unsized part.
464 let ptr = Heap.alloc(Layout::for_value(&*ptr))
465 .unwrap_or_else(|e| Heap.oom(e));
466 let ptr: *mut RcBox<[T]> = mem::transmute([ptr as usize, value.len()]);
468 // Initialize the new RcBox.
469 ptr::write(&mut (*ptr).strong, Cell::new(1));
470 ptr::write(&mut (*ptr).weak, Cell::new(1));
471 ptr::copy_nonoverlapping(
473 &mut (*ptr).value as *mut [T] as *mut T,
476 // Free the original allocation without freeing its (moved) contents.
477 box_free(Box::into_raw(value));
479 Rc { ptr: Shared::new(ptr as *mut _) }
484 impl<T: ?Sized> Rc<T> {
485 /// Creates a new [`Weak`][weak] pointer to this value.
487 /// [weak]: struct.Weak.html
494 /// let five = Rc::new(5);
496 /// let weak_five = Rc::downgrade(&five);
498 #[stable(feature = "rc_weak", since = "1.4.0")]
499 pub fn downgrade(this: &Self) -> Weak<T> {
501 Weak { ptr: this.ptr }
504 /// Gets the number of [`Weak`][weak] pointers to this value.
506 /// [weak]: struct.Weak.html
513 /// let five = Rc::new(5);
514 /// let _weak_five = Rc::downgrade(&five);
516 /// assert_eq!(1, Rc::weak_count(&five));
519 #[stable(feature = "rc_counts", since = "1.15.0")]
520 pub fn weak_count(this: &Self) -> usize {
524 /// Gets the number of strong (`Rc`) pointers to this value.
531 /// let five = Rc::new(5);
532 /// let _also_five = Rc::clone(&five);
534 /// assert_eq!(2, Rc::strong_count(&five));
537 #[stable(feature = "rc_counts", since = "1.15.0")]
538 pub fn strong_count(this: &Self) -> usize {
542 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
543 /// this inner value.
545 /// [weak]: struct.Weak.html
547 fn is_unique(this: &Self) -> bool {
548 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
551 /// Returns a mutable reference to the inner value, if there are
552 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
554 /// Returns [`None`] otherwise, because it is not safe to
555 /// mutate a shared value.
557 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
558 /// the inner value when it's shared.
560 /// [weak]: struct.Weak.html
561 /// [`None`]: ../../std/option/enum.Option.html#variant.None
562 /// [make_mut]: struct.Rc.html#method.make_mut
563 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
570 /// let mut x = Rc::new(3);
571 /// *Rc::get_mut(&mut x).unwrap() = 4;
572 /// assert_eq!(*x, 4);
574 /// let _y = Rc::clone(&x);
575 /// assert!(Rc::get_mut(&mut x).is_none());
578 #[stable(feature = "rc_unique", since = "1.4.0")]
579 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
580 if Rc::is_unique(this) {
582 Some(&mut this.ptr.as_mut().value)
590 #[stable(feature = "ptr_eq", since = "1.17.0")]
591 /// Returns true if the two `Rc`s point to the same value (not
592 /// just values that compare as equal).
599 /// let five = Rc::new(5);
600 /// let same_five = Rc::clone(&five);
601 /// let other_five = Rc::new(5);
603 /// assert!(Rc::ptr_eq(&five, &same_five));
604 /// assert!(!Rc::ptr_eq(&five, &other_five));
606 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
607 this.ptr.as_ptr() == other.ptr.as_ptr()
611 impl<T: Clone> Rc<T> {
612 /// Makes a mutable reference into the given `Rc`.
614 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
615 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
616 /// ensure unique ownership. This is also referred to as clone-on-write.
618 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
620 /// [weak]: struct.Weak.html
621 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
622 /// [get_mut]: struct.Rc.html#method.get_mut
629 /// let mut data = Rc::new(5);
631 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
632 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
633 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
634 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
635 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
637 /// // Now `data` and `other_data` point to different values.
638 /// assert_eq!(*data, 8);
639 /// assert_eq!(*other_data, 12);
642 #[stable(feature = "rc_unique", since = "1.4.0")]
643 pub fn make_mut(this: &mut Self) -> &mut T {
644 if Rc::strong_count(this) != 1 {
645 // Gotta clone the data, there are other Rcs
646 *this = Rc::new((**this).clone())
647 } else if Rc::weak_count(this) != 0 {
648 // Can just steal the data, all that's left is Weaks
650 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
651 mem::swap(this, &mut swap);
653 // Remove implicit strong-weak ref (no need to craft a fake
654 // Weak here -- we know other Weaks can clean up for us)
659 // This unsafety is ok because we're guaranteed that the pointer
660 // returned is the *only* pointer that will ever be returned to T. Our
661 // reference count is guaranteed to be 1 at this point, and we required
662 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
663 // reference to the inner value.
665 &mut this.ptr.as_mut().value
670 #[stable(feature = "rust1", since = "1.0.0")]
671 impl<T: ?Sized> Deref for Rc<T> {
675 fn deref(&self) -> &T {
680 #[stable(feature = "rust1", since = "1.0.0")]
681 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
684 /// This will decrement the strong reference count. If the strong reference
685 /// count reaches zero then the only other references (if any) are
686 /// [`Weak`][weak], so we `drop` the inner value.
688 /// [weak]: struct.Weak.html
697 /// impl Drop for Foo {
698 /// fn drop(&mut self) {
699 /// println!("dropped!");
703 /// let foo = Rc::new(Foo);
704 /// let foo2 = Rc::clone(&foo);
706 /// drop(foo); // Doesn't print anything
707 /// drop(foo2); // Prints "dropped!"
711 let ptr = self.ptr.as_ptr();
714 if self.strong() == 0 {
715 // destroy the contained object
716 ptr::drop_in_place(self.ptr.as_mut());
718 // remove the implicit "strong weak" pointer now that we've
719 // destroyed the contents.
722 if self.weak() == 0 {
723 Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T: ?Sized> Clone for Rc<T> {
732 /// Makes a clone of the `Rc` pointer.
734 /// This creates another pointer to the same inner value, increasing the
735 /// strong reference count.
742 /// let five = Rc::new(5);
744 /// Rc::clone(&five);
747 fn clone(&self) -> Rc<T> {
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T: Default> Default for Rc<T> {
755 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
762 /// let x: Rc<i32> = Default::default();
763 /// assert_eq!(*x, 0);
766 fn default() -> Rc<T> {
767 Rc::new(Default::default())
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
773 /// Equality for two `Rc`s.
775 /// Two `Rc`s are equal if their inner values are equal.
782 /// let five = Rc::new(5);
784 /// assert!(five == Rc::new(5));
787 fn eq(&self, other: &Rc<T>) -> bool {
791 /// Inequality for two `Rc`s.
793 /// Two `Rc`s are unequal if their inner values are unequal.
800 /// let five = Rc::new(5);
802 /// assert!(five != Rc::new(6));
805 fn ne(&self, other: &Rc<T>) -> bool {
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl<T: ?Sized + Eq> Eq for Rc<T> {}
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
815 /// Partial comparison for two `Rc`s.
817 /// The two are compared by calling `partial_cmp()` on their inner values.
823 /// use std::cmp::Ordering;
825 /// let five = Rc::new(5);
827 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
830 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
831 (**self).partial_cmp(&**other)
834 /// Less-than comparison for two `Rc`s.
836 /// The two are compared by calling `<` on their inner values.
843 /// let five = Rc::new(5);
845 /// assert!(five < Rc::new(6));
848 fn lt(&self, other: &Rc<T>) -> bool {
852 /// 'Less than or equal to' comparison for two `Rc`s.
854 /// The two are compared by calling `<=` on their inner values.
861 /// let five = Rc::new(5);
863 /// assert!(five <= Rc::new(5));
866 fn le(&self, other: &Rc<T>) -> bool {
870 /// Greater-than comparison for two `Rc`s.
872 /// The two are compared by calling `>` on their inner values.
879 /// let five = Rc::new(5);
881 /// assert!(five > Rc::new(4));
884 fn gt(&self, other: &Rc<T>) -> bool {
888 /// 'Greater than or equal to' comparison for two `Rc`s.
890 /// The two are compared by calling `>=` on their inner values.
897 /// let five = Rc::new(5);
899 /// assert!(five >= Rc::new(5));
902 fn ge(&self, other: &Rc<T>) -> bool {
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<T: ?Sized + Ord> Ord for Rc<T> {
909 /// Comparison for two `Rc`s.
911 /// The two are compared by calling `cmp()` on their inner values.
917 /// use std::cmp::Ordering;
919 /// let five = Rc::new(5);
921 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
924 fn cmp(&self, other: &Rc<T>) -> Ordering {
925 (**self).cmp(&**other)
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl<T: ?Sized + Hash> Hash for Rc<T> {
931 fn hash<H: Hasher>(&self, state: &mut H) {
932 (**self).hash(state);
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
938 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
939 fmt::Display::fmt(&**self, f)
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
945 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
946 fmt::Debug::fmt(&**self, f)
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl<T: ?Sized> fmt::Pointer for Rc<T> {
952 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
953 fmt::Pointer::fmt(&self.ptr, f)
957 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
958 impl<T> From<T> for Rc<T> {
959 fn from(t: T) -> Self {
964 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
965 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
966 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
968 /// Since a `Weak` reference does not count towards ownership, it will not
969 /// prevent the inner value from being dropped, and `Weak` itself makes no
970 /// guarantees about the value still being present and may return [`None`]
971 /// when [`upgrade`]d.
973 /// A `Weak` pointer is useful for keeping a temporary reference to the value
974 /// within [`Rc`] without extending its lifetime. It is also used to prevent
975 /// circular references between [`Rc`] pointers, since mutual owning references
976 /// would never allow either [`Arc`] to be dropped. For example, a tree could
977 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
978 /// pointers from children back to their parents.
980 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
982 /// [`Rc`]: struct.Rc.html
983 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
984 /// [`upgrade`]: struct.Weak.html#method.upgrade
985 /// [`Option`]: ../../std/option/enum.Option.html
986 /// [`None`]: ../../std/option/enum.Option.html#variant.None
987 #[stable(feature = "rc_weak", since = "1.4.0")]
988 pub struct Weak<T: ?Sized> {
989 ptr: Shared<RcBox<T>>,
992 #[stable(feature = "rc_weak", since = "1.4.0")]
993 impl<T: ?Sized> !marker::Send for Weak<T> {}
994 #[stable(feature = "rc_weak", since = "1.4.0")]
995 impl<T: ?Sized> !marker::Sync for Weak<T> {}
997 #[unstable(feature = "coerce_unsized", issue = "27732")]
998 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1001 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1002 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1004 /// [`upgrade`]: struct.Weak.html#method.upgrade
1005 /// [`None`]: ../../std/option/enum.Option.html
1010 /// use std::rc::Weak;
1012 /// let empty: Weak<i64> = Weak::new();
1013 /// assert!(empty.upgrade().is_none());
1015 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1016 pub fn new() -> Weak<T> {
1019 ptr: Shared::new(Box::into_raw(box RcBox {
1020 strong: Cell::new(0),
1022 value: uninitialized(),
1029 impl<T: ?Sized> Weak<T> {
1030 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1031 /// the lifetime of the value if successful.
1033 /// Returns [`None`] if the value has since been dropped.
1035 /// [`Rc`]: struct.Rc.html
1036 /// [`None`]: ../../std/option/enum.Option.html
1041 /// use std::rc::Rc;
1043 /// let five = Rc::new(5);
1045 /// let weak_five = Rc::downgrade(&five);
1047 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1048 /// assert!(strong_five.is_some());
1050 /// // Destroy all strong pointers.
1051 /// drop(strong_five);
1054 /// assert!(weak_five.upgrade().is_none());
1056 #[stable(feature = "rc_weak", since = "1.4.0")]
1057 pub fn upgrade(&self) -> Option<Rc<T>> {
1058 if self.strong() == 0 {
1062 Some(Rc { ptr: self.ptr })
1067 #[stable(feature = "rc_weak", since = "1.4.0")]
1068 impl<T: ?Sized> Drop for Weak<T> {
1069 /// Drops the `Weak` pointer.
1074 /// use std::rc::{Rc, Weak};
1078 /// impl Drop for Foo {
1079 /// fn drop(&mut self) {
1080 /// println!("dropped!");
1084 /// let foo = Rc::new(Foo);
1085 /// let weak_foo = Rc::downgrade(&foo);
1086 /// let other_weak_foo = Weak::clone(&weak_foo);
1088 /// drop(weak_foo); // Doesn't print anything
1089 /// drop(foo); // Prints "dropped!"
1091 /// assert!(other_weak_foo.upgrade().is_none());
1093 fn drop(&mut self) {
1095 let ptr = self.ptr.as_ptr();
1098 // the weak count starts at 1, and will only go to zero if all
1099 // the strong pointers have disappeared.
1100 if self.weak() == 0 {
1101 Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
1107 #[stable(feature = "rc_weak", since = "1.4.0")]
1108 impl<T: ?Sized> Clone for Weak<T> {
1109 /// Makes a clone of the `Weak` pointer that points to the same value.
1114 /// use std::rc::{Rc, Weak};
1116 /// let weak_five = Rc::downgrade(&Rc::new(5));
1118 /// Weak::clone(&weak_five);
1121 fn clone(&self) -> Weak<T> {
1123 Weak { ptr: self.ptr }
1127 #[stable(feature = "rc_weak", since = "1.4.0")]
1128 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1134 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1135 impl<T> Default for Weak<T> {
1136 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1137 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1139 /// [`upgrade`]: struct.Weak.html#method.upgrade
1140 /// [`None`]: ../../std/option/enum.Option.html
1145 /// use std::rc::Weak;
1147 /// let empty: Weak<i64> = Default::default();
1148 /// assert!(empty.upgrade().is_none());
1150 fn default() -> Weak<T> {
1155 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1156 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1157 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1158 // We abort because this is such a degenerate scenario that we don't care about
1159 // what happens -- no real program should ever experience this.
1161 // This should have negligible overhead since you don't actually need to
1162 // clone these much in Rust thanks to ownership and move-semantics.
1165 trait RcBoxPtr<T: ?Sized> {
1166 fn inner(&self) -> &RcBox<T>;
1169 fn strong(&self) -> usize {
1170 self.inner().strong.get()
1174 fn inc_strong(&self) {
1175 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1179 fn dec_strong(&self) {
1180 self.inner().strong.set(self.strong() - 1);
1184 fn weak(&self) -> usize {
1185 self.inner().weak.get()
1189 fn inc_weak(&self) {
1190 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1194 fn dec_weak(&self) {
1195 self.inner().weak.set(self.weak() - 1);
1199 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1201 fn inner(&self) -> &RcBox<T> {
1208 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1210 fn inner(&self) -> &RcBox<T> {
1219 use super::{Rc, Weak};
1220 use std::boxed::Box;
1221 use std::cell::RefCell;
1222 use std::option::Option;
1223 use std::option::Option::{None, Some};
1224 use std::result::Result::{Err, Ok};
1226 use std::clone::Clone;
1227 use std::convert::From;
1231 let x = Rc::new(RefCell::new(5));
1233 *x.borrow_mut() = 20;
1234 assert_eq!(*y.borrow(), 20);
1244 fn test_simple_clone() {
1252 fn test_destructor() {
1253 let x: Rc<Box<_>> = Rc::new(box 5);
1260 let y = Rc::downgrade(&x);
1261 assert!(y.upgrade().is_some());
1267 let y = Rc::downgrade(&x);
1269 assert!(y.upgrade().is_none());
1273 fn weak_self_cyclic() {
1275 x: RefCell<Option<Weak<Cycle>>>,
1278 let a = Rc::new(Cycle { x: RefCell::new(None) });
1279 let b = Rc::downgrade(&a.clone());
1280 *a.x.borrow_mut() = Some(b);
1282 // hopefully we don't double-free (or leak)...
1288 assert!(Rc::is_unique(&x));
1290 assert!(!Rc::is_unique(&x));
1292 assert!(Rc::is_unique(&x));
1293 let w = Rc::downgrade(&x);
1294 assert!(!Rc::is_unique(&x));
1296 assert!(Rc::is_unique(&x));
1300 fn test_strong_count() {
1302 assert!(Rc::strong_count(&a) == 1);
1303 let w = Rc::downgrade(&a);
1304 assert!(Rc::strong_count(&a) == 1);
1305 let b = w.upgrade().expect("upgrade of live rc failed");
1306 assert!(Rc::strong_count(&b) == 2);
1307 assert!(Rc::strong_count(&a) == 2);
1310 assert!(Rc::strong_count(&b) == 1);
1312 assert!(Rc::strong_count(&b) == 2);
1313 assert!(Rc::strong_count(&c) == 2);
1317 fn test_weak_count() {
1319 assert!(Rc::strong_count(&a) == 1);
1320 assert!(Rc::weak_count(&a) == 0);
1321 let w = Rc::downgrade(&a);
1322 assert!(Rc::strong_count(&a) == 1);
1323 assert!(Rc::weak_count(&a) == 1);
1325 assert!(Rc::strong_count(&a) == 1);
1326 assert!(Rc::weak_count(&a) == 0);
1328 assert!(Rc::strong_count(&a) == 2);
1329 assert!(Rc::weak_count(&a) == 0);
1336 assert_eq!(Rc::try_unwrap(x), Ok(3));
1339 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1341 let _w = Rc::downgrade(&x);
1342 assert_eq!(Rc::try_unwrap(x), Ok(5));
1346 fn into_from_raw() {
1347 let x = Rc::new(box "hello");
1350 let x_ptr = Rc::into_raw(x);
1353 assert_eq!(**x_ptr, "hello");
1355 let x = Rc::from_raw(x_ptr);
1356 assert_eq!(**x, "hello");
1358 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1364 let mut x = Rc::new(3);
1365 *Rc::get_mut(&mut x).unwrap() = 4;
1368 assert!(Rc::get_mut(&mut x).is_none());
1370 assert!(Rc::get_mut(&mut x).is_some());
1371 let _w = Rc::downgrade(&x);
1372 assert!(Rc::get_mut(&mut x).is_none());
1376 fn test_cowrc_clone_make_unique() {
1377 let mut cow0 = Rc::new(75);
1378 let mut cow1 = cow0.clone();
1379 let mut cow2 = cow1.clone();
1381 assert!(75 == *Rc::make_mut(&mut cow0));
1382 assert!(75 == *Rc::make_mut(&mut cow1));
1383 assert!(75 == *Rc::make_mut(&mut cow2));
1385 *Rc::make_mut(&mut cow0) += 1;
1386 *Rc::make_mut(&mut cow1) += 2;
1387 *Rc::make_mut(&mut cow2) += 3;
1389 assert!(76 == *cow0);
1390 assert!(77 == *cow1);
1391 assert!(78 == *cow2);
1393 // none should point to the same backing memory
1394 assert!(*cow0 != *cow1);
1395 assert!(*cow0 != *cow2);
1396 assert!(*cow1 != *cow2);
1400 fn test_cowrc_clone_unique2() {
1401 let mut cow0 = Rc::new(75);
1402 let cow1 = cow0.clone();
1403 let cow2 = cow1.clone();
1405 assert!(75 == *cow0);
1406 assert!(75 == *cow1);
1407 assert!(75 == *cow2);
1409 *Rc::make_mut(&mut cow0) += 1;
1411 assert!(76 == *cow0);
1412 assert!(75 == *cow1);
1413 assert!(75 == *cow2);
1415 // cow1 and cow2 should share the same contents
1416 // cow0 should have a unique reference
1417 assert!(*cow0 != *cow1);
1418 assert!(*cow0 != *cow2);
1419 assert!(*cow1 == *cow2);
1423 fn test_cowrc_clone_weak() {
1424 let mut cow0 = Rc::new(75);
1425 let cow1_weak = Rc::downgrade(&cow0);
1427 assert!(75 == *cow0);
1428 assert!(75 == *cow1_weak.upgrade().unwrap());
1430 *Rc::make_mut(&mut cow0) += 1;
1432 assert!(76 == *cow0);
1433 assert!(cow1_weak.upgrade().is_none());
1438 let foo = Rc::new(75);
1439 assert_eq!(format!("{:?}", foo), "75");
1444 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1445 assert_eq!(foo, foo.clone());
1449 fn test_from_owned() {
1451 let foo_rc = Rc::from(foo);
1452 assert!(123 == *foo_rc);
1456 fn test_new_weak() {
1457 let foo: Weak<usize> = Weak::new();
1458 assert!(foo.upgrade().is_none());
1463 let five = Rc::new(5);
1464 let same_five = five.clone();
1465 let other_five = Rc::new(5);
1467 assert!(Rc::ptr_eq(&five, &same_five));
1468 assert!(!Rc::ptr_eq(&five, &other_five));
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1474 fn borrow(&self) -> &T {
1479 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1480 impl<T: ?Sized> AsRef<T> for Rc<T> {
1481 fn as_ref(&self) -> &T {