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, 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)` instead of
255 /// `value.get_mut()`. This avoids conflicts with methods of the inner
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub struct Rc<T: ?Sized> {
259 ptr: Shared<RcBox<T>>,
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T: ?Sized> !marker::Send for Rc<T> {}
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<T: ?Sized> !marker::Sync for Rc<T> {}
267 #[unstable(feature = "coerce_unsized", issue = "27732")]
268 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
271 /// Constructs a new `Rc<T>`.
278 /// let five = Rc::new(5);
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn new(value: T) -> Rc<T> {
284 // there is an implicit weak pointer owned by all the strong
285 // pointers, which ensures that the weak destructor never frees
286 // the allocation while the strong destructor is running, even
287 // if the weak pointer is stored inside the strong one.
288 ptr: Shared::new(Box::into_raw(box RcBox {
289 strong: Cell::new(1),
297 /// Returns the contained value, if the `Rc` has exactly one strong reference.
299 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
302 /// This will succeed even if there are outstanding weak references.
304 /// [result]: ../../std/result/enum.Result.html
311 /// let x = Rc::new(3);
312 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
314 /// let x = Rc::new(4);
315 /// let _y = x.clone();
316 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
319 #[stable(feature = "rc_unique", since = "1.4.0")]
320 pub fn try_unwrap(this: Self) -> Result<T, Self> {
321 if Rc::would_unwrap(&this) {
323 let val = ptr::read(&*this); // copy the contained object
325 // Indicate to Weaks that they can't be promoted by decrememting
326 // the strong count, and then remove the implicit "strong weak"
327 // pointer while also handling drop logic by just crafting a
330 let _weak = Weak { ptr: this.ptr };
339 /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
342 /// [try_unwrap]: struct.Rc.html#method.try_unwrap
343 /// [result]: ../../std/result/enum.Result.html
348 /// #![feature(rc_would_unwrap)]
352 /// let x = Rc::new(3);
353 /// assert!(Rc::would_unwrap(&x));
354 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
356 /// let x = Rc::new(4);
357 /// let _y = x.clone();
358 /// assert!(!Rc::would_unwrap(&x));
359 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
361 #[unstable(feature = "rc_would_unwrap",
362 reason = "just added for niche usecase",
364 pub fn would_unwrap(this: &Self) -> bool {
365 Rc::strong_count(&this) == 1
370 /// Constructs a new `Rc<str>` from a string slice.
372 #[unstable(feature = "rustc_private",
373 reason = "for internal use in rustc",
375 pub fn __from_str(value: &str) -> Rc<str> {
377 // Allocate enough space for `RcBox<str>`.
378 let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
379 let vec = RawVec::<usize>::with_capacity(aligned_len);
382 // Initialize fields of `RcBox<str>`.
383 *ptr.offset(0) = 1; // strong: Cell::new(1)
384 *ptr.offset(1) = 1; // weak: Cell::new(1)
385 ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
386 // Combine the allocation address and the string length into a fat pointer to `RcBox`.
387 let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
388 assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
389 Rc { ptr: Shared::new(rcbox_ptr) }
394 impl<T: ?Sized> Rc<T> {
395 /// Creates a new [`Weak`][weak] pointer to this value.
397 /// [weak]: struct.Weak.html
404 /// let five = Rc::new(5);
406 /// let weak_five = Rc::downgrade(&five);
408 #[stable(feature = "rc_weak", since = "1.4.0")]
409 pub fn downgrade(this: &Self) -> Weak<T> {
411 Weak { ptr: this.ptr }
414 /// Gets the number of [`Weak`][weak] pointers to this value.
416 /// [weak]: struct.Weak.html
421 /// #![feature(rc_counts)]
425 /// let five = Rc::new(5);
426 /// let _weak_five = Rc::downgrade(&five);
428 /// assert_eq!(1, Rc::weak_count(&five));
431 #[unstable(feature = "rc_counts", reason = "not clearly useful",
433 pub fn weak_count(this: &Self) -> usize {
437 /// Gets the number of strong (`Rc`) pointers to this value.
442 /// #![feature(rc_counts)]
446 /// let five = Rc::new(5);
447 /// let _also_five = five.clone();
449 /// assert_eq!(2, Rc::strong_count(&five));
452 #[unstable(feature = "rc_counts", reason = "not clearly useful",
454 pub fn strong_count(this: &Self) -> usize {
458 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
459 /// this inner value.
461 /// [weak]: struct.Weak.html
466 /// #![feature(rc_counts)]
470 /// let five = Rc::new(5);
472 /// assert!(Rc::is_unique(&five));
475 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
477 pub fn is_unique(this: &Self) -> bool {
478 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
481 /// Returns a mutable reference to the inner value, if there are
482 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
484 /// Returns [`None`][option] otherwise, because it is not safe to
485 /// mutate a shared value.
487 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
488 /// the inner value when it's shared.
490 /// [weak]: struct.Weak.html
491 /// [option]: ../../std/option/enum.Option.html
492 /// [make_mut]: struct.Rc.html#method.make_mut
493 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
500 /// let mut x = Rc::new(3);
501 /// *Rc::get_mut(&mut x).unwrap() = 4;
502 /// assert_eq!(*x, 4);
504 /// let _y = x.clone();
505 /// assert!(Rc::get_mut(&mut x).is_none());
508 #[stable(feature = "rc_unique", since = "1.4.0")]
509 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
510 if Rc::is_unique(this) {
511 let inner = unsafe { &mut **this.ptr };
512 Some(&mut inner.value)
519 #[unstable(feature = "ptr_eq",
520 reason = "newly added",
522 /// Returns true if the two `Rc`s point to the same value (not
523 /// just values that compare as equal).
528 /// #![feature(ptr_eq)]
532 /// let five = Rc::new(5);
533 /// let same_five = five.clone();
534 /// let other_five = Rc::new(5);
536 /// assert!(Rc::ptr_eq(&five, &same_five));
537 /// assert!(!Rc::ptr_eq(&five, &other_five));
539 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
540 let this_ptr: *const RcBox<T> = *this.ptr;
541 let other_ptr: *const RcBox<T> = *other.ptr;
542 this_ptr == other_ptr
546 impl<T: Clone> Rc<T> {
547 /// Makes a mutable reference into the given `Rc`.
549 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
550 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
551 /// ensure unique ownership. This is also referred to as clone-on-write.
553 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
555 /// [weak]: struct.Weak.html
556 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
557 /// [get_mut]: struct.Rc.html#method.get_mut
564 /// let mut data = Rc::new(5);
566 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
567 /// let mut other_data = data.clone(); // Won't clone inner data
568 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
569 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
570 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
572 /// // Now `data` and `other_data` point to different values.
573 /// assert_eq!(*data, 8);
574 /// assert_eq!(*other_data, 12);
577 #[stable(feature = "rc_unique", since = "1.4.0")]
578 pub fn make_mut(this: &mut Self) -> &mut T {
579 if Rc::strong_count(this) != 1 {
580 // Gotta clone the data, there are other Rcs
581 *this = Rc::new((**this).clone())
582 } else if Rc::weak_count(this) != 0 {
583 // Can just steal the data, all that's left is Weaks
585 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
586 mem::swap(this, &mut swap);
588 // Remove implicit strong-weak ref (no need to craft a fake
589 // Weak here -- we know other Weaks can clean up for us)
594 // This unsafety is ok because we're guaranteed that the pointer
595 // returned is the *only* pointer that will ever be returned to T. Our
596 // reference count is guaranteed to be 1 at this point, and we required
597 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
598 // reference to the inner value.
599 let inner = unsafe { &mut **this.ptr };
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<T: ?Sized> Deref for Rc<T> {
609 fn deref(&self) -> &T {
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<T: ?Sized> Drop for Rc<T> {
618 /// This will decrement the strong reference count. If the strong reference
619 /// count reaches zero then the only other references (if any) are
620 /// [`Weak`][weak], so we `drop` the inner value.
622 /// [weak]: struct.Weak.html
631 /// impl Drop for Foo {
632 /// fn drop(&mut self) {
633 /// println!("dropped!");
637 /// let foo = Rc::new(Foo);
638 /// let foo2 = foo.clone();
640 /// drop(foo); // Doesn't print anything
641 /// drop(foo2); // Prints "dropped!"
643 #[unsafe_destructor_blind_to_params]
649 if self.strong() == 0 {
650 // destroy the contained object
651 ptr::drop_in_place(&mut (*ptr).value);
653 // remove the implicit "strong weak" pointer now that we've
654 // destroyed the contents.
657 if self.weak() == 0 {
658 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl<T: ?Sized> Clone for Rc<T> {
667 /// Makes a clone of the `Rc` pointer.
669 /// This creates another pointer to the same inner value, increasing the
670 /// strong reference count.
677 /// let five = Rc::new(5);
682 fn clone(&self) -> Rc<T> {
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl<T: Default> Default for Rc<T> {
690 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
697 /// let x: Rc<i32> = Default::default();
698 /// assert_eq!(*x, 0);
701 fn default() -> Rc<T> {
702 Rc::new(Default::default())
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
708 /// Equality for two `Rc`s.
710 /// Two `Rc`s are equal if their inner values are equal.
717 /// let five = Rc::new(5);
719 /// assert!(five == Rc::new(5));
722 fn eq(&self, other: &Rc<T>) -> bool {
726 /// Inequality for two `Rc`s.
728 /// Two `Rc`s are unequal if their inner values are unequal.
735 /// let five = Rc::new(5);
737 /// assert!(five != Rc::new(6));
740 fn ne(&self, other: &Rc<T>) -> bool {
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<T: ?Sized + Eq> Eq for Rc<T> {}
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
750 /// Partial comparison for two `Rc`s.
752 /// The two are compared by calling `partial_cmp()` on their inner values.
758 /// use std::cmp::Ordering;
760 /// let five = Rc::new(5);
762 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
765 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
766 (**self).partial_cmp(&**other)
769 /// Less-than comparison for two `Rc`s.
771 /// The two are compared by calling `<` on their inner values.
778 /// let five = Rc::new(5);
780 /// assert!(five < Rc::new(6));
783 fn lt(&self, other: &Rc<T>) -> bool {
787 /// 'Less than or equal to' comparison for two `Rc`s.
789 /// The two are compared by calling `<=` on their inner values.
796 /// let five = Rc::new(5);
798 /// assert!(five <= Rc::new(5));
801 fn le(&self, other: &Rc<T>) -> bool {
805 /// Greater-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(4));
819 fn gt(&self, other: &Rc<T>) -> bool {
823 /// 'Greater 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 ge(&self, other: &Rc<T>) -> bool {
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T: ?Sized + Ord> Ord for Rc<T> {
844 /// Comparison for two `Rc`s.
846 /// The two are compared by calling `cmp()` on their inner values.
852 /// use std::cmp::Ordering;
854 /// let five = Rc::new(5);
856 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
859 fn cmp(&self, other: &Rc<T>) -> Ordering {
860 (**self).cmp(&**other)
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<T: ?Sized + Hash> Hash for Rc<T> {
866 fn hash<H: Hasher>(&self, state: &mut H) {
867 (**self).hash(state);
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
873 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
874 fmt::Display::fmt(&**self, f)
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
880 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
881 fmt::Debug::fmt(&**self, f)
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<T: ?Sized> fmt::Pointer for Rc<T> {
887 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
888 fmt::Pointer::fmt(&*self.ptr, f)
892 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
893 impl<T> From<T> for Rc<T> {
894 fn from(t: T) -> Self {
899 /// A weak version of [`Rc`][rc].
901 /// `Weak` pointers do not count towards determining if the inner value
902 /// should be dropped.
904 /// The typical way to obtain a `Weak` pointer is to call
905 /// [`Rc::downgrade`][downgrade].
907 /// See the [module-level documentation](./index.html) for more details.
909 /// [rc]: struct.Rc.html
910 /// [downgrade]: struct.Rc.html#method.downgrade
911 #[stable(feature = "rc_weak", since = "1.4.0")]
912 pub struct Weak<T: ?Sized> {
913 ptr: Shared<RcBox<T>>,
916 #[stable(feature = "rc_weak", since = "1.4.0")]
917 impl<T: ?Sized> !marker::Send for Weak<T> {}
918 #[stable(feature = "rc_weak", since = "1.4.0")]
919 impl<T: ?Sized> !marker::Sync for Weak<T> {}
921 #[unstable(feature = "coerce_unsized", issue = "27732")]
922 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
925 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
927 /// This allocates memory for `T`, but does not initialize it. Calling
928 /// [`upgrade`][upgrade] on the return value always gives
929 /// [`None`][option].
931 /// [upgrade]: struct.Weak.html#method.upgrade
932 /// [option]: ../../std/option/enum.Option.html
937 /// use std::rc::Weak;
939 /// let empty: Weak<i64> = Weak::new();
940 /// assert!(empty.upgrade().is_none());
942 #[stable(feature = "downgraded_weak", since = "1.10.0")]
943 pub fn new() -> Weak<T> {
946 ptr: Shared::new(Box::into_raw(box RcBox {
947 strong: Cell::new(0),
949 value: uninitialized(),
956 impl<T: ?Sized> Weak<T> {
957 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
959 /// Returns [`None`][option] if the strong count has reached zero and the
960 /// inner value was destroyed.
962 /// [rc]: struct.Rc.html
963 /// [option]: ../../std/option/enum.Option.html
970 /// let five = Rc::new(5);
972 /// let weak_five = Rc::downgrade(&five);
974 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
975 /// assert!(strong_five.is_some());
977 /// // Destroy all strong pointers.
978 /// drop(strong_five);
981 /// assert!(weak_five.upgrade().is_none());
983 #[stable(feature = "rc_weak", since = "1.4.0")]
984 pub fn upgrade(&self) -> Option<Rc<T>> {
985 if self.strong() == 0 {
989 Some(Rc { ptr: self.ptr })
994 #[stable(feature = "rc_weak", since = "1.4.0")]
995 impl<T: ?Sized> Drop for Weak<T> {
996 /// Drops the `Weak` pointer.
998 /// This will decrement the weak reference count.
1003 /// use std::rc::Rc;
1007 /// impl Drop for Foo {
1008 /// fn drop(&mut self) {
1009 /// println!("dropped!");
1013 /// let foo = Rc::new(Foo);
1014 /// let weak_foo = Rc::downgrade(&foo);
1015 /// let other_weak_foo = weak_foo.clone();
1017 /// drop(weak_foo); // Doesn't print anything
1018 /// drop(foo); // Prints "dropped!"
1020 /// assert!(other_weak_foo.upgrade().is_none());
1022 fn drop(&mut self) {
1024 let ptr = *self.ptr;
1027 // the weak count starts at 1, and will only go to zero if all
1028 // the strong pointers have disappeared.
1029 if self.weak() == 0 {
1030 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1036 #[stable(feature = "rc_weak", since = "1.4.0")]
1037 impl<T: ?Sized> Clone for Weak<T> {
1038 /// Makes a clone of the `Weak` pointer.
1040 /// This creates another pointer to the same inner value, increasing the
1041 /// weak reference count.
1046 /// use std::rc::Rc;
1048 /// let weak_five = Rc::downgrade(&Rc::new(5));
1050 /// weak_five.clone();
1053 fn clone(&self) -> Weak<T> {
1055 Weak { ptr: self.ptr }
1059 #[stable(feature = "rc_weak", since = "1.4.0")]
1060 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1061 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1066 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1067 impl<T> Default for Weak<T> {
1068 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1070 /// This allocates memory for `T`, but does not initialize it. Calling
1071 /// [`upgrade`][upgrade] on the return value always gives
1072 /// [`None`][option].
1074 /// [upgrade]: struct.Weak.html#method.upgrade
1075 /// [option]: ../../std/option/enum.Option.html
1080 /// use std::rc::Weak;
1082 /// let empty: Weak<i64> = Default::default();
1083 /// assert!(empty.upgrade().is_none());
1085 fn default() -> Weak<T> {
1090 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1091 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1092 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1093 // We abort because this is such a degenerate scenario that we don't care about
1094 // what happens -- no real program should ever experience this.
1096 // This should have negligible overhead since you don't actually need to
1097 // clone these much in Rust thanks to ownership and move-semantics.
1100 trait RcBoxPtr<T: ?Sized> {
1101 fn inner(&self) -> &RcBox<T>;
1104 fn strong(&self) -> usize {
1105 self.inner().strong.get()
1109 fn inc_strong(&self) {
1110 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1114 fn dec_strong(&self) {
1115 self.inner().strong.set(self.strong() - 1);
1119 fn weak(&self) -> usize {
1120 self.inner().weak.get()
1124 fn inc_weak(&self) {
1125 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1129 fn dec_weak(&self) {
1130 self.inner().weak.set(self.weak() - 1);
1134 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1136 fn inner(&self) -> &RcBox<T> {
1138 // Safe to assume this here, as if it weren't true, we'd be breaking
1139 // the contract anyway.
1140 // This allows the null check to be elided in the destructor if we
1141 // manipulated the reference count in the same function.
1142 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1148 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1150 fn inner(&self) -> &RcBox<T> {
1152 // Safe to assume this here, as if it weren't true, we'd be breaking
1153 // the contract anyway.
1154 // This allows the null check to be elided in the destructor if we
1155 // manipulated the reference count in the same function.
1156 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1164 use super::{Rc, Weak};
1165 use std::boxed::Box;
1166 use std::cell::RefCell;
1167 use std::option::Option;
1168 use std::option::Option::{None, Some};
1169 use std::result::Result::{Err, Ok};
1171 use std::clone::Clone;
1172 use std::convert::From;
1176 let x = Rc::new(RefCell::new(5));
1178 *x.borrow_mut() = 20;
1179 assert_eq!(*y.borrow(), 20);
1189 fn test_simple_clone() {
1197 fn test_destructor() {
1198 let x: Rc<Box<_>> = Rc::new(box 5);
1205 let y = Rc::downgrade(&x);
1206 assert!(y.upgrade().is_some());
1212 let y = Rc::downgrade(&x);
1214 assert!(y.upgrade().is_none());
1218 fn weak_self_cyclic() {
1220 x: RefCell<Option<Weak<Cycle>>>,
1223 let a = Rc::new(Cycle { x: RefCell::new(None) });
1224 let b = Rc::downgrade(&a.clone());
1225 *a.x.borrow_mut() = Some(b);
1227 // hopefully we don't double-free (or leak)...
1233 assert!(Rc::is_unique(&x));
1235 assert!(!Rc::is_unique(&x));
1237 assert!(Rc::is_unique(&x));
1238 let w = Rc::downgrade(&x);
1239 assert!(!Rc::is_unique(&x));
1241 assert!(Rc::is_unique(&x));
1245 fn test_strong_count() {
1247 assert!(Rc::strong_count(&a) == 1);
1248 let w = Rc::downgrade(&a);
1249 assert!(Rc::strong_count(&a) == 1);
1250 let b = w.upgrade().expect("upgrade of live rc failed");
1251 assert!(Rc::strong_count(&b) == 2);
1252 assert!(Rc::strong_count(&a) == 2);
1255 assert!(Rc::strong_count(&b) == 1);
1257 assert!(Rc::strong_count(&b) == 2);
1258 assert!(Rc::strong_count(&c) == 2);
1262 fn test_weak_count() {
1264 assert!(Rc::strong_count(&a) == 1);
1265 assert!(Rc::weak_count(&a) == 0);
1266 let w = Rc::downgrade(&a);
1267 assert!(Rc::strong_count(&a) == 1);
1268 assert!(Rc::weak_count(&a) == 1);
1270 assert!(Rc::strong_count(&a) == 1);
1271 assert!(Rc::weak_count(&a) == 0);
1273 assert!(Rc::strong_count(&a) == 2);
1274 assert!(Rc::weak_count(&a) == 0);
1281 assert_eq!(Rc::try_unwrap(x), Ok(3));
1284 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1286 let _w = Rc::downgrade(&x);
1287 assert_eq!(Rc::try_unwrap(x), Ok(5));
1292 let mut x = Rc::new(3);
1293 *Rc::get_mut(&mut x).unwrap() = 4;
1296 assert!(Rc::get_mut(&mut x).is_none());
1298 assert!(Rc::get_mut(&mut x).is_some());
1299 let _w = Rc::downgrade(&x);
1300 assert!(Rc::get_mut(&mut x).is_none());
1304 fn test_cowrc_clone_make_unique() {
1305 let mut cow0 = Rc::new(75);
1306 let mut cow1 = cow0.clone();
1307 let mut cow2 = cow1.clone();
1309 assert!(75 == *Rc::make_mut(&mut cow0));
1310 assert!(75 == *Rc::make_mut(&mut cow1));
1311 assert!(75 == *Rc::make_mut(&mut cow2));
1313 *Rc::make_mut(&mut cow0) += 1;
1314 *Rc::make_mut(&mut cow1) += 2;
1315 *Rc::make_mut(&mut cow2) += 3;
1317 assert!(76 == *cow0);
1318 assert!(77 == *cow1);
1319 assert!(78 == *cow2);
1321 // none should point to the same backing memory
1322 assert!(*cow0 != *cow1);
1323 assert!(*cow0 != *cow2);
1324 assert!(*cow1 != *cow2);
1328 fn test_cowrc_clone_unique2() {
1329 let mut cow0 = Rc::new(75);
1330 let cow1 = cow0.clone();
1331 let cow2 = cow1.clone();
1333 assert!(75 == *cow0);
1334 assert!(75 == *cow1);
1335 assert!(75 == *cow2);
1337 *Rc::make_mut(&mut cow0) += 1;
1339 assert!(76 == *cow0);
1340 assert!(75 == *cow1);
1341 assert!(75 == *cow2);
1343 // cow1 and cow2 should share the same contents
1344 // cow0 should have a unique reference
1345 assert!(*cow0 != *cow1);
1346 assert!(*cow0 != *cow2);
1347 assert!(*cow1 == *cow2);
1351 fn test_cowrc_clone_weak() {
1352 let mut cow0 = Rc::new(75);
1353 let cow1_weak = Rc::downgrade(&cow0);
1355 assert!(75 == *cow0);
1356 assert!(75 == *cow1_weak.upgrade().unwrap());
1358 *Rc::make_mut(&mut cow0) += 1;
1360 assert!(76 == *cow0);
1361 assert!(cow1_weak.upgrade().is_none());
1366 let foo = Rc::new(75);
1367 assert_eq!(format!("{:?}", foo), "75");
1372 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1373 assert_eq!(foo, foo.clone());
1377 fn test_from_owned() {
1379 let foo_rc = Rc::from(foo);
1380 assert!(123 == *foo_rc);
1384 fn test_new_weak() {
1385 let foo: Weak<usize> = Weak::new();
1386 assert!(foo.upgrade().is_none());
1391 let five = Rc::new(5);
1392 let same_five = five.clone();
1393 let other_five = Rc::new(5);
1395 assert!(Rc::ptr_eq(&five, &same_five));
1396 assert!(!Rc::ptr_eq(&five, &other_five));
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1402 fn borrow(&self) -> &T {
1407 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1408 impl<T: ?Sized> AsRef<T> for Rc<T> {
1409 fn as_ref(&self) -> &T {