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.
58 //! # Cloning references
60 //! Creating a new reference from an existing reference counted pointer is done using the
61 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
65 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
66 //! // The two syntaxes below are equivalent.
67 //! let a = foo.clone();
68 //! let b = Rc::clone(&foo);
69 //! // a and b both point to the same memory location as foo.
72 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
73 //! the meaning of the code. In the example above, this syntax makes it easier to see that
74 //! this code is creating a new reference rather than copying the whole content of foo.
78 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
79 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
80 //! unique ownership, because more than one gadget may belong to the same
81 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
82 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
89 //! // ...other fields
95 //! // ...other fields
99 //! // Create a reference-counted `Owner`.
100 //! let gadget_owner: Rc<Owner> = Rc::new(
102 //! name: "Gadget Man".to_string(),
106 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
107 //! // value gives us a new pointer to the same `Owner` value, incrementing
108 //! // the reference count in the process.
109 //! let gadget1 = Gadget {
111 //! owner: Rc::clone(&gadget_owner),
113 //! let gadget2 = Gadget {
115 //! owner: Rc::clone(&gadget_owner),
118 //! // Dispose of our local variable `gadget_owner`.
119 //! drop(gadget_owner);
121 //! // Despite dropping `gadget_owner`, we're still able to print out the name
122 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
123 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
124 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
125 //! // allocated. The field projection `gadget1.owner.name` works because
126 //! // `Rc<Owner>` automatically dereferences to `Owner`.
127 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
128 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
130 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
131 //! // with them the last counted references to our `Owner`. Gadget Man now
132 //! // gets destroyed as well.
136 //! If our requirements change, and we also need to be able to traverse from
137 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
138 //! to `Gadget` introduces a cycle between the values. This means that their
139 //! reference counts can never reach 0, and the values will remain allocated
140 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
143 //! Rust actually makes it somewhat difficult to produce this loop in the first
144 //! place. In order to end up with two values that point at each other, one of
145 //! them needs to be mutable. This is difficult because [`Rc`] enforces
146 //! memory safety by only giving out shared references to the value it wraps,
147 //! and these don't allow direct mutation. We need to wrap the part of the
148 //! value we wish to mutate in a [`RefCell`], which provides *interior
149 //! mutability*: a method to achieve mutability through a shared reference.
150 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
154 //! use std::rc::Weak;
155 //! use std::cell::RefCell;
159 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
160 //! // ...other fields
165 //! owner: Rc<Owner>,
166 //! // ...other fields
170 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
171 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
172 //! // a shared reference.
173 //! let gadget_owner: Rc<Owner> = Rc::new(
175 //! name: "Gadget Man".to_string(),
176 //! gadgets: RefCell::new(vec![]),
180 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
181 //! let gadget1 = Rc::new(
184 //! owner: Rc::clone(&gadget_owner),
187 //! let gadget2 = Rc::new(
190 //! owner: Rc::clone(&gadget_owner),
194 //! // Add the `Gadget`s to their `Owner`.
196 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
197 //! gadgets.push(Rc::downgrade(&gadget1));
198 //! gadgets.push(Rc::downgrade(&gadget2));
200 //! // `RefCell` dynamic borrow ends here.
203 //! // Iterate over our `Gadget`s, printing their details out.
204 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
206 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
207 //! // guarantee the value is still allocated, we need to call
208 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
210 //! // In this case we know the value still exists, so we simply
211 //! // `unwrap` the `Option`. In a more complicated program, you might
212 //! // need graceful error handling for a `None` result.
214 //! let gadget = gadget_weak.upgrade().unwrap();
215 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
218 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
219 //! // are destroyed. There are now no strong (`Rc`) pointers to the
220 //! // gadgets, so they are destroyed. This zeroes the reference count on
221 //! // Gadget Man, so he gets destroyed as well.
225 //! [`Rc`]: struct.Rc.html
226 //! [`Weak`]: struct.Weak.html
227 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
228 //! [`Cell`]: ../../std/cell/struct.Cell.html
229 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
230 //! [send]: ../../std/marker/trait.Send.html
231 //! [arc]: ../../std/sync/struct.Arc.html
232 //! [`Deref`]: ../../std/ops/trait.Deref.html
233 //! [downgrade]: struct.Rc.html#method.downgrade
234 //! [upgrade]: struct.Weak.html#method.upgrade
235 //! [`None`]: ../../std/option/enum.Option.html#variant.None
236 //! [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
237 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
239 #![stable(feature = "rust1", since = "1.0.0")]
247 use core::cell::Cell;
248 use core::cmp::Ordering;
250 use core::hash::{Hash, Hasher};
251 use core::intrinsics::abort;
253 use core::marker::Unsize;
254 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
255 use core::ops::Deref;
256 use core::ops::CoerceUnsized;
257 use core::ptr::{self, Shared};
258 use core::convert::From;
260 use heap::{allocate, deallocate, box_free};
263 struct RcBox<T: ?Sized> {
269 /// A single-threaded reference-counting pointer.
271 /// See the [module-level documentation](./index.html) for more details.
273 /// The inherent methods of `Rc` are all associated functions, which means
274 /// that you have to call them as e.g. [`Rc::get_mut(&value)`][get_mut] instead of
275 /// `value.get_mut()`. This avoids conflicts with methods of the inner
278 /// [get_mut]: #method.get_mut
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub struct Rc<T: ?Sized> {
281 ptr: Shared<RcBox<T>>,
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<T: ?Sized> !marker::Send for Rc<T> {}
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T: ?Sized> !marker::Sync for Rc<T> {}
289 #[unstable(feature = "coerce_unsized", issue = "27732")]
290 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
293 /// Constructs a new `Rc<T>`.
300 /// let five = Rc::new(5);
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn new(value: T) -> Rc<T> {
306 // there is an implicit weak pointer owned by all the strong
307 // pointers, which ensures that the weak destructor never frees
308 // the allocation while the strong destructor is running, even
309 // if the weak pointer is stored inside the strong one.
310 ptr: Shared::new(Box::into_raw(box RcBox {
311 strong: Cell::new(1),
319 /// Returns the contained value, if the `Rc` has exactly one strong reference.
321 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
324 /// This will succeed even if there are outstanding weak references.
326 /// [result]: ../../std/result/enum.Result.html
333 /// let x = Rc::new(3);
334 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
336 /// let x = Rc::new(4);
337 /// let _y = Rc::clone(&x);
338 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
341 #[stable(feature = "rc_unique", since = "1.4.0")]
342 pub fn try_unwrap(this: Self) -> Result<T, Self> {
343 if Rc::strong_count(&this) == 1 {
345 let val = ptr::read(&*this); // copy the contained object
347 // Indicate to Weaks that they can't be promoted by decrememting
348 // the strong count, and then remove the implicit "strong weak"
349 // pointer while also handling drop logic by just crafting a
352 let _weak = Weak { ptr: this.ptr };
361 /// Consumes the `Rc`, returning the wrapped pointer.
363 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
364 /// [`Rc::from_raw`][from_raw].
366 /// [from_raw]: struct.Rc.html#method.from_raw
373 /// let x = Rc::new(10);
374 /// let x_ptr = Rc::into_raw(x);
375 /// assert_eq!(unsafe { *x_ptr }, 10);
377 #[stable(feature = "rc_raw", since = "1.17.0")]
378 pub fn into_raw(this: Self) -> *const T {
379 let ptr: *const T = &*this;
384 /// Constructs an `Rc` from a raw pointer.
386 /// The raw pointer must have been previously returned by a call to a
387 /// [`Rc::into_raw`][into_raw].
389 /// This function is unsafe because improper use may lead to memory problems. For example, a
390 /// double-free may occur if the function is called twice on the same raw pointer.
392 /// [into_raw]: struct.Rc.html#method.into_raw
399 /// let x = Rc::new(10);
400 /// let x_ptr = Rc::into_raw(x);
403 /// // Convert back to an `Rc` to prevent leak.
404 /// let x = Rc::from_raw(x_ptr);
405 /// assert_eq!(*x, 10);
407 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
410 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
412 #[stable(feature = "rc_raw", since = "1.17.0")]
413 pub unsafe fn from_raw(ptr: *const T) -> Self {
414 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
415 // `value` field from the pointer.
417 let ptr = (ptr as *const u8).offset(-offset_of!(RcBox<T>, value));
419 ptr: Shared::new(ptr as *mut u8 as *mut _)
425 /// Constructs a new `Rc<str>` from a string slice.
427 #[unstable(feature = "rustc_private",
428 reason = "for internal use in rustc",
430 pub fn __from_str(value: &str) -> Rc<str> {
432 // Allocate enough space for `RcBox<str>`.
433 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
434 let vec = RawVec::<usize>::with_capacity(aligned_len);
437 // Initialize fields of `RcBox<str>`.
438 *ptr.offset(0) = 1; // strong: Cell::new(1)
439 *ptr.offset(1) = 1; // weak: Cell::new(1)
440 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
441 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
442 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
443 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
444 Rc { ptr: Shared::new(rcbox_ptr) }
450 /// Constructs a new `Rc<[T]>` from a `Box<[T]>`.
452 #[unstable(feature = "rustc_private",
453 reason = "for internal use in rustc",
455 pub fn __from_array(value: Box<[T]>) -> Rc<[T]> {
457 let ptr: *mut RcBox<[T]> =
458 mem::transmute([mem::align_of::<RcBox<[T; 1]>>(), value.len()]);
459 // FIXME(custom-DST): creating this invalid &[T] is dubiously defined,
460 // we should have a better way of getting the size/align
461 // of a DST from its unsized part.
462 let ptr = allocate(size_of_val(&*ptr), align_of_val(&*ptr));
463 let ptr: *mut RcBox<[T]> = mem::transmute([ptr as usize, value.len()]);
465 // Initialize the new RcBox.
466 ptr::write(&mut (*ptr).strong, Cell::new(1));
467 ptr::write(&mut (*ptr).weak, Cell::new(1));
468 ptr::copy_nonoverlapping(
470 &mut (*ptr).value as *mut [T] as *mut T,
473 // Free the original allocation without freeing its (moved) contents.
474 box_free(Box::into_raw(value));
476 Rc { ptr: Shared::new(ptr as *mut _) }
481 impl<T: ?Sized> Rc<T> {
482 /// Creates a new [`Weak`][weak] pointer to this value.
484 /// [weak]: struct.Weak.html
491 /// let five = Rc::new(5);
493 /// let weak_five = Rc::downgrade(&five);
495 #[stable(feature = "rc_weak", since = "1.4.0")]
496 pub fn downgrade(this: &Self) -> Weak<T> {
498 Weak { ptr: this.ptr }
501 /// Gets the number of [`Weak`][weak] pointers to this value.
503 /// [weak]: struct.Weak.html
510 /// let five = Rc::new(5);
511 /// let _weak_five = Rc::downgrade(&five);
513 /// assert_eq!(1, Rc::weak_count(&five));
516 #[stable(feature = "rc_counts", since = "1.15.0")]
517 pub fn weak_count(this: &Self) -> usize {
521 /// Gets the number of strong (`Rc`) pointers to this value.
528 /// let five = Rc::new(5);
529 /// let _also_five = Rc::clone(&five);
531 /// assert_eq!(2, Rc::strong_count(&five));
534 #[stable(feature = "rc_counts", since = "1.15.0")]
535 pub fn strong_count(this: &Self) -> usize {
539 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
540 /// this inner value.
542 /// [weak]: struct.Weak.html
544 fn is_unique(this: &Self) -> bool {
545 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
548 /// Returns a mutable reference to the inner value, if there are
549 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
551 /// Returns [`None`] otherwise, because it is not safe to
552 /// mutate a shared value.
554 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
555 /// the inner value when it's shared.
557 /// [weak]: struct.Weak.html
558 /// [`None`]: ../../std/option/enum.Option.html#variant.None
559 /// [make_mut]: struct.Rc.html#method.make_mut
560 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
567 /// let mut x = Rc::new(3);
568 /// *Rc::get_mut(&mut x).unwrap() = 4;
569 /// assert_eq!(*x, 4);
571 /// let _y = Rc::clone(&x);
572 /// assert!(Rc::get_mut(&mut x).is_none());
575 #[stable(feature = "rc_unique", since = "1.4.0")]
576 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
577 if Rc::is_unique(this) {
579 Some(&mut this.ptr.as_mut().value)
587 #[stable(feature = "ptr_eq", since = "1.17.0")]
588 /// Returns true if the two `Rc`s point to the same value (not
589 /// just values that compare as equal).
596 /// let five = Rc::new(5);
597 /// let same_five = Rc::clone(&five);
598 /// let other_five = Rc::new(5);
600 /// assert!(Rc::ptr_eq(&five, &same_five));
601 /// assert!(!Rc::ptr_eq(&five, &other_five));
603 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
604 this.ptr.as_ptr() == other.ptr.as_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 = Rc::clone(&data); // 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.as_ref().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.
662 &mut this.ptr.as_mut().value
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl<T: ?Sized> Deref for Rc<T> {
672 fn deref(&self) -> &T {
677 #[stable(feature = "rust1", since = "1.0.0")]
678 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
681 /// This will decrement the strong reference count. If the strong reference
682 /// count reaches zero then the only other references (if any) are
683 /// [`Weak`][weak], so we `drop` the inner value.
685 /// [weak]: struct.Weak.html
694 /// impl Drop for Foo {
695 /// fn drop(&mut self) {
696 /// println!("dropped!");
700 /// let foo = Rc::new(Foo);
701 /// let foo2 = Rc::clone(&foo);
703 /// drop(foo); // Doesn't print anything
704 /// drop(foo2); // Prints "dropped!"
708 let ptr = self.ptr.as_ptr();
711 if self.strong() == 0 {
712 // destroy the contained object
713 ptr::drop_in_place(self.ptr.as_mut());
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);
741 /// Rc::clone(&five);
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 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
962 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
963 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
965 /// Since a `Weak` reference does not count towards ownership, it will not
966 /// prevent the inner value from being dropped, and `Weak` itself makes no
967 /// guarantees about the value still being present and may return [`None`]
968 /// when [`upgrade`]d.
970 /// A `Weak` pointer is useful for keeping a temporary reference to the value
971 /// within [`Rc`] without extending its lifetime. It is also used to prevent
972 /// circular references between [`Rc`] pointers, since mutual owning references
973 /// would never allow either [`Arc`] to be dropped. For example, a tree could
974 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
975 /// pointers from children back to their parents.
977 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
979 /// [`Rc`]: struct.Rc.html
980 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
981 /// [`upgrade`]: struct.Weak.html#method.upgrade
982 /// [`Option`]: ../../std/option/enum.Option.html
983 /// [`None`]: ../../std/option/enum.Option.html#variant.None
984 #[stable(feature = "rc_weak", since = "1.4.0")]
985 pub struct Weak<T: ?Sized> {
986 ptr: Shared<RcBox<T>>,
989 #[stable(feature = "rc_weak", since = "1.4.0")]
990 impl<T: ?Sized> !marker::Send for Weak<T> {}
991 #[stable(feature = "rc_weak", since = "1.4.0")]
992 impl<T: ?Sized> !marker::Sync for Weak<T> {}
994 #[unstable(feature = "coerce_unsized", issue = "27732")]
995 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
998 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
999 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1001 /// [`upgrade`]: struct.Weak.html#method.upgrade
1002 /// [`None`]: ../../std/option/enum.Option.html
1007 /// use std::rc::Weak;
1009 /// let empty: Weak<i64> = Weak::new();
1010 /// assert!(empty.upgrade().is_none());
1012 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1013 pub fn new() -> Weak<T> {
1016 ptr: Shared::new(Box::into_raw(box RcBox {
1017 strong: Cell::new(0),
1019 value: uninitialized(),
1026 impl<T: ?Sized> Weak<T> {
1027 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1028 /// the lifetime of the value if successful.
1030 /// Returns [`None`] if the value has since been dropped.
1032 /// [`Rc`]: struct.Rc.html
1033 /// [`None`]: ../../std/option/enum.Option.html
1038 /// use std::rc::Rc;
1040 /// let five = Rc::new(5);
1042 /// let weak_five = Rc::downgrade(&five);
1044 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1045 /// assert!(strong_five.is_some());
1047 /// // Destroy all strong pointers.
1048 /// drop(strong_five);
1051 /// assert!(weak_five.upgrade().is_none());
1053 #[stable(feature = "rc_weak", since = "1.4.0")]
1054 pub fn upgrade(&self) -> Option<Rc<T>> {
1055 if self.strong() == 0 {
1059 Some(Rc { ptr: self.ptr })
1064 #[stable(feature = "rc_weak", since = "1.4.0")]
1065 impl<T: ?Sized> Drop for Weak<T> {
1066 /// Drops the `Weak` pointer.
1071 /// use std::rc::{Rc, Weak};
1075 /// impl Drop for Foo {
1076 /// fn drop(&mut self) {
1077 /// println!("dropped!");
1081 /// let foo = Rc::new(Foo);
1082 /// let weak_foo = Rc::downgrade(&foo);
1083 /// let other_weak_foo = Weak::clone(&weak_foo);
1085 /// drop(weak_foo); // Doesn't print anything
1086 /// drop(foo); // Prints "dropped!"
1088 /// assert!(other_weak_foo.upgrade().is_none());
1090 fn drop(&mut self) {
1092 let ptr = self.ptr.as_ptr();
1095 // the weak count starts at 1, and will only go to zero if all
1096 // the strong pointers have disappeared.
1097 if self.weak() == 0 {
1098 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1104 #[stable(feature = "rc_weak", since = "1.4.0")]
1105 impl<T: ?Sized> Clone for Weak<T> {
1106 /// Makes a clone of the `Weak` pointer that points to the same value.
1111 /// use std::rc::{Rc, Weak};
1113 /// let weak_five = Rc::downgrade(&Rc::new(5));
1115 /// Weak::clone(&weak_five);
1118 fn clone(&self) -> Weak<T> {
1120 Weak { ptr: self.ptr }
1124 #[stable(feature = "rc_weak", since = "1.4.0")]
1125 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1132 impl<T> Default for Weak<T> {
1133 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1134 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1136 /// [`upgrade`]: struct.Weak.html#method.upgrade
1137 /// [`None`]: ../../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> {
1205 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1207 fn inner(&self) -> &RcBox<T> {
1216 use super::{Rc, Weak};
1217 use std::boxed::Box;
1218 use std::cell::RefCell;
1219 use std::option::Option;
1220 use std::option::Option::{None, Some};
1221 use std::result::Result::{Err, Ok};
1223 use std::clone::Clone;
1224 use std::convert::From;
1228 let x = Rc::new(RefCell::new(5));
1230 *x.borrow_mut() = 20;
1231 assert_eq!(*y.borrow(), 20);
1241 fn test_simple_clone() {
1249 fn test_destructor() {
1250 let x: Rc<Box<_>> = Rc::new(box 5);
1257 let y = Rc::downgrade(&x);
1258 assert!(y.upgrade().is_some());
1264 let y = Rc::downgrade(&x);
1266 assert!(y.upgrade().is_none());
1270 fn weak_self_cyclic() {
1272 x: RefCell<Option<Weak<Cycle>>>,
1275 let a = Rc::new(Cycle { x: RefCell::new(None) });
1276 let b = Rc::downgrade(&a.clone());
1277 *a.x.borrow_mut() = Some(b);
1279 // hopefully we don't double-free (or leak)...
1285 assert!(Rc::is_unique(&x));
1287 assert!(!Rc::is_unique(&x));
1289 assert!(Rc::is_unique(&x));
1290 let w = Rc::downgrade(&x);
1291 assert!(!Rc::is_unique(&x));
1293 assert!(Rc::is_unique(&x));
1297 fn test_strong_count() {
1299 assert!(Rc::strong_count(&a) == 1);
1300 let w = Rc::downgrade(&a);
1301 assert!(Rc::strong_count(&a) == 1);
1302 let b = w.upgrade().expect("upgrade of live rc failed");
1303 assert!(Rc::strong_count(&b) == 2);
1304 assert!(Rc::strong_count(&a) == 2);
1307 assert!(Rc::strong_count(&b) == 1);
1309 assert!(Rc::strong_count(&b) == 2);
1310 assert!(Rc::strong_count(&c) == 2);
1314 fn test_weak_count() {
1316 assert!(Rc::strong_count(&a) == 1);
1317 assert!(Rc::weak_count(&a) == 0);
1318 let w = Rc::downgrade(&a);
1319 assert!(Rc::strong_count(&a) == 1);
1320 assert!(Rc::weak_count(&a) == 1);
1322 assert!(Rc::strong_count(&a) == 1);
1323 assert!(Rc::weak_count(&a) == 0);
1325 assert!(Rc::strong_count(&a) == 2);
1326 assert!(Rc::weak_count(&a) == 0);
1333 assert_eq!(Rc::try_unwrap(x), Ok(3));
1336 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1338 let _w = Rc::downgrade(&x);
1339 assert_eq!(Rc::try_unwrap(x), Ok(5));
1343 fn into_from_raw() {
1344 let x = Rc::new(box "hello");
1347 let x_ptr = Rc::into_raw(x);
1350 assert_eq!(**x_ptr, "hello");
1352 let x = Rc::from_raw(x_ptr);
1353 assert_eq!(**x, "hello");
1355 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1361 let mut x = Rc::new(3);
1362 *Rc::get_mut(&mut x).unwrap() = 4;
1365 assert!(Rc::get_mut(&mut x).is_none());
1367 assert!(Rc::get_mut(&mut x).is_some());
1368 let _w = Rc::downgrade(&x);
1369 assert!(Rc::get_mut(&mut x).is_none());
1373 fn test_cowrc_clone_make_unique() {
1374 let mut cow0 = Rc::new(75);
1375 let mut cow1 = cow0.clone();
1376 let mut cow2 = cow1.clone();
1378 assert!(75 == *Rc::make_mut(&mut cow0));
1379 assert!(75 == *Rc::make_mut(&mut cow1));
1380 assert!(75 == *Rc::make_mut(&mut cow2));
1382 *Rc::make_mut(&mut cow0) += 1;
1383 *Rc::make_mut(&mut cow1) += 2;
1384 *Rc::make_mut(&mut cow2) += 3;
1386 assert!(76 == *cow0);
1387 assert!(77 == *cow1);
1388 assert!(78 == *cow2);
1390 // none should point to the same backing memory
1391 assert!(*cow0 != *cow1);
1392 assert!(*cow0 != *cow2);
1393 assert!(*cow1 != *cow2);
1397 fn test_cowrc_clone_unique2() {
1398 let mut cow0 = Rc::new(75);
1399 let cow1 = cow0.clone();
1400 let cow2 = cow1.clone();
1402 assert!(75 == *cow0);
1403 assert!(75 == *cow1);
1404 assert!(75 == *cow2);
1406 *Rc::make_mut(&mut cow0) += 1;
1408 assert!(76 == *cow0);
1409 assert!(75 == *cow1);
1410 assert!(75 == *cow2);
1412 // cow1 and cow2 should share the same contents
1413 // cow0 should have a unique reference
1414 assert!(*cow0 != *cow1);
1415 assert!(*cow0 != *cow2);
1416 assert!(*cow1 == *cow2);
1420 fn test_cowrc_clone_weak() {
1421 let mut cow0 = Rc::new(75);
1422 let cow1_weak = Rc::downgrade(&cow0);
1424 assert!(75 == *cow0);
1425 assert!(75 == *cow1_weak.upgrade().unwrap());
1427 *Rc::make_mut(&mut cow0) += 1;
1429 assert!(76 == *cow0);
1430 assert!(cow1_weak.upgrade().is_none());
1435 let foo = Rc::new(75);
1436 assert_eq!(format!("{:?}", foo), "75");
1441 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1442 assert_eq!(foo, foo.clone());
1446 fn test_from_owned() {
1448 let foo_rc = Rc::from(foo);
1449 assert!(123 == *foo_rc);
1453 fn test_new_weak() {
1454 let foo: Weak<usize> = Weak::new();
1455 assert!(foo.upgrade().is_none());
1460 let five = Rc::new(5);
1461 let same_five = five.clone();
1462 let other_five = Rc::new(5);
1464 assert!(Rc::ptr_eq(&five, &same_five));
1465 assert!(!Rc::ptr_eq(&five, &other_five));
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1471 fn borrow(&self) -> &T {
1476 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1477 impl<T: ?Sized> AsRef<T> for Rc<T> {
1478 fn as_ref(&self) -> &T {