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`][cell] or
22 //! [`RefCell`][refcell].
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`][weak] pointer. A `Weak` pointer can be [`upgrade`][upgrade]d
33 //! to an `Rc`, but this will return [`None`][option] 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`][deref] trait),
42 //! so you can call `T`'s methods on a value of type `Rc<T>`. To avoid name
43 //! clashes with `T`'s methods, the methods of `Rc<T>` 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>` does not auto-dereference to `T`, because the value may have
54 //! already been destroyed.
56 //! [rc]: struct.Rc.html
57 //! [weak]: struct.Weak.html
58 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
59 //! [cell]: ../../std/cell/struct.Cell.html
60 //! [refcell]: ../../std/cell/struct.RefCell.html
61 //! [send]: ../../std/marker/trait.Send.html
62 //! [arc]: ../../std/sync/struct.Arc.html
63 //! [deref]: ../../std/ops/trait.Deref.html
64 //! [downgrade]: struct.Rc.html#method.downgrade
65 //! [upgrade]: struct.Weak.html#method.upgrade
66 //! [option]: ../../std/option/enum.Option.html
67 //! [assoc]: ../../book/method-syntax.html#associated-functions
71 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
72 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
73 //! unique ownership, because more than one gadget may belong to the same
74 //! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s,
75 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
82 //! // ...other fields
88 //! // ...other fields
92 //! // Create a reference-counted `Owner`.
93 //! let gadget_owner: Rc<Owner> = Rc::new(
95 //! name: "Gadget Man".to_string(),
99 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
100 //! // value gives us a new pointer to the same `Owner` value, incrementing
101 //! // the reference count in the process.
102 //! let gadget1 = Gadget {
104 //! owner: gadget_owner.clone(),
106 //! let gadget2 = Gadget {
108 //! owner: gadget_owner.clone(),
111 //! // Dispose of our local variable `gadget_owner`.
112 //! drop(gadget_owner);
114 //! // Despite dropping `gadget_owner`, we're still able to print out the name
115 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
116 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
117 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
118 //! // allocated. The field projection `gadget1.owner.name` works because
119 //! // `Rc<Owner>` automatically dereferences to `Owner`.
120 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
121 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
123 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
124 //! // with them the last counted references to our `Owner`. Gadget Man now
125 //! // gets destroyed as well.
129 //! If our requirements change, and we also need to be able to traverse from
130 //! `Owner` to `Gadget`, we will run into problems. An `Rc` pointer from `Owner`
131 //! to `Gadget` introduces a cycle between the values. This means that their
132 //! reference counts can never reach 0, and the values will remain allocated
133 //! forever: a memory leak. In order to get around this, we can use `Weak`
136 //! Rust actually makes it somewhat difficult to produce this loop in the first
137 //! place. In order to end up with two values that point at each other, one of
138 //! them needs to be mutable. This is difficult because `Rc` enforces
139 //! memory safety by only giving out shared references to the value it wraps,
140 //! and these don't allow direct mutation. We need to wrap the part of the
141 //! value we wish to mutate in a [`RefCell`][refcell], which provides *interior
142 //! mutability*: a method to achieve mutability through a shared reference.
143 //! `RefCell` enforces Rust's borrowing rules at runtime.
147 //! use std::rc::Weak;
148 //! use std::cell::RefCell;
152 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
153 //! // ...other fields
158 //! owner: Rc<Owner>,
159 //! // ...other fields
163 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
164 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
165 //! // a shared reference.
166 //! let gadget_owner: Rc<Owner> = Rc::new(
168 //! name: "Gadget Man".to_string(),
169 //! gadgets: RefCell::new(vec![]),
173 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
174 //! let gadget1 = Rc::new(
177 //! owner: gadget_owner.clone(),
180 //! let gadget2 = Rc::new(
183 //! owner: gadget_owner.clone(),
187 //! // Add the `Gadget`s to their `Owner`.
189 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
190 //! gadgets.push(Rc::downgrade(&gadget1));
191 //! gadgets.push(Rc::downgrade(&gadget2));
193 //! // `RefCell` dynamic borrow ends here.
196 //! // Iterate over our `Gadget`s, printing their details out.
197 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
199 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
200 //! // guarantee the value is still allocated, we need to call
201 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
203 //! // In this case we know the value still exists, so we simply
204 //! // `unwrap` the `Option`. In a more complicated program, you might
205 //! // need graceful error handling for a `None` result.
207 //! let gadget = gadget_weak.upgrade().unwrap();
208 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
211 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
212 //! // are destroyed. There are now no strong (`Rc`) pointers to the
213 //! // gadgets, so they are destroyed. This zeroes the reference count on
214 //! // Gadget Man, so he gets destroyed as well.
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_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;
241 struct RcBox<T: ?Sized> {
248 /// A single-threaded reference-counting pointer.
250 /// See the [module-level documentation](./index.html) for more details.
252 /// The inherent methods of `Rc` are all associated functions, which means
253 /// that you have to call them as e.g. `Rc::get_mut(&value)` instead of
254 /// `value.get_mut()`. This avoids conflicts with methods of the inner
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub struct Rc<T: ?Sized> {
258 ptr: Shared<RcBox<T>>,
261 #[stable(feature = "rust1", since = "1.0.0")]
262 impl<T: ?Sized> !marker::Send for Rc<T> {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T: ?Sized> !marker::Sync for Rc<T> {}
266 #[unstable(feature = "coerce_unsized", issue = "27732")]
267 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
270 /// Constructs a new `Rc<T>`.
277 /// let five = Rc::new(5);
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn new(value: T) -> Rc<T> {
283 // there is an implicit weak pointer owned by all the strong
284 // pointers, which ensures that the weak destructor never frees
285 // the allocation while the strong destructor is running, even
286 // if the weak pointer is stored inside the strong one.
287 ptr: Shared::new(Box::into_raw(box RcBox {
288 strong: Cell::new(1),
296 /// Returns the contained value, if the `Rc` has exactly one strong reference.
298 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
301 /// This will succeed even if there are outstanding weak references.
303 /// [result]: ../../std/result/enum.Result.html
310 /// let x = Rc::new(3);
311 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
313 /// let x = Rc::new(4);
314 /// let _y = x.clone();
315 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
318 #[stable(feature = "rc_unique", since = "1.4.0")]
319 pub fn try_unwrap(this: Self) -> Result<T, Self> {
320 if Rc::would_unwrap(&this) {
322 let val = ptr::read(&*this); // copy the contained object
324 // Indicate to Weaks that they can't be promoted by decrememting
325 // the strong count, and then remove the implicit "strong weak"
326 // pointer while also handling drop logic by just crafting a
329 let _weak = Weak { ptr: this.ptr };
338 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
341 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
342 /// [result]: ../../std/result/enum.Result.html
347 /// #![feature(rc_would_unwrap)]
351 /// let x = Rc::new(3);
352 /// assert!(Rc::would_unwrap(&x));
353 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
355 /// let x = Rc::new(4);
356 /// let _y = x.clone();
357 /// assert!(!Rc::would_unwrap(&x));
358 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
360 #[unstable(feature = "rc_would_unwrap",
361 reason = "just added for niche usecase",
363 pub fn would_unwrap(this: &Self) -> bool {
364 Rc::strong_count(&this) == 1
367 /// Consumes the `Rc`, returning the wrapped pointer.
369 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
370 /// [`Rc::from_raw`][from_raw].
372 /// [from_raw]: struct.Rc.html#method.from_raw
377 /// #![feature(rc_raw)]
381 /// let x = Rc::new(10);
382 /// let x_ptr = Rc::into_raw(x);
383 /// assert_eq!(unsafe { *x_ptr }, 10);
385 #[unstable(feature = "rc_raw", issue = "37197")]
386 pub fn into_raw(this: Self) -> *mut T {
387 let ptr = unsafe { &mut (**this.ptr).value as *mut _ };
392 /// Constructs an `Rc` from a raw pointer.
394 /// The raw pointer must have been previously returned by a call to a
395 /// [`Rc::into_raw`][into_raw].
397 /// This function is unsafe because improper use may lead to memory problems. For example, a
398 /// double-free may occur if the function is called twice on the same raw pointer.
400 /// [into_raw]: struct.Rc.html#method.into_raw
405 /// #![feature(rc_raw)]
409 /// let x = Rc::new(10);
410 /// let x_ptr = Rc::into_raw(x);
413 /// // Convert back to an `Rc` to prevent leak.
414 /// let x = Rc::from_raw(x_ptr);
415 /// assert_eq!(*x, 10);
417 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
420 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
422 #[unstable(feature = "rc_raw", issue = "37197")]
423 pub unsafe fn from_raw(ptr: *mut T) -> Self {
424 // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
425 // `value` field from the pointer.
426 Rc { ptr: Shared::new((ptr as *mut u8).offset(-offset_of!(RcBox<T>, value)) as *mut _) }
430 impl<T: ?Sized> Rc<T> {
431 /// Creates a new [`Weak`][weak] pointer to this value.
433 /// [weak]: struct.Weak.html
440 /// let five = Rc::new(5);
442 /// let weak_five = Rc::downgrade(&five);
444 #[stable(feature = "rc_weak", since = "1.4.0")]
445 pub fn downgrade(this: &Self) -> Weak<T> {
447 Weak { ptr: this.ptr }
450 /// Gets the number of [`Weak`][weak] pointers to this value.
452 /// [weak]: struct.Weak.html
457 /// #![feature(rc_counts)]
461 /// let five = Rc::new(5);
462 /// let _weak_five = Rc::downgrade(&five);
464 /// assert_eq!(1, Rc::weak_count(&five));
467 #[unstable(feature = "rc_counts", reason = "not clearly useful",
469 pub fn weak_count(this: &Self) -> usize {
473 /// Gets the number of strong (`Rc`) pointers to this value.
478 /// #![feature(rc_counts)]
482 /// let five = Rc::new(5);
483 /// let _also_five = five.clone();
485 /// assert_eq!(2, Rc::strong_count(&five));
488 #[unstable(feature = "rc_counts", reason = "not clearly useful",
490 pub fn strong_count(this: &Self) -> usize {
494 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
495 /// this inner value.
497 /// [weak]: struct.Weak.html
502 /// #![feature(rc_counts)]
506 /// let five = Rc::new(5);
508 /// assert!(Rc::is_unique(&five));
511 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
513 pub fn is_unique(this: &Self) -> bool {
514 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
517 /// Returns a mutable reference to the inner value, if there are
518 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
520 /// Returns [`None`][option] otherwise, because it is not safe to
521 /// mutate a shared value.
523 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
524 /// the inner value when it's shared.
526 /// [weak]: struct.Weak.html
527 /// [option]: ../../std/option/enum.Option.html
528 /// [make_mut]: struct.Rc.html#method.make_mut
529 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
536 /// let mut x = Rc::new(3);
537 /// *Rc::get_mut(&mut x).unwrap() = 4;
538 /// assert_eq!(*x, 4);
540 /// let _y = x.clone();
541 /// assert!(Rc::get_mut(&mut x).is_none());
544 #[stable(feature = "rc_unique", since = "1.4.0")]
545 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
546 if Rc::is_unique(this) {
547 let inner = unsafe { &mut **this.ptr };
548 Some(&mut inner.value)
555 #[unstable(feature = "ptr_eq",
556 reason = "newly added",
558 /// Returns true if the two `Rc`s point to the same value (not
559 /// just values that compare as equal).
564 /// #![feature(ptr_eq)]
568 /// let five = Rc::new(5);
569 /// let same_five = five.clone();
570 /// let other_five = Rc::new(5);
572 /// assert!(Rc::ptr_eq(&five, &same_five));
573 /// assert!(!Rc::ptr_eq(&five, &other_five));
575 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
576 let this_ptr: *const RcBox<T> = *this.ptr;
577 let other_ptr: *const RcBox<T> = *other.ptr;
578 this_ptr == other_ptr
582 impl<T: Clone> Rc<T> {
583 /// Makes a mutable reference into the given `Rc`.
585 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
586 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
587 /// ensure unique ownership. This is also referred to as clone-on-write.
589 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
591 /// [weak]: struct.Weak.html
592 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
593 /// [get_mut]: struct.Rc.html#method.get_mut
600 /// let mut data = Rc::new(5);
602 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
603 /// let mut other_data = data.clone(); // Won't clone inner data
604 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
605 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
606 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
608 /// // Now `data` and `other_data` point to different values.
609 /// assert_eq!(*data, 8);
610 /// assert_eq!(*other_data, 12);
613 #[stable(feature = "rc_unique", since = "1.4.0")]
614 pub fn make_mut(this: &mut Self) -> &mut T {
615 if Rc::strong_count(this) != 1 {
616 // Gotta clone the data, there are other Rcs
617 *this = Rc::new((**this).clone())
618 } else if Rc::weak_count(this) != 0 {
619 // Can just steal the data, all that's left is Weaks
621 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
622 mem::swap(this, &mut swap);
624 // Remove implicit strong-weak ref (no need to craft a fake
625 // Weak here -- we know other Weaks can clean up for us)
630 // This unsafety is ok because we're guaranteed that the pointer
631 // returned is the *only* pointer that will ever be returned to T. Our
632 // reference count is guaranteed to be 1 at this point, and we required
633 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
634 // reference to the inner value.
635 let inner = unsafe { &mut **this.ptr };
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T: ?Sized> Deref for Rc<T> {
645 fn deref(&self) -> &T {
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T: ?Sized> Drop for Rc<T> {
654 /// This will decrement the strong reference count. If the strong reference
655 /// count reaches zero then the only other references (if any) are
656 /// [`Weak`][weak], so we `drop` the inner value.
658 /// [weak]: struct.Weak.html
667 /// impl Drop for Foo {
668 /// fn drop(&mut self) {
669 /// println!("dropped!");
673 /// let foo = Rc::new(Foo);
674 /// let foo2 = foo.clone();
676 /// drop(foo); // Doesn't print anything
677 /// drop(foo2); // Prints "dropped!"
679 #[unsafe_destructor_blind_to_params]
685 if self.strong() == 0 {
686 // destroy the contained object
687 ptr::drop_in_place(&mut (*ptr).value);
689 // remove the implicit "strong weak" pointer now that we've
690 // destroyed the contents.
693 if self.weak() == 0 {
694 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl<T: ?Sized> Clone for Rc<T> {
703 /// Makes a clone of the `Rc` pointer.
705 /// This creates another pointer to the same inner value, increasing the
706 /// strong reference count.
713 /// let five = Rc::new(5);
718 fn clone(&self) -> Rc<T> {
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl<T: Default> Default for Rc<T> {
726 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
733 /// let x: Rc<i32> = Default::default();
734 /// assert_eq!(*x, 0);
737 fn default() -> Rc<T> {
738 Rc::new(Default::default())
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
744 /// Equality for two `Rc`s.
746 /// Two `Rc`s are equal if their inner values are equal.
753 /// let five = Rc::new(5);
755 /// assert!(five == Rc::new(5));
758 fn eq(&self, other: &Rc<T>) -> bool {
762 /// Inequality for two `Rc`s.
764 /// Two `Rc`s are unequal if their inner values are unequal.
771 /// let five = Rc::new(5);
773 /// assert!(five != Rc::new(6));
776 fn ne(&self, other: &Rc<T>) -> bool {
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T: ?Sized + Eq> Eq for Rc<T> {}
784 #[stable(feature = "rust1", since = "1.0.0")]
785 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
786 /// Partial comparison for two `Rc`s.
788 /// The two are compared by calling `partial_cmp()` on their inner values.
794 /// use std::cmp::Ordering;
796 /// let five = Rc::new(5);
798 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
801 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
802 (**self).partial_cmp(&**other)
805 /// Less-than comparison for two `Rc`s.
807 /// The two are compared by calling `<` on their inner values.
814 /// let five = Rc::new(5);
816 /// assert!(five < Rc::new(6));
819 fn lt(&self, other: &Rc<T>) -> bool {
823 /// 'Less than or equal to' comparison for two `Rc`s.
825 /// The two are compared by calling `<=` on their inner values.
832 /// let five = Rc::new(5);
834 /// assert!(five <= Rc::new(5));
837 fn le(&self, other: &Rc<T>) -> bool {
841 /// Greater-than comparison for two `Rc`s.
843 /// The two are compared by calling `>` on their inner values.
850 /// let five = Rc::new(5);
852 /// assert!(five > Rc::new(4));
855 fn gt(&self, other: &Rc<T>) -> bool {
859 /// 'Greater than or equal to' comparison for two `Rc`s.
861 /// The two are compared by calling `>=` on their inner values.
868 /// let five = Rc::new(5);
870 /// assert!(five >= Rc::new(5));
873 fn ge(&self, other: &Rc<T>) -> bool {
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T: ?Sized + Ord> Ord for Rc<T> {
880 /// Comparison for two `Rc`s.
882 /// The two are compared by calling `cmp()` on their inner values.
888 /// use std::cmp::Ordering;
890 /// let five = Rc::new(5);
892 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
895 fn cmp(&self, other: &Rc<T>) -> Ordering {
896 (**self).cmp(&**other)
900 #[stable(feature = "rust1", since = "1.0.0")]
901 impl<T: ?Sized + Hash> Hash for Rc<T> {
902 fn hash<H: Hasher>(&self, state: &mut H) {
903 (**self).hash(state);
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
909 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
910 fmt::Display::fmt(&**self, f)
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917 fmt::Debug::fmt(&**self, f)
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<T: ?Sized> fmt::Pointer for Rc<T> {
923 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
924 fmt::Pointer::fmt(&*self.ptr, f)
928 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
929 impl<T> From<T> for Rc<T> {
930 fn from(t: T) -> Self {
935 /// A weak version of [`Rc`][rc].
937 /// `Weak` pointers do not count towards determining if the inner value
938 /// should be dropped.
940 /// The typical way to obtain a `Weak` pointer is to call
941 /// [`Rc::downgrade`][downgrade].
943 /// See the [module-level documentation](./index.html) for more details.
945 /// [rc]: struct.Rc.html
946 /// [downgrade]: struct.Rc.html#method.downgrade
947 #[stable(feature = "rc_weak", since = "1.4.0")]
948 pub struct Weak<T: ?Sized> {
949 ptr: Shared<RcBox<T>>,
952 #[stable(feature = "rc_weak", since = "1.4.0")]
953 impl<T: ?Sized> !marker::Send for Weak<T> {}
954 #[stable(feature = "rc_weak", since = "1.4.0")]
955 impl<T: ?Sized> !marker::Sync for Weak<T> {}
957 #[unstable(feature = "coerce_unsized", issue = "27732")]
958 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
961 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
963 /// This allocates memory for `T`, but does not initialize it. Calling
964 /// [`upgrade`][upgrade] on the return value always gives
965 /// [`None`][option].
967 /// [upgrade]: struct.Weak.html#method.upgrade
968 /// [option]: ../../std/option/enum.Option.html
973 /// use std::rc::Weak;
975 /// let empty: Weak<i64> = Weak::new();
976 /// assert!(empty.upgrade().is_none());
978 #[stable(feature = "downgraded_weak", since = "1.10.0")]
979 pub fn new() -> Weak<T> {
982 ptr: Shared::new(Box::into_raw(box RcBox {
983 strong: Cell::new(0),
985 value: uninitialized(),
992 impl<T: ?Sized> Weak<T> {
993 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
995 /// Returns [`None`][option] if the strong count has reached zero and the
996 /// inner value was destroyed.
998 /// [rc]: struct.Rc.html
999 /// [option]: ../../std/option/enum.Option.html
1004 /// use std::rc::Rc;
1006 /// let five = Rc::new(5);
1008 /// let weak_five = Rc::downgrade(&five);
1010 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1011 /// assert!(strong_five.is_some());
1013 /// // Destroy all strong pointers.
1014 /// drop(strong_five);
1017 /// assert!(weak_five.upgrade().is_none());
1019 #[stable(feature = "rc_weak", since = "1.4.0")]
1020 pub fn upgrade(&self) -> Option<Rc<T>> {
1021 if self.strong() == 0 {
1025 Some(Rc { ptr: self.ptr })
1030 #[stable(feature = "rc_weak", since = "1.4.0")]
1031 impl<T: ?Sized> Drop for Weak<T> {
1032 /// Drops the `Weak` pointer.
1034 /// This will decrement the weak reference count.
1039 /// use std::rc::Rc;
1043 /// impl Drop for Foo {
1044 /// fn drop(&mut self) {
1045 /// println!("dropped!");
1049 /// let foo = Rc::new(Foo);
1050 /// let weak_foo = Rc::downgrade(&foo);
1051 /// let other_weak_foo = weak_foo.clone();
1053 /// drop(weak_foo); // Doesn't print anything
1054 /// drop(foo); // Prints "dropped!"
1056 /// assert!(other_weak_foo.upgrade().is_none());
1058 fn drop(&mut self) {
1060 let ptr = *self.ptr;
1063 // the weak count starts at 1, and will only go to zero if all
1064 // the strong pointers have disappeared.
1065 if self.weak() == 0 {
1066 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1072 #[stable(feature = "rc_weak", since = "1.4.0")]
1073 impl<T: ?Sized> Clone for Weak<T> {
1074 /// Makes a clone of the `Weak` pointer.
1076 /// This creates another pointer to the same inner value, increasing the
1077 /// weak reference count.
1082 /// use std::rc::Rc;
1084 /// let weak_five = Rc::downgrade(&Rc::new(5));
1086 /// weak_five.clone();
1089 fn clone(&self) -> Weak<T> {
1091 Weak { ptr: self.ptr }
1095 #[stable(feature = "rc_weak", since = "1.4.0")]
1096 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1097 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1102 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1103 impl<T> Default for Weak<T> {
1104 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1106 /// This allocates memory for `T`, but does not initialize it. Calling
1107 /// [`upgrade`][upgrade] on the return value always gives
1108 /// [`None`][option].
1110 /// [upgrade]: struct.Weak.html#method.upgrade
1111 /// [option]: ../../std/option/enum.Option.html
1116 /// use std::rc::Weak;
1118 /// let empty: Weak<i64> = Default::default();
1119 /// assert!(empty.upgrade().is_none());
1121 fn default() -> Weak<T> {
1126 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1127 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1128 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1129 // We abort because this is such a degenerate scenario that we don't care about
1130 // what happens -- no real program should ever experience this.
1132 // This should have negligible overhead since you don't actually need to
1133 // clone these much in Rust thanks to ownership and move-semantics.
1136 trait RcBoxPtr<T: ?Sized> {
1137 fn inner(&self) -> &RcBox<T>;
1140 fn strong(&self) -> usize {
1141 self.inner().strong.get()
1145 fn inc_strong(&self) {
1146 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1150 fn dec_strong(&self) {
1151 self.inner().strong.set(self.strong() - 1);
1155 fn weak(&self) -> usize {
1156 self.inner().weak.get()
1160 fn inc_weak(&self) {
1161 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1165 fn dec_weak(&self) {
1166 self.inner().weak.set(self.weak() - 1);
1170 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1172 fn inner(&self) -> &RcBox<T> {
1174 // Safe to assume this here, as if it weren't true, we'd be breaking
1175 // the contract anyway.
1176 // This allows the null check to be elided in the destructor if we
1177 // manipulated the reference count in the same function.
1178 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1184 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1186 fn inner(&self) -> &RcBox<T> {
1188 // Safe to assume this here, as if it weren't true, we'd be breaking
1189 // the contract anyway.
1190 // This allows the null check to be elided in the destructor if we
1191 // manipulated the reference count in the same function.
1192 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1200 use super::{Rc, Weak};
1201 use std::boxed::Box;
1202 use std::cell::RefCell;
1203 use std::option::Option;
1204 use std::option::Option::{None, Some};
1205 use std::result::Result::{Err, Ok};
1207 use std::clone::Clone;
1208 use std::convert::From;
1212 let x = Rc::new(RefCell::new(5));
1214 *x.borrow_mut() = 20;
1215 assert_eq!(*y.borrow(), 20);
1225 fn test_simple_clone() {
1233 fn test_destructor() {
1234 let x: Rc<Box<_>> = Rc::new(box 5);
1241 let y = Rc::downgrade(&x);
1242 assert!(y.upgrade().is_some());
1248 let y = Rc::downgrade(&x);
1250 assert!(y.upgrade().is_none());
1254 fn weak_self_cyclic() {
1256 x: RefCell<Option<Weak<Cycle>>>,
1259 let a = Rc::new(Cycle { x: RefCell::new(None) });
1260 let b = Rc::downgrade(&a.clone());
1261 *a.x.borrow_mut() = Some(b);
1263 // hopefully we don't double-free (or leak)...
1269 assert!(Rc::is_unique(&x));
1271 assert!(!Rc::is_unique(&x));
1273 assert!(Rc::is_unique(&x));
1274 let w = Rc::downgrade(&x);
1275 assert!(!Rc::is_unique(&x));
1277 assert!(Rc::is_unique(&x));
1281 fn test_strong_count() {
1283 assert!(Rc::strong_count(&a) == 1);
1284 let w = Rc::downgrade(&a);
1285 assert!(Rc::strong_count(&a) == 1);
1286 let b = w.upgrade().expect("upgrade of live rc failed");
1287 assert!(Rc::strong_count(&b) == 2);
1288 assert!(Rc::strong_count(&a) == 2);
1291 assert!(Rc::strong_count(&b) == 1);
1293 assert!(Rc::strong_count(&b) == 2);
1294 assert!(Rc::strong_count(&c) == 2);
1298 fn test_weak_count() {
1300 assert!(Rc::strong_count(&a) == 1);
1301 assert!(Rc::weak_count(&a) == 0);
1302 let w = Rc::downgrade(&a);
1303 assert!(Rc::strong_count(&a) == 1);
1304 assert!(Rc::weak_count(&a) == 1);
1306 assert!(Rc::strong_count(&a) == 1);
1307 assert!(Rc::weak_count(&a) == 0);
1309 assert!(Rc::strong_count(&a) == 2);
1310 assert!(Rc::weak_count(&a) == 0);
1317 assert_eq!(Rc::try_unwrap(x), Ok(3));
1320 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1322 let _w = Rc::downgrade(&x);
1323 assert_eq!(Rc::try_unwrap(x), Ok(5));
1327 fn into_from_raw() {
1328 let x = Rc::new(box "hello");
1331 let x_ptr = Rc::into_raw(x);
1334 assert_eq!(**x_ptr, "hello");
1336 let x = Rc::from_raw(x_ptr);
1337 assert_eq!(**x, "hello");
1339 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1345 let mut x = Rc::new(3);
1346 *Rc::get_mut(&mut x).unwrap() = 4;
1349 assert!(Rc::get_mut(&mut x).is_none());
1351 assert!(Rc::get_mut(&mut x).is_some());
1352 let _w = Rc::downgrade(&x);
1353 assert!(Rc::get_mut(&mut x).is_none());
1357 fn test_cowrc_clone_make_unique() {
1358 let mut cow0 = Rc::new(75);
1359 let mut cow1 = cow0.clone();
1360 let mut cow2 = cow1.clone();
1362 assert!(75 == *Rc::make_mut(&mut cow0));
1363 assert!(75 == *Rc::make_mut(&mut cow1));
1364 assert!(75 == *Rc::make_mut(&mut cow2));
1366 *Rc::make_mut(&mut cow0) += 1;
1367 *Rc::make_mut(&mut cow1) += 2;
1368 *Rc::make_mut(&mut cow2) += 3;
1370 assert!(76 == *cow0);
1371 assert!(77 == *cow1);
1372 assert!(78 == *cow2);
1374 // none should point to the same backing memory
1375 assert!(*cow0 != *cow1);
1376 assert!(*cow0 != *cow2);
1377 assert!(*cow1 != *cow2);
1381 fn test_cowrc_clone_unique2() {
1382 let mut cow0 = Rc::new(75);
1383 let cow1 = cow0.clone();
1384 let cow2 = cow1.clone();
1386 assert!(75 == *cow0);
1387 assert!(75 == *cow1);
1388 assert!(75 == *cow2);
1390 *Rc::make_mut(&mut cow0) += 1;
1392 assert!(76 == *cow0);
1393 assert!(75 == *cow1);
1394 assert!(75 == *cow2);
1396 // cow1 and cow2 should share the same contents
1397 // cow0 should have a unique reference
1398 assert!(*cow0 != *cow1);
1399 assert!(*cow0 != *cow2);
1400 assert!(*cow1 == *cow2);
1404 fn test_cowrc_clone_weak() {
1405 let mut cow0 = Rc::new(75);
1406 let cow1_weak = Rc::downgrade(&cow0);
1408 assert!(75 == *cow0);
1409 assert!(75 == *cow1_weak.upgrade().unwrap());
1411 *Rc::make_mut(&mut cow0) += 1;
1413 assert!(76 == *cow0);
1414 assert!(cow1_weak.upgrade().is_none());
1419 let foo = Rc::new(75);
1420 assert_eq!(format!("{:?}", foo), "75");
1425 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1426 assert_eq!(foo, foo.clone());
1430 fn test_from_owned() {
1432 let foo_rc = Rc::from(foo);
1433 assert!(123 == *foo_rc);
1437 fn test_new_weak() {
1438 let foo: Weak<usize> = Weak::new();
1439 assert!(foo.upgrade().is_none());
1444 let five = Rc::new(5);
1445 let same_five = five.clone();
1446 let other_five = Rc::new(5);
1448 assert!(Rc::ptr_eq(&five, &same_five));
1449 assert!(!Rc::ptr_eq(&five, &other_five));
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1455 fn borrow(&self) -> &T {
1460 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1461 impl<T: ?Sized> AsRef<T> for Rc<T> {
1462 fn as_ref(&self) -> &T {