1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! Single-threaded reference-counting pointers.
15 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
16 //! allocated in the heap. Invoking [`clone()`][clone] on [`Rc`] produces a new
17 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
18 //! given value is destroyed, the pointed-to value is also destroyed.
20 //! Shared references in Rust disallow mutation by default, and `Rc` is no
21 //! exception. If you need to mutate through an [`Rc`], use [`Cell`] or
24 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
25 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
26 //! does not implement [`Send`][send]. As a result, the Rust compiler
27 //! will check *at compile time* that you are not sending [`Rc`]s between
28 //! threads. If you need multi-threaded, atomic reference counting, use
29 //! [`sync::Arc`][arc].
31 //! The [`downgrade()`][downgrade] method can be used to create a non-owning
32 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
33 //! to an [`Rc`], but this will return [`None`] if the value has
34 //! already been dropped.
36 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
37 //! [`Weak`] is used to break cycles. For example, a tree could have strong
38 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
39 //! children back to their parents.
41 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
42 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
43 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
44 //! functions][assoc], called using function-like syntax:
48 //! let my_rc = Rc::new(());
50 //! Rc::downgrade(&my_rc);
53 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
54 //! already been destroyed.
58 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
59 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
60 //! unique ownership, because more than one gadget may belong to the same
61 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
62 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
69 //! // ...other fields
75 //! // ...other fields
79 //! // Create a reference-counted `Owner`.
80 //! let gadget_owner: Rc<Owner> = Rc::new(
82 //! name: "Gadget Man".to_string(),
86 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
87 //! // value gives us a new pointer to the same `Owner` value, incrementing
88 //! // the reference count in the process.
89 //! let gadget1 = Gadget {
91 //! owner: gadget_owner.clone(),
93 //! let gadget2 = Gadget {
95 //! owner: gadget_owner.clone(),
98 //! // Dispose of our local variable `gadget_owner`.
99 //! drop(gadget_owner);
101 //! // Despite dropping `gadget_owner`, we're still able to print out the name
102 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
103 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
104 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
105 //! // allocated. The field projection `gadget1.owner.name` works because
106 //! // `Rc<Owner>` automatically dereferences to `Owner`.
107 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
108 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
110 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
111 //! // with them the last counted references to our `Owner`. Gadget Man now
112 //! // gets destroyed as well.
116 //! If our requirements change, and we also need to be able to traverse from
117 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
118 //! to `Gadget` introduces a cycle between the values. This means that their
119 //! reference counts can never reach 0, and the values will remain allocated
120 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
123 //! Rust actually makes it somewhat difficult to produce this loop in the first
124 //! place. In order to end up with two values that point at each other, one of
125 //! them needs to be mutable. This is difficult because [`Rc`] enforces
126 //! memory safety by only giving out shared references to the value it wraps,
127 //! and these don't allow direct mutation. We need to wrap the part of the
128 //! value we wish to mutate in a [`RefCell`], which provides *interior
129 //! mutability*: a method to achieve mutability through a shared reference.
130 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
134 //! use std::rc::Weak;
135 //! use std::cell::RefCell;
139 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
140 //! // ...other fields
145 //! owner: Rc<Owner>,
146 //! // ...other fields
150 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
151 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
152 //! // a shared reference.
153 //! let gadget_owner: Rc<Owner> = Rc::new(
155 //! name: "Gadget Man".to_string(),
156 //! gadgets: RefCell::new(vec![]),
160 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
161 //! let gadget1 = Rc::new(
164 //! owner: gadget_owner.clone(),
167 //! let gadget2 = Rc::new(
170 //! owner: gadget_owner.clone(),
174 //! // Add the `Gadget`s to their `Owner`.
176 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
177 //! gadgets.push(Rc::downgrade(&gadget1));
178 //! gadgets.push(Rc::downgrade(&gadget2));
180 //! // `RefCell` dynamic borrow ends here.
183 //! // Iterate over our `Gadget`s, printing their details out.
184 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
186 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
187 //! // guarantee the value is still allocated, we need to call
188 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
190 //! // In this case we know the value still exists, so we simply
191 //! // `unwrap` the `Option`. In a more complicated program, you might
192 //! // need graceful error handling for a `None` result.
194 //! let gadget = gadget_weak.upgrade().unwrap();
195 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
198 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
199 //! // are destroyed. There are now no strong (`Rc`) pointers to the
200 //! // gadgets, so they are destroyed. This zeroes the reference count on
201 //! // Gadget Man, so he gets destroyed as well.
205 //! [`Rc`]: struct.Rc.html
206 //! [`Weak`]: struct.Weak.html
207 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
208 //! [`Cell`]: ../../std/cell/struct.Cell.html
209 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
210 //! [send]: ../../std/marker/trait.Send.html
211 //! [arc]: ../../std/sync/struct.Arc.html
212 //! [`Deref`]: ../../std/ops/trait.Deref.html
213 //! [downgrade]: struct.Rc.html#method.downgrade
214 //! [upgrade]: struct.Weak.html#method.upgrade
215 //! [`None`]: ../../std/option/enum.Option.html#variant.None
216 //! [assoc]: ../../book/method-syntax.html#associated-functions
218 #![stable(feature = "rust1", since = "1.0.0")]
226 use core::cell::Cell;
227 use core::cmp::Ordering;
229 use core::hash::{Hash, Hasher};
230 use core::intrinsics::{abort, assume};
232 use core::marker::Unsize;
233 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
234 use core::ops::Deref;
235 use core::ops::CoerceUnsized;
236 use core::ptr::{self, Shared};
237 use core::convert::From;
239 use heap::deallocate;
242 struct RcBox<T: ?Sized> {
249 /// A single-threaded reference-counting pointer.
251 /// See the [module-level documentation](./index.html) for more details.
253 /// The inherent methods of `Rc` are all associated functions, which means
254 /// that you have to call them as e.g. [`Rc::get_mut(&value)`][get_mut] instead of
255 /// `value.get_mut()`. This avoids conflicts with methods of the inner
258 /// [get_mut]: #method.get_mut
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub struct Rc<T: ?Sized> {
261 ptr: Shared<RcBox<T>>,
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<T: ?Sized> !marker::Send for Rc<T> {}
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T: ?Sized> !marker::Sync for Rc<T> {}
269 #[unstable(feature = "coerce_unsized", issue = "27732")]
270 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
273 /// Constructs a new `Rc<T>`.
280 /// let five = Rc::new(5);
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn new(value: T) -> Rc<T> {
286 // there is an implicit weak pointer owned by all the strong
287 // pointers, which ensures that the weak destructor never frees
288 // the allocation while the strong destructor is running, even
289 // if the weak pointer is stored inside the strong one.
290 ptr: Shared::new(Box::into_raw(box RcBox {
291 strong: Cell::new(1),
299 /// Returns the contained value, if the `Rc` has exactly one strong reference.
301 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
304 /// This will succeed even if there are outstanding weak references.
306 /// [result]: ../../std/result/enum.Result.html
313 /// let x = Rc::new(3);
314 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
316 /// let x = Rc::new(4);
317 /// let _y = x.clone();
318 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
321 #[stable(feature = "rc_unique", since = "1.4.0")]
322 pub fn try_unwrap(this: Self) -> Result<T, Self> {
323 if Rc::would_unwrap(&this) {
325 let val = ptr::read(&*this); // copy the contained object
327 // Indicate to Weaks that they can't be promoted by decrememting
328 // the strong count, and then remove the implicit "strong weak"
329 // pointer while also handling drop logic by just crafting a
332 let _weak = Weak { ptr: this.ptr };
341 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
344 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
345 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
350 /// #![feature(rc_would_unwrap)]
354 /// let x = Rc::new(3);
355 /// assert!(Rc::would_unwrap(&x));
356 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
358 /// let x = Rc::new(4);
359 /// let _y = x.clone();
360 /// assert!(!Rc::would_unwrap(&x));
361 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
363 #[unstable(feature = "rc_would_unwrap",
364 reason = "just added for niche usecase",
366 pub fn would_unwrap(this: &Self) -> bool {
367 Rc::strong_count(&this) == 1
370 /// Consumes the `Rc`, returning the wrapped pointer.
372 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
373 /// [`Rc::from_raw`][from_raw].
375 /// [from_raw]: struct.Rc.html#method.from_raw
380 /// #![feature(rc_raw)]
384 /// let x = Rc::new(10);
385 /// let x_ptr = Rc::into_raw(x);
386 /// assert_eq!(unsafe { *x_ptr }, 10);
388 #[unstable(feature = "rc_raw", issue = "37197")]
389 pub fn into_raw(this: Self) -> *mut T {
390 let ptr = unsafe { &mut (**this.ptr).value as *mut _ };
395 /// Constructs an `Rc` from a raw pointer.
397 /// The raw pointer must have been previously returned by a call to a
398 /// [`Rc::into_raw`][into_raw].
400 /// This function is unsafe because improper use may lead to memory problems. For example, a
401 /// double-free may occur if the function is called twice on the same raw pointer.
403 /// [into_raw]: struct.Rc.html#method.into_raw
408 /// #![feature(rc_raw)]
412 /// let x = Rc::new(10);
413 /// let x_ptr = Rc::into_raw(x);
416 /// // Convert back to an `Rc` to prevent leak.
417 /// let x = Rc::from_raw(x_ptr);
418 /// assert_eq!(*x, 10);
420 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
423 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
425 #[unstable(feature = "rc_raw", issue = "37197")]
426 pub unsafe fn from_raw(ptr: *mut T) -> Self {
427 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
428 // `value` field from the pointer.
429 Rc { ptr: Shared::new((ptr as *mut u8).offset(-offset_of!(RcBox<T>, value)) as *mut _) }
434 /// Constructs a new `Rc<str>` from a string slice.
436 #[unstable(feature = "rustc_private",
437 reason = "for internal use in rustc",
439 pub fn __from_str(value: &str) -> Rc<str> {
441 // Allocate enough space for `RcBox<str>`.
442 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
443 let vec = RawVec::<usize>::with_capacity(aligned_len);
446 // Initialize fields of `RcBox<str>`.
447 *ptr.offset(0) = 1; // strong: Cell::new(1)
448 *ptr.offset(1) = 1; // weak: Cell::new(1)
449 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
450 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
451 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
452 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
453 Rc { ptr: Shared::new(rcbox_ptr) }
458 impl<T: ?Sized> Rc<T> {
459 /// Creates a new [`Weak`][weak] pointer to this value.
461 /// [weak]: struct.Weak.html
468 /// let five = Rc::new(5);
470 /// let weak_five = Rc::downgrade(&five);
472 #[stable(feature = "rc_weak", since = "1.4.0")]
473 pub fn downgrade(this: &Self) -> Weak<T> {
475 Weak { ptr: this.ptr }
478 /// Gets the number of [`Weak`][weak] pointers to this value.
480 /// [weak]: struct.Weak.html
485 /// #![feature(rc_counts)]
489 /// let five = Rc::new(5);
490 /// let _weak_five = Rc::downgrade(&five);
492 /// assert_eq!(1, Rc::weak_count(&five));
495 #[unstable(feature = "rc_counts", reason = "not clearly useful",
497 pub fn weak_count(this: &Self) -> usize {
501 /// Gets the number of strong (`Rc`) pointers to this value.
506 /// #![feature(rc_counts)]
510 /// let five = Rc::new(5);
511 /// let _also_five = five.clone();
513 /// assert_eq!(2, Rc::strong_count(&five));
516 #[unstable(feature = "rc_counts", reason = "not clearly useful",
518 pub fn strong_count(this: &Self) -> usize {
522 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
523 /// this inner value.
525 /// [weak]: struct.Weak.html
530 /// #![feature(rc_counts)]
534 /// let five = Rc::new(5);
536 /// assert!(Rc::is_unique(&five));
539 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
541 pub fn is_unique(this: &Self) -> bool {
542 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
545 /// Returns a mutable reference to the inner value, if there are
546 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
548 /// Returns [`None`] otherwise, because it is not safe to
549 /// mutate a shared value.
551 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
552 /// the inner value when it's shared.
554 /// [weak]: struct.Weak.html
555 /// [`None`]: ../../std/option/enum.Option.html#variant.None
556 /// [make_mut]: struct.Rc.html#method.make_mut
557 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
564 /// let mut x = Rc::new(3);
565 /// *Rc::get_mut(&mut x).unwrap() = 4;
566 /// assert_eq!(*x, 4);
568 /// let _y = x.clone();
569 /// assert!(Rc::get_mut(&mut x).is_none());
572 #[stable(feature = "rc_unique", since = "1.4.0")]
573 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
574 if Rc::is_unique(this) {
575 let inner = unsafe { &mut **this.ptr };
576 Some(&mut inner.value)
583 #[unstable(feature = "ptr_eq",
584 reason = "newly added",
586 /// Returns true if the two `Rc`s point to the same value (not
587 /// just values that compare as equal).
592 /// #![feature(ptr_eq)]
596 /// let five = Rc::new(5);
597 /// let same_five = five.clone();
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 let this_ptr: *const RcBox<T> = *this.ptr;
605 let other_ptr: *const RcBox<T> = *other.ptr;
606 this_ptr == other_ptr
610 impl<T: Clone> Rc<T> {
611 /// Makes a mutable reference into the given `Rc`.
613 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
614 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
615 /// ensure unique ownership. This is also referred to as clone-on-write.
617 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
619 /// [weak]: struct.Weak.html
620 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
621 /// [get_mut]: struct.Rc.html#method.get_mut
628 /// let mut data = Rc::new(5);
630 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
631 /// let mut other_data = data.clone(); // Won't clone inner data
632 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
633 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
634 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
636 /// // Now `data` and `other_data` point to different values.
637 /// assert_eq!(*data, 8);
638 /// assert_eq!(*other_data, 12);
641 #[stable(feature = "rc_unique", since = "1.4.0")]
642 pub fn make_mut(this: &mut Self) -> &mut T {
643 if Rc::strong_count(this) != 1 {
644 // Gotta clone the data, there are other Rcs
645 *this = Rc::new((**this).clone())
646 } else if Rc::weak_count(this) != 0 {
647 // Can just steal the data, all that's left is Weaks
649 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
650 mem::swap(this, &mut swap);
652 // Remove implicit strong-weak ref (no need to craft a fake
653 // Weak here -- we know other Weaks can clean up for us)
658 // This unsafety is ok because we're guaranteed that the pointer
659 // returned is the *only* pointer that will ever be returned to T. Our
660 // reference count is guaranteed to be 1 at this point, and we required
661 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
662 // reference to the inner value.
663 let inner = unsafe { &mut **this.ptr };
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<T: ?Sized> Deref for Rc<T> {
673 fn deref(&self) -> &T {
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T: ?Sized> Drop for Rc<T> {
682 /// This will decrement the strong reference count. If the strong reference
683 /// count reaches zero then the only other references (if any) are
684 /// [`Weak`][weak], so we `drop` the inner value.
686 /// [weak]: struct.Weak.html
695 /// impl Drop for Foo {
696 /// fn drop(&mut self) {
697 /// println!("dropped!");
701 /// let foo = Rc::new(Foo);
702 /// let foo2 = foo.clone();
704 /// drop(foo); // Doesn't print anything
705 /// drop(foo2); // Prints "dropped!"
707 #[unsafe_destructor_blind_to_params]
713 if self.strong() == 0 {
714 // destroy the contained object
715 ptr::drop_in_place(&mut (*ptr).value);
717 // remove the implicit "strong weak" pointer now that we've
718 // destroyed the contents.
721 if self.weak() == 0 {
722 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl<T: ?Sized> Clone for Rc<T> {
731 /// Makes a clone of the `Rc` pointer.
733 /// This creates another pointer to the same inner value, increasing the
734 /// strong reference count.
741 /// let five = Rc::new(5);
746 fn clone(&self) -> Rc<T> {
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<T: Default> Default for Rc<T> {
754 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
761 /// let x: Rc<i32> = Default::default();
762 /// assert_eq!(*x, 0);
765 fn default() -> Rc<T> {
766 Rc::new(Default::default())
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
772 /// Equality for two `Rc`s.
774 /// Two `Rc`s are equal if their inner values are equal.
781 /// let five = Rc::new(5);
783 /// assert!(five == Rc::new(5));
786 fn eq(&self, other: &Rc<T>) -> bool {
790 /// Inequality for two `Rc`s.
792 /// Two `Rc`s are unequal if their inner values are unequal.
799 /// let five = Rc::new(5);
801 /// assert!(five != Rc::new(6));
804 fn ne(&self, other: &Rc<T>) -> bool {
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<T: ?Sized + Eq> Eq for Rc<T> {}
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
814 /// Partial comparison for two `Rc`s.
816 /// The two are compared by calling `partial_cmp()` on their inner values.
822 /// use std::cmp::Ordering;
824 /// let five = Rc::new(5);
826 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
829 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
830 (**self).partial_cmp(&**other)
833 /// Less-than comparison for two `Rc`s.
835 /// The two are compared by calling `<` on their inner values.
842 /// let five = Rc::new(5);
844 /// assert!(five < Rc::new(6));
847 fn lt(&self, other: &Rc<T>) -> bool {
851 /// 'Less than or equal to' comparison for two `Rc`s.
853 /// The two are compared by calling `<=` on their inner values.
860 /// let five = Rc::new(5);
862 /// assert!(five <= Rc::new(5));
865 fn le(&self, other: &Rc<T>) -> bool {
869 /// Greater-than comparison for two `Rc`s.
871 /// The two are compared by calling `>` on their inner values.
878 /// let five = Rc::new(5);
880 /// assert!(five > Rc::new(4));
883 fn gt(&self, other: &Rc<T>) -> bool {
887 /// 'Greater than or equal to' comparison for two `Rc`s.
889 /// The two are compared by calling `>=` on their inner values.
896 /// let five = Rc::new(5);
898 /// assert!(five >= Rc::new(5));
901 fn ge(&self, other: &Rc<T>) -> bool {
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl<T: ?Sized + Ord> Ord for Rc<T> {
908 /// Comparison for two `Rc`s.
910 /// The two are compared by calling `cmp()` on their inner values.
916 /// use std::cmp::Ordering;
918 /// let five = Rc::new(5);
920 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
923 fn cmp(&self, other: &Rc<T>) -> Ordering {
924 (**self).cmp(&**other)
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<T: ?Sized + Hash> Hash for Rc<T> {
930 fn hash<H: Hasher>(&self, state: &mut H) {
931 (**self).hash(state);
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
937 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
938 fmt::Display::fmt(&**self, f)
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
945 fmt::Debug::fmt(&**self, f)
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<T: ?Sized> fmt::Pointer for Rc<T> {
951 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
952 fmt::Pointer::fmt(&*self.ptr, f)
956 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
957 impl<T> From<T> for Rc<T> {
958 fn from(t: T) -> Self {
963 /// A weak version of [`Rc`][rc].
965 /// `Weak` pointers do not count towards determining if the inner value
966 /// should be dropped.
968 /// The typical way to obtain a `Weak` pointer is to call
969 /// [`Rc::downgrade`][downgrade].
971 /// See the [module-level documentation](./index.html) for more details.
973 /// [rc]: struct.Rc.html
974 /// [downgrade]: struct.Rc.html#method.downgrade
975 #[stable(feature = "rc_weak", since = "1.4.0")]
976 pub struct Weak<T: ?Sized> {
977 ptr: Shared<RcBox<T>>,
980 #[stable(feature = "rc_weak", since = "1.4.0")]
981 impl<T: ?Sized> !marker::Send for Weak<T> {}
982 #[stable(feature = "rc_weak", since = "1.4.0")]
983 impl<T: ?Sized> !marker::Sync for Weak<T> {}
985 #[unstable(feature = "coerce_unsized", issue = "27732")]
986 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
989 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
991 /// This allocates memory for `T`, but does not initialize it. Calling
992 /// [`upgrade`][upgrade] on the return value always gives
993 /// [`None`][option].
995 /// [upgrade]: struct.Weak.html#method.upgrade
996 /// [option]: ../../std/option/enum.Option.html
1001 /// use std::rc::Weak;
1003 /// let empty: Weak<i64> = Weak::new();
1004 /// assert!(empty.upgrade().is_none());
1006 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1007 pub fn new() -> Weak<T> {
1010 ptr: Shared::new(Box::into_raw(box RcBox {
1011 strong: Cell::new(0),
1013 value: uninitialized(),
1020 impl<T: ?Sized> Weak<T> {
1021 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
1023 /// Returns [`None`][option] if the strong count has reached zero and the
1024 /// inner value was destroyed.
1026 /// [rc]: struct.Rc.html
1027 /// [option]: ../../std/option/enum.Option.html
1032 /// use std::rc::Rc;
1034 /// let five = Rc::new(5);
1036 /// let weak_five = Rc::downgrade(&five);
1038 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1039 /// assert!(strong_five.is_some());
1041 /// // Destroy all strong pointers.
1042 /// drop(strong_five);
1045 /// assert!(weak_five.upgrade().is_none());
1047 #[stable(feature = "rc_weak", since = "1.4.0")]
1048 pub fn upgrade(&self) -> Option<Rc<T>> {
1049 if self.strong() == 0 {
1053 Some(Rc { ptr: self.ptr })
1058 #[stable(feature = "rc_weak", since = "1.4.0")]
1059 impl<T: ?Sized> Drop for Weak<T> {
1060 /// Drops the `Weak` pointer.
1062 /// This will decrement the weak reference count.
1067 /// use std::rc::Rc;
1071 /// impl Drop for Foo {
1072 /// fn drop(&mut self) {
1073 /// println!("dropped!");
1077 /// let foo = Rc::new(Foo);
1078 /// let weak_foo = Rc::downgrade(&foo);
1079 /// let other_weak_foo = weak_foo.clone();
1081 /// drop(weak_foo); // Doesn't print anything
1082 /// drop(foo); // Prints "dropped!"
1084 /// assert!(other_weak_foo.upgrade().is_none());
1086 fn drop(&mut self) {
1088 let ptr = *self.ptr;
1091 // the weak count starts at 1, and will only go to zero if all
1092 // the strong pointers have disappeared.
1093 if self.weak() == 0 {
1094 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1100 #[stable(feature = "rc_weak", since = "1.4.0")]
1101 impl<T: ?Sized> Clone for Weak<T> {
1102 /// Makes a clone of the `Weak` pointer.
1104 /// This creates another pointer to the same inner value, increasing the
1105 /// weak reference count.
1110 /// use std::rc::Rc;
1112 /// let weak_five = Rc::downgrade(&Rc::new(5));
1114 /// weak_five.clone();
1117 fn clone(&self) -> Weak<T> {
1119 Weak { ptr: self.ptr }
1123 #[stable(feature = "rc_weak", since = "1.4.0")]
1124 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1130 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1131 impl<T> Default for Weak<T> {
1132 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1134 /// This allocates memory for `T`, but does not initialize it. Calling
1135 /// [`upgrade`][upgrade] on the return value always gives
1136 /// [`None`][option].
1138 /// [upgrade]: struct.Weak.html#method.upgrade
1139 /// [option]: ../../std/option/enum.Option.html
1144 /// use std::rc::Weak;
1146 /// let empty: Weak<i64> = Default::default();
1147 /// assert!(empty.upgrade().is_none());
1149 fn default() -> Weak<T> {
1154 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1155 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1156 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1157 // We abort because this is such a degenerate scenario that we don't care about
1158 // what happens -- no real program should ever experience this.
1160 // This should have negligible overhead since you don't actually need to
1161 // clone these much in Rust thanks to ownership and move-semantics.
1164 trait RcBoxPtr<T: ?Sized> {
1165 fn inner(&self) -> &RcBox<T>;
1168 fn strong(&self) -> usize {
1169 self.inner().strong.get()
1173 fn inc_strong(&self) {
1174 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1178 fn dec_strong(&self) {
1179 self.inner().strong.set(self.strong() - 1);
1183 fn weak(&self) -> usize {
1184 self.inner().weak.get()
1188 fn inc_weak(&self) {
1189 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1193 fn dec_weak(&self) {
1194 self.inner().weak.set(self.weak() - 1);
1198 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1200 fn inner(&self) -> &RcBox<T> {
1202 // Safe to assume this here, as if it weren't true, we'd be breaking
1203 // the contract anyway.
1204 // This allows the null check to be elided in the destructor if we
1205 // manipulated the reference count in the same function.
1206 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1212 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1214 fn inner(&self) -> &RcBox<T> {
1216 // Safe to assume this here, as if it weren't true, we'd be breaking
1217 // the contract anyway.
1218 // This allows the null check to be elided in the destructor if we
1219 // manipulated the reference count in the same function.
1220 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1228 use super::{Rc, Weak};
1229 use std::boxed::Box;
1230 use std::cell::RefCell;
1231 use std::option::Option;
1232 use std::option::Option::{None, Some};
1233 use std::result::Result::{Err, Ok};
1235 use std::clone::Clone;
1236 use std::convert::From;
1240 let x = Rc::new(RefCell::new(5));
1242 *x.borrow_mut() = 20;
1243 assert_eq!(*y.borrow(), 20);
1253 fn test_simple_clone() {
1261 fn test_destructor() {
1262 let x: Rc<Box<_>> = Rc::new(box 5);
1269 let y = Rc::downgrade(&x);
1270 assert!(y.upgrade().is_some());
1276 let y = Rc::downgrade(&x);
1278 assert!(y.upgrade().is_none());
1282 fn weak_self_cyclic() {
1284 x: RefCell<Option<Weak<Cycle>>>,
1287 let a = Rc::new(Cycle { x: RefCell::new(None) });
1288 let b = Rc::downgrade(&a.clone());
1289 *a.x.borrow_mut() = Some(b);
1291 // hopefully we don't double-free (or leak)...
1297 assert!(Rc::is_unique(&x));
1299 assert!(!Rc::is_unique(&x));
1301 assert!(Rc::is_unique(&x));
1302 let w = Rc::downgrade(&x);
1303 assert!(!Rc::is_unique(&x));
1305 assert!(Rc::is_unique(&x));
1309 fn test_strong_count() {
1311 assert!(Rc::strong_count(&a) == 1);
1312 let w = Rc::downgrade(&a);
1313 assert!(Rc::strong_count(&a) == 1);
1314 let b = w.upgrade().expect("upgrade of live rc failed");
1315 assert!(Rc::strong_count(&b) == 2);
1316 assert!(Rc::strong_count(&a) == 2);
1319 assert!(Rc::strong_count(&b) == 1);
1321 assert!(Rc::strong_count(&b) == 2);
1322 assert!(Rc::strong_count(&c) == 2);
1326 fn test_weak_count() {
1328 assert!(Rc::strong_count(&a) == 1);
1329 assert!(Rc::weak_count(&a) == 0);
1330 let w = Rc::downgrade(&a);
1331 assert!(Rc::strong_count(&a) == 1);
1332 assert!(Rc::weak_count(&a) == 1);
1334 assert!(Rc::strong_count(&a) == 1);
1335 assert!(Rc::weak_count(&a) == 0);
1337 assert!(Rc::strong_count(&a) == 2);
1338 assert!(Rc::weak_count(&a) == 0);
1345 assert_eq!(Rc::try_unwrap(x), Ok(3));
1348 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1350 let _w = Rc::downgrade(&x);
1351 assert_eq!(Rc::try_unwrap(x), Ok(5));
1355 fn into_from_raw() {
1356 let x = Rc::new(box "hello");
1359 let x_ptr = Rc::into_raw(x);
1362 assert_eq!(**x_ptr, "hello");
1364 let x = Rc::from_raw(x_ptr);
1365 assert_eq!(**x, "hello");
1367 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1373 let mut x = Rc::new(3);
1374 *Rc::get_mut(&mut x).unwrap() = 4;
1377 assert!(Rc::get_mut(&mut x).is_none());
1379 assert!(Rc::get_mut(&mut x).is_some());
1380 let _w = Rc::downgrade(&x);
1381 assert!(Rc::get_mut(&mut x).is_none());
1385 fn test_cowrc_clone_make_unique() {
1386 let mut cow0 = Rc::new(75);
1387 let mut cow1 = cow0.clone();
1388 let mut cow2 = cow1.clone();
1390 assert!(75 == *Rc::make_mut(&mut cow0));
1391 assert!(75 == *Rc::make_mut(&mut cow1));
1392 assert!(75 == *Rc::make_mut(&mut cow2));
1394 *Rc::make_mut(&mut cow0) += 1;
1395 *Rc::make_mut(&mut cow1) += 2;
1396 *Rc::make_mut(&mut cow2) += 3;
1398 assert!(76 == *cow0);
1399 assert!(77 == *cow1);
1400 assert!(78 == *cow2);
1402 // none should point to the same backing memory
1403 assert!(*cow0 != *cow1);
1404 assert!(*cow0 != *cow2);
1405 assert!(*cow1 != *cow2);
1409 fn test_cowrc_clone_unique2() {
1410 let mut cow0 = Rc::new(75);
1411 let cow1 = cow0.clone();
1412 let cow2 = cow1.clone();
1414 assert!(75 == *cow0);
1415 assert!(75 == *cow1);
1416 assert!(75 == *cow2);
1418 *Rc::make_mut(&mut cow0) += 1;
1420 assert!(76 == *cow0);
1421 assert!(75 == *cow1);
1422 assert!(75 == *cow2);
1424 // cow1 and cow2 should share the same contents
1425 // cow0 should have a unique reference
1426 assert!(*cow0 != *cow1);
1427 assert!(*cow0 != *cow2);
1428 assert!(*cow1 == *cow2);
1432 fn test_cowrc_clone_weak() {
1433 let mut cow0 = Rc::new(75);
1434 let cow1_weak = Rc::downgrade(&cow0);
1436 assert!(75 == *cow0);
1437 assert!(75 == *cow1_weak.upgrade().unwrap());
1439 *Rc::make_mut(&mut cow0) += 1;
1441 assert!(76 == *cow0);
1442 assert!(cow1_weak.upgrade().is_none());
1447 let foo = Rc::new(75);
1448 assert_eq!(format!("{:?}", foo), "75");
1453 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1454 assert_eq!(foo, foo.clone());
1458 fn test_from_owned() {
1460 let foo_rc = Rc::from(foo);
1461 assert!(123 == *foo_rc);
1465 fn test_new_weak() {
1466 let foo: Weak<usize> = Weak::new();
1467 assert!(foo.upgrade().is_none());
1472 let five = Rc::new(5);
1473 let same_five = five.clone();
1474 let other_five = Rc::new(5);
1476 assert!(Rc::ptr_eq(&five, &same_five));
1477 assert!(!Rc::ptr_eq(&five, &other_five));
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1483 fn borrow(&self) -> &T {
1488 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1489 impl<T: ?Sized> AsRef<T> for Rc<T> {
1490 fn as_ref(&self) -> &T {