1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! Single-threaded reference-counting pointers.
15 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
16 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
17 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
18 //! given value is destroyed, the pointed-to value is also destroyed.
20 //! Shared references in Rust disallow mutation by default, and [`Rc`]
21 //! is no exception: you cannot obtain a mutable reference to
22 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
23 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
24 //! inside an Rc][mutability].
26 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
27 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
28 //! does not implement [`Send`][send]. As a result, the Rust compiler
29 //! will check *at compile time* that you are not sending [`Rc`]s between
30 //! threads. If you need multi-threaded, atomic reference counting, use
31 //! [`sync::Arc`][arc].
33 //! The [`downgrade`][downgrade] method can be used to create a non-owning
34 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
35 //! to an [`Rc`], but this will return [`None`] if the value has
36 //! already been dropped.
38 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
39 //! [`Weak`] is used to break cycles. For example, a tree could have strong
40 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
41 //! children back to their parents.
43 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
44 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
45 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
46 //! functions][assoc], called using function-like syntax:
50 //! let my_rc = Rc::new(());
52 //! Rc::downgrade(&my_rc);
55 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
56 //! already been destroyed.
60 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
61 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
62 //! unique ownership, because more than one gadget may belong to the same
63 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
64 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
71 //! // ...other fields
77 //! // ...other fields
81 //! // Create a reference-counted `Owner`.
82 //! let gadget_owner: Rc<Owner> = Rc::new(
84 //! name: "Gadget Man".to_string(),
88 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
89 //! // value gives us a new pointer to the same `Owner` value, incrementing
90 //! // the reference count in the process.
91 //! let gadget1 = Gadget {
93 //! owner: gadget_owner.clone(),
95 //! let gadget2 = Gadget {
97 //! owner: gadget_owner.clone(),
100 //! // Dispose of our local variable `gadget_owner`.
101 //! drop(gadget_owner);
103 //! // Despite dropping `gadget_owner`, we're still able to print out the name
104 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
105 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
106 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
107 //! // allocated. The field projection `gadget1.owner.name` works because
108 //! // `Rc<Owner>` automatically dereferences to `Owner`.
109 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
110 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
112 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
113 //! // with them the last counted references to our `Owner`. Gadget Man now
114 //! // gets destroyed as well.
118 //! If our requirements change, and we also need to be able to traverse from
119 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
120 //! to `Gadget` introduces a cycle between the values. This means that their
121 //! reference counts can never reach 0, and the values will remain allocated
122 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
125 //! Rust actually makes it somewhat difficult to produce this loop in the first
126 //! place. In order to end up with two values that point at each other, one of
127 //! them needs to be mutable. This is difficult because [`Rc`] enforces
128 //! memory safety by only giving out shared references to the value it wraps,
129 //! and these don't allow direct mutation. We need to wrap the part of the
130 //! value we wish to mutate in a [`RefCell`], which provides *interior
131 //! mutability*: a method to achieve mutability through a shared reference.
132 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
136 //! use std::rc::Weak;
137 //! use std::cell::RefCell;
141 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
142 //! // ...other fields
147 //! owner: Rc<Owner>,
148 //! // ...other fields
152 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
153 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
154 //! // a shared reference.
155 //! let gadget_owner: Rc<Owner> = Rc::new(
157 //! name: "Gadget Man".to_string(),
158 //! gadgets: RefCell::new(vec![]),
162 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
163 //! let gadget1 = Rc::new(
166 //! owner: gadget_owner.clone(),
169 //! let gadget2 = Rc::new(
172 //! owner: gadget_owner.clone(),
176 //! // Add the `Gadget`s to their `Owner`.
178 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
179 //! gadgets.push(Rc::downgrade(&gadget1));
180 //! gadgets.push(Rc::downgrade(&gadget2));
182 //! // `RefCell` dynamic borrow ends here.
185 //! // Iterate over our `Gadget`s, printing their details out.
186 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
188 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
189 //! // guarantee the value is still allocated, we need to call
190 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
192 //! // In this case we know the value still exists, so we simply
193 //! // `unwrap` the `Option`. In a more complicated program, you might
194 //! // need graceful error handling for a `None` result.
196 //! let gadget = gadget_weak.upgrade().unwrap();
197 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
200 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
201 //! // are destroyed. There are now no strong (`Rc`) pointers to the
202 //! // gadgets, so they are destroyed. This zeroes the reference count on
203 //! // Gadget Man, so he gets destroyed as well.
207 //! [`Rc`]: struct.Rc.html
208 //! [`Weak`]: struct.Weak.html
209 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
210 //! [`Cell`]: ../../std/cell/struct.Cell.html
211 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
212 //! [send]: ../../std/marker/trait.Send.html
213 //! [arc]: ../../std/sync/struct.Arc.html
214 //! [`Deref`]: ../../std/ops/trait.Deref.html
215 //! [downgrade]: struct.Rc.html#method.downgrade
216 //! [upgrade]: struct.Weak.html#method.upgrade
217 //! [`None`]: ../../std/option/enum.Option.html#variant.None
218 //! [assoc]: ../../book/method-syntax.html#associated-functions
219 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
221 #![stable(feature = "rust1", since = "1.0.0")]
229 use core::cell::Cell;
230 use core::cmp::Ordering;
232 use core::hash::{Hash, Hasher};
233 use core::intrinsics::{abort, assume};
235 use core::marker::Unsize;
236 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
237 use core::ops::Deref;
238 use core::ops::CoerceUnsized;
239 use core::ptr::{self, Shared};
240 use core::convert::From;
242 use heap::deallocate;
245 struct RcBox<T: ?Sized> {
252 /// A single-threaded reference-counting pointer.
254 /// See the [module-level documentation](./index.html) for more details.
256 /// The inherent methods of `Rc` are all associated functions, which means
257 /// that you have to call them as e.g. [`Rc::get_mut(&value)`][get_mut] instead of
258 /// `value.get_mut()`. This avoids conflicts with methods of the inner
261 /// [get_mut]: #method.get_mut
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub struct Rc<T: ?Sized> {
264 ptr: Shared<RcBox<T>>,
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T: ?Sized> !marker::Send for Rc<T> {}
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T: ?Sized> !marker::Sync for Rc<T> {}
272 #[unstable(feature = "coerce_unsized", issue = "27732")]
273 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
276 /// Constructs a new `Rc<T>`.
283 /// let five = Rc::new(5);
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn new(value: T) -> Rc<T> {
289 // there is an implicit weak pointer owned by all the strong
290 // pointers, which ensures that the weak destructor never frees
291 // the allocation while the strong destructor is running, even
292 // if the weak pointer is stored inside the strong one.
293 ptr: Shared::new(Box::into_raw(box RcBox {
294 strong: Cell::new(1),
302 /// Returns the contained value, if the `Rc` has exactly one strong reference.
304 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
307 /// This will succeed even if there are outstanding weak references.
309 /// [result]: ../../std/result/enum.Result.html
316 /// let x = Rc::new(3);
317 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
319 /// let x = Rc::new(4);
320 /// let _y = x.clone();
321 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
324 #[stable(feature = "rc_unique", since = "1.4.0")]
325 pub fn try_unwrap(this: Self) -> Result<T, Self> {
326 if Rc::strong_count(&this) == 1 {
328 let val = ptr::read(&*this); // copy the contained object
330 // Indicate to Weaks that they can't be promoted by decrememting
331 // the strong count, and then remove the implicit "strong weak"
332 // pointer while also handling drop logic by just crafting a
335 let _weak = Weak { ptr: this.ptr };
344 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
347 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
348 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
349 #[unstable(feature = "rc_would_unwrap",
350 reason = "just added for niche usecase",
352 #[rustc_deprecated(since = "1.15.0", reason = "too niche; use `strong_count` instead")]
353 pub fn would_unwrap(this: &Self) -> bool {
354 Rc::strong_count(&this) == 1
357 /// Consumes the `Rc`, returning the wrapped pointer.
359 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
360 /// [`Rc::from_raw`][from_raw].
362 /// [from_raw]: struct.Rc.html#method.from_raw
367 /// #![feature(rc_raw)]
371 /// let x = Rc::new(10);
372 /// let x_ptr = Rc::into_raw(x);
373 /// assert_eq!(unsafe { *x_ptr }, 10);
375 #[unstable(feature = "rc_raw", issue = "37197")]
376 pub fn into_raw(this: Self) -> *mut T {
377 let ptr = unsafe { &mut (**this.ptr).value as *mut _ };
382 /// Constructs an `Rc` from a raw pointer.
384 /// The raw pointer must have been previously returned by a call to a
385 /// [`Rc::into_raw`][into_raw].
387 /// This function is unsafe because improper use may lead to memory problems. For example, a
388 /// double-free may occur if the function is called twice on the same raw pointer.
390 /// [into_raw]: struct.Rc.html#method.into_raw
395 /// #![feature(rc_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 #[unstable(feature = "rc_raw", issue = "37197")]
413 pub unsafe fn from_raw(ptr: *mut 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.
416 Rc { ptr: Shared::new((ptr as *mut u8).offset(-offset_of!(RcBox<T>, value)) as *mut _) }
421 /// Constructs a new `Rc<str>` from a string slice.
423 #[unstable(feature = "rustc_private",
424 reason = "for internal use in rustc",
426 pub fn __from_str(value: &str) -> Rc<str> {
428 // Allocate enough space for `RcBox<str>`.
429 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
430 let vec = RawVec::<usize>::with_capacity(aligned_len);
433 // Initialize fields of `RcBox<str>`.
434 *ptr.offset(0) = 1; // strong: Cell::new(1)
435 *ptr.offset(1) = 1; // weak: Cell::new(1)
436 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
437 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
438 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
439 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
440 Rc { ptr: Shared::new(rcbox_ptr) }
445 impl<T: ?Sized> Rc<T> {
446 /// Creates a new [`Weak`][weak] pointer to this value.
448 /// [weak]: struct.Weak.html
455 /// let five = Rc::new(5);
457 /// let weak_five = Rc::downgrade(&five);
459 #[stable(feature = "rc_weak", since = "1.4.0")]
460 pub fn downgrade(this: &Self) -> Weak<T> {
462 Weak { ptr: this.ptr }
465 /// Gets the number of [`Weak`][weak] pointers to this value.
467 /// [weak]: struct.Weak.html
474 /// let five = Rc::new(5);
475 /// let _weak_five = Rc::downgrade(&five);
477 /// assert_eq!(1, Rc::weak_count(&five));
480 #[stable(feature = "rc_counts", since = "1.15.0")]
481 pub fn weak_count(this: &Self) -> usize {
485 /// Gets the number of strong (`Rc`) pointers to this value.
492 /// let five = Rc::new(5);
493 /// let _also_five = five.clone();
495 /// assert_eq!(2, Rc::strong_count(&five));
498 #[stable(feature = "rc_counts", since = "1.15.0")]
499 pub fn strong_count(this: &Self) -> usize {
503 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
504 /// this inner value.
506 /// [weak]: struct.Weak.html
508 #[unstable(feature = "is_unique", reason = "uniqueness has unclear meaning",
510 #[rustc_deprecated(since = "1.15.0",
511 reason = "too niche; use `strong_count` and `weak_count` instead")]
512 pub fn is_unique(this: &Self) -> bool {
513 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
516 /// Returns a mutable reference to the inner value, if there are
517 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
519 /// Returns [`None`] otherwise, because it is not safe to
520 /// mutate a shared value.
522 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
523 /// the inner value when it's shared.
525 /// [weak]: struct.Weak.html
526 /// [`None`]: ../../std/option/enum.Option.html#variant.None
527 /// [make_mut]: struct.Rc.html#method.make_mut
528 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
535 /// let mut x = Rc::new(3);
536 /// *Rc::get_mut(&mut x).unwrap() = 4;
537 /// assert_eq!(*x, 4);
539 /// let _y = x.clone();
540 /// assert!(Rc::get_mut(&mut x).is_none());
543 #[stable(feature = "rc_unique", since = "1.4.0")]
544 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
545 if Rc::is_unique(this) {
546 let inner = unsafe { &mut **this.ptr };
547 Some(&mut inner.value)
554 #[unstable(feature = "ptr_eq",
555 reason = "newly added",
557 /// Returns true if the two `Rc`s point to the same value (not
558 /// just values that compare as equal).
563 /// #![feature(ptr_eq)]
567 /// let five = Rc::new(5);
568 /// let same_five = five.clone();
569 /// let other_five = Rc::new(5);
571 /// assert!(Rc::ptr_eq(&five, &same_five));
572 /// assert!(!Rc::ptr_eq(&five, &other_five));
574 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
575 let this_ptr: *const RcBox<T> = *this.ptr;
576 let other_ptr: *const RcBox<T> = *other.ptr;
577 this_ptr == other_ptr
581 impl<T: Clone> Rc<T> {
582 /// Makes a mutable reference into the given `Rc`.
584 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
585 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
586 /// ensure unique ownership. This is also referred to as clone-on-write.
588 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
590 /// [weak]: struct.Weak.html
591 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
592 /// [get_mut]: struct.Rc.html#method.get_mut
599 /// let mut data = Rc::new(5);
601 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
602 /// let mut other_data = data.clone(); // Won't clone inner data
603 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
604 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
605 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
607 /// // Now `data` and `other_data` point to different values.
608 /// assert_eq!(*data, 8);
609 /// assert_eq!(*other_data, 12);
612 #[stable(feature = "rc_unique", since = "1.4.0")]
613 pub fn make_mut(this: &mut Self) -> &mut T {
614 if Rc::strong_count(this) != 1 {
615 // Gotta clone the data, there are other Rcs
616 *this = Rc::new((**this).clone())
617 } else if Rc::weak_count(this) != 0 {
618 // Can just steal the data, all that's left is Weaks
620 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
621 mem::swap(this, &mut swap);
623 // Remove implicit strong-weak ref (no need to craft a fake
624 // Weak here -- we know other Weaks can clean up for us)
629 // This unsafety is ok because we're guaranteed that the pointer
630 // returned is the *only* pointer that will ever be returned to T. Our
631 // reference count is guaranteed to be 1 at this point, and we required
632 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
633 // reference to the inner value.
634 let inner = unsafe { &mut **this.ptr };
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<T: ?Sized> Deref for Rc<T> {
644 fn deref(&self) -> &T {
649 #[stable(feature = "rust1", since = "1.0.0")]
650 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
653 /// This will decrement the strong reference count. If the strong reference
654 /// count reaches zero then the only other references (if any) are
655 /// [`Weak`][weak], so we `drop` the inner value.
657 /// [weak]: struct.Weak.html
666 /// impl Drop for Foo {
667 /// fn drop(&mut self) {
668 /// println!("dropped!");
672 /// let foo = Rc::new(Foo);
673 /// let foo2 = foo.clone();
675 /// drop(foo); // Doesn't print anything
676 /// drop(foo2); // Prints "dropped!"
683 if self.strong() == 0 {
684 // destroy the contained object
685 ptr::drop_in_place(&mut (*ptr).value);
687 // remove the implicit "strong weak" pointer now that we've
688 // destroyed the contents.
691 if self.weak() == 0 {
692 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<T: ?Sized> Clone for Rc<T> {
701 /// Makes a clone of the `Rc` pointer.
703 /// This creates another pointer to the same inner value, increasing the
704 /// strong reference count.
711 /// let five = Rc::new(5);
716 fn clone(&self) -> Rc<T> {
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<T: Default> Default for Rc<T> {
724 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
731 /// let x: Rc<i32> = Default::default();
732 /// assert_eq!(*x, 0);
735 fn default() -> Rc<T> {
736 Rc::new(Default::default())
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
742 /// Equality for two `Rc`s.
744 /// Two `Rc`s are equal if their inner values are equal.
751 /// let five = Rc::new(5);
753 /// assert!(five == Rc::new(5));
756 fn eq(&self, other: &Rc<T>) -> bool {
760 /// Inequality for two `Rc`s.
762 /// Two `Rc`s are unequal if their inner values are unequal.
769 /// let five = Rc::new(5);
771 /// assert!(five != Rc::new(6));
774 fn ne(&self, other: &Rc<T>) -> bool {
779 #[stable(feature = "rust1", since = "1.0.0")]
780 impl<T: ?Sized + Eq> Eq for Rc<T> {}
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
784 /// Partial comparison for two `Rc`s.
786 /// The two are compared by calling `partial_cmp()` on their inner values.
792 /// use std::cmp::Ordering;
794 /// let five = Rc::new(5);
796 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
799 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
800 (**self).partial_cmp(&**other)
803 /// Less-than comparison for two `Rc`s.
805 /// The two are compared by calling `<` on their inner values.
812 /// let five = Rc::new(5);
814 /// assert!(five < Rc::new(6));
817 fn lt(&self, other: &Rc<T>) -> bool {
821 /// 'Less than or equal to' comparison for two `Rc`s.
823 /// The two are compared by calling `<=` on their inner values.
830 /// let five = Rc::new(5);
832 /// assert!(five <= Rc::new(5));
835 fn le(&self, other: &Rc<T>) -> bool {
839 /// Greater-than comparison for two `Rc`s.
841 /// The two are compared by calling `>` on their inner values.
848 /// let five = Rc::new(5);
850 /// assert!(five > Rc::new(4));
853 fn gt(&self, other: &Rc<T>) -> bool {
857 /// 'Greater than or equal to' comparison for two `Rc`s.
859 /// The two are compared by calling `>=` on their inner values.
866 /// let five = Rc::new(5);
868 /// assert!(five >= Rc::new(5));
871 fn ge(&self, other: &Rc<T>) -> bool {
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<T: ?Sized + Ord> Ord for Rc<T> {
878 /// Comparison for two `Rc`s.
880 /// The two are compared by calling `cmp()` on their inner values.
886 /// use std::cmp::Ordering;
888 /// let five = Rc::new(5);
890 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
893 fn cmp(&self, other: &Rc<T>) -> Ordering {
894 (**self).cmp(&**other)
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<T: ?Sized + Hash> Hash for Rc<T> {
900 fn hash<H: Hasher>(&self, state: &mut H) {
901 (**self).hash(state);
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
907 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
908 fmt::Display::fmt(&**self, f)
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
915 fmt::Debug::fmt(&**self, f)
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl<T: ?Sized> fmt::Pointer for Rc<T> {
921 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
922 fmt::Pointer::fmt(&*self.ptr, f)
926 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
927 impl<T> From<T> for Rc<T> {
928 fn from(t: T) -> Self {
933 /// A weak version of [`Rc`][rc].
935 /// `Weak` pointers do not count towards determining if the inner value
936 /// should be dropped.
938 /// The typical way to obtain a `Weak` pointer is to call
939 /// [`Rc::downgrade`][downgrade].
941 /// See the [module-level documentation](./index.html) for more details.
943 /// [rc]: struct.Rc.html
944 /// [downgrade]: struct.Rc.html#method.downgrade
945 #[stable(feature = "rc_weak", since = "1.4.0")]
946 pub struct Weak<T: ?Sized> {
947 ptr: Shared<RcBox<T>>,
950 #[stable(feature = "rc_weak", since = "1.4.0")]
951 impl<T: ?Sized> !marker::Send for Weak<T> {}
952 #[stable(feature = "rc_weak", since = "1.4.0")]
953 impl<T: ?Sized> !marker::Sync for Weak<T> {}
955 #[unstable(feature = "coerce_unsized", issue = "27732")]
956 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
959 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
961 /// This allocates memory for `T`, but does not initialize it. Calling
962 /// [`upgrade`][upgrade] on the return value always gives
963 /// [`None`][option].
965 /// [upgrade]: struct.Weak.html#method.upgrade
966 /// [option]: ../../std/option/enum.Option.html
971 /// use std::rc::Weak;
973 /// let empty: Weak<i64> = Weak::new();
974 /// assert!(empty.upgrade().is_none());
976 #[stable(feature = "downgraded_weak", since = "1.10.0")]
977 pub fn new() -> Weak<T> {
980 ptr: Shared::new(Box::into_raw(box RcBox {
981 strong: Cell::new(0),
983 value: uninitialized(),
990 impl<T: ?Sized> Weak<T> {
991 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
993 /// Returns [`None`][option] if the strong count has reached zero and the
994 /// inner value was destroyed.
996 /// [rc]: struct.Rc.html
997 /// [option]: ../../std/option/enum.Option.html
1002 /// use std::rc::Rc;
1004 /// let five = Rc::new(5);
1006 /// let weak_five = Rc::downgrade(&five);
1008 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1009 /// assert!(strong_five.is_some());
1011 /// // Destroy all strong pointers.
1012 /// drop(strong_five);
1015 /// assert!(weak_five.upgrade().is_none());
1017 #[stable(feature = "rc_weak", since = "1.4.0")]
1018 pub fn upgrade(&self) -> Option<Rc<T>> {
1019 if self.strong() == 0 {
1023 Some(Rc { ptr: self.ptr })
1028 #[stable(feature = "rc_weak", since = "1.4.0")]
1029 impl<T: ?Sized> Drop for Weak<T> {
1030 /// Drops the `Weak` pointer.
1032 /// This will decrement the weak reference count.
1037 /// use std::rc::Rc;
1041 /// impl Drop for Foo {
1042 /// fn drop(&mut self) {
1043 /// println!("dropped!");
1047 /// let foo = Rc::new(Foo);
1048 /// let weak_foo = Rc::downgrade(&foo);
1049 /// let other_weak_foo = weak_foo.clone();
1051 /// drop(weak_foo); // Doesn't print anything
1052 /// drop(foo); // Prints "dropped!"
1054 /// assert!(other_weak_foo.upgrade().is_none());
1056 fn drop(&mut self) {
1058 let ptr = *self.ptr;
1061 // the weak count starts at 1, and will only go to zero if all
1062 // the strong pointers have disappeared.
1063 if self.weak() == 0 {
1064 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1070 #[stable(feature = "rc_weak", since = "1.4.0")]
1071 impl<T: ?Sized> Clone for Weak<T> {
1072 /// Makes a clone of the `Weak` pointer.
1074 /// This creates another pointer to the same inner value, increasing the
1075 /// weak reference count.
1080 /// use std::rc::Rc;
1082 /// let weak_five = Rc::downgrade(&Rc::new(5));
1084 /// weak_five.clone();
1087 fn clone(&self) -> Weak<T> {
1089 Weak { ptr: self.ptr }
1093 #[stable(feature = "rc_weak", since = "1.4.0")]
1094 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1095 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1100 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1101 impl<T> Default for Weak<T> {
1102 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1104 /// This allocates memory for `T`, but does not initialize it. Calling
1105 /// [`upgrade`][upgrade] on the return value always gives
1106 /// [`None`][option].
1108 /// [upgrade]: struct.Weak.html#method.upgrade
1109 /// [option]: ../../std/option/enum.Option.html
1114 /// use std::rc::Weak;
1116 /// let empty: Weak<i64> = Default::default();
1117 /// assert!(empty.upgrade().is_none());
1119 fn default() -> Weak<T> {
1124 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1125 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1126 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1127 // We abort because this is such a degenerate scenario that we don't care about
1128 // what happens -- no real program should ever experience this.
1130 // This should have negligible overhead since you don't actually need to
1131 // clone these much in Rust thanks to ownership and move-semantics.
1134 trait RcBoxPtr<T: ?Sized> {
1135 fn inner(&self) -> &RcBox<T>;
1138 fn strong(&self) -> usize {
1139 self.inner().strong.get()
1143 fn inc_strong(&self) {
1144 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1148 fn dec_strong(&self) {
1149 self.inner().strong.set(self.strong() - 1);
1153 fn weak(&self) -> usize {
1154 self.inner().weak.get()
1158 fn inc_weak(&self) {
1159 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1163 fn dec_weak(&self) {
1164 self.inner().weak.set(self.weak() - 1);
1168 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1170 fn inner(&self) -> &RcBox<T> {
1172 // Safe to assume this here, as if it weren't true, we'd be breaking
1173 // the contract anyway.
1174 // This allows the null check to be elided in the destructor if we
1175 // manipulated the reference count in the same function.
1176 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1182 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1184 fn inner(&self) -> &RcBox<T> {
1186 // Safe to assume this here, as if it weren't true, we'd be breaking
1187 // the contract anyway.
1188 // This allows the null check to be elided in the destructor if we
1189 // manipulated the reference count in the same function.
1190 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1198 use super::{Rc, Weak};
1199 use std::boxed::Box;
1200 use std::cell::RefCell;
1201 use std::option::Option;
1202 use std::option::Option::{None, Some};
1203 use std::result::Result::{Err, Ok};
1205 use std::clone::Clone;
1206 use std::convert::From;
1210 let x = Rc::new(RefCell::new(5));
1212 *x.borrow_mut() = 20;
1213 assert_eq!(*y.borrow(), 20);
1223 fn test_simple_clone() {
1231 fn test_destructor() {
1232 let x: Rc<Box<_>> = Rc::new(box 5);
1239 let y = Rc::downgrade(&x);
1240 assert!(y.upgrade().is_some());
1246 let y = Rc::downgrade(&x);
1248 assert!(y.upgrade().is_none());
1252 fn weak_self_cyclic() {
1254 x: RefCell<Option<Weak<Cycle>>>,
1257 let a = Rc::new(Cycle { x: RefCell::new(None) });
1258 let b = Rc::downgrade(&a.clone());
1259 *a.x.borrow_mut() = Some(b);
1261 // hopefully we don't double-free (or leak)...
1267 assert!(Rc::is_unique(&x));
1269 assert!(!Rc::is_unique(&x));
1271 assert!(Rc::is_unique(&x));
1272 let w = Rc::downgrade(&x);
1273 assert!(!Rc::is_unique(&x));
1275 assert!(Rc::is_unique(&x));
1279 fn test_strong_count() {
1281 assert!(Rc::strong_count(&a) == 1);
1282 let w = Rc::downgrade(&a);
1283 assert!(Rc::strong_count(&a) == 1);
1284 let b = w.upgrade().expect("upgrade of live rc failed");
1285 assert!(Rc::strong_count(&b) == 2);
1286 assert!(Rc::strong_count(&a) == 2);
1289 assert!(Rc::strong_count(&b) == 1);
1291 assert!(Rc::strong_count(&b) == 2);
1292 assert!(Rc::strong_count(&c) == 2);
1296 fn test_weak_count() {
1298 assert!(Rc::strong_count(&a) == 1);
1299 assert!(Rc::weak_count(&a) == 0);
1300 let w = Rc::downgrade(&a);
1301 assert!(Rc::strong_count(&a) == 1);
1302 assert!(Rc::weak_count(&a) == 1);
1304 assert!(Rc::strong_count(&a) == 1);
1305 assert!(Rc::weak_count(&a) == 0);
1307 assert!(Rc::strong_count(&a) == 2);
1308 assert!(Rc::weak_count(&a) == 0);
1315 assert_eq!(Rc::try_unwrap(x), Ok(3));
1318 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1320 let _w = Rc::downgrade(&x);
1321 assert_eq!(Rc::try_unwrap(x), Ok(5));
1325 fn into_from_raw() {
1326 let x = Rc::new(box "hello");
1329 let x_ptr = Rc::into_raw(x);
1332 assert_eq!(**x_ptr, "hello");
1334 let x = Rc::from_raw(x_ptr);
1335 assert_eq!(**x, "hello");
1337 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1343 let mut x = Rc::new(3);
1344 *Rc::get_mut(&mut x).unwrap() = 4;
1347 assert!(Rc::get_mut(&mut x).is_none());
1349 assert!(Rc::get_mut(&mut x).is_some());
1350 let _w = Rc::downgrade(&x);
1351 assert!(Rc::get_mut(&mut x).is_none());
1355 fn test_cowrc_clone_make_unique() {
1356 let mut cow0 = Rc::new(75);
1357 let mut cow1 = cow0.clone();
1358 let mut cow2 = cow1.clone();
1360 assert!(75 == *Rc::make_mut(&mut cow0));
1361 assert!(75 == *Rc::make_mut(&mut cow1));
1362 assert!(75 == *Rc::make_mut(&mut cow2));
1364 *Rc::make_mut(&mut cow0) += 1;
1365 *Rc::make_mut(&mut cow1) += 2;
1366 *Rc::make_mut(&mut cow2) += 3;
1368 assert!(76 == *cow0);
1369 assert!(77 == *cow1);
1370 assert!(78 == *cow2);
1372 // none should point to the same backing memory
1373 assert!(*cow0 != *cow1);
1374 assert!(*cow0 != *cow2);
1375 assert!(*cow1 != *cow2);
1379 fn test_cowrc_clone_unique2() {
1380 let mut cow0 = Rc::new(75);
1381 let cow1 = cow0.clone();
1382 let cow2 = cow1.clone();
1384 assert!(75 == *cow0);
1385 assert!(75 == *cow1);
1386 assert!(75 == *cow2);
1388 *Rc::make_mut(&mut cow0) += 1;
1390 assert!(76 == *cow0);
1391 assert!(75 == *cow1);
1392 assert!(75 == *cow2);
1394 // cow1 and cow2 should share the same contents
1395 // cow0 should have a unique reference
1396 assert!(*cow0 != *cow1);
1397 assert!(*cow0 != *cow2);
1398 assert!(*cow1 == *cow2);
1402 fn test_cowrc_clone_weak() {
1403 let mut cow0 = Rc::new(75);
1404 let cow1_weak = Rc::downgrade(&cow0);
1406 assert!(75 == *cow0);
1407 assert!(75 == *cow1_weak.upgrade().unwrap());
1409 *Rc::make_mut(&mut cow0) += 1;
1411 assert!(76 == *cow0);
1412 assert!(cow1_weak.upgrade().is_none());
1417 let foo = Rc::new(75);
1418 assert_eq!(format!("{:?}", foo), "75");
1423 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1424 assert_eq!(foo, foo.clone());
1428 fn test_from_owned() {
1430 let foo_rc = Rc::from(foo);
1431 assert!(123 == *foo_rc);
1435 fn test_new_weak() {
1436 let foo: Weak<usize> = Weak::new();
1437 assert!(foo.upgrade().is_none());
1442 let five = Rc::new(5);
1443 let same_five = five.clone();
1444 let other_five = Rc::new(5);
1446 assert!(Rc::ptr_eq(&five, &same_five));
1447 assert!(!Rc::ptr_eq(&five, &other_five));
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1453 fn borrow(&self) -> &T {
1458 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1459 impl<T: ?Sized> AsRef<T> for Rc<T> {
1460 fn as_ref(&self) -> &T {