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, allocated
16 //! in the heap. Invoking [`clone`][clone] on `Rc` produces a new pointer
17 //! to the same value in the heap. When the last `Rc` pointer to a given
18 //! value is destroyed, the pointed-to value is also destroyed.
20 //! Shared pointers 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:
47 //! # use std::rc::Rc;
48 //! # let my_rc = Rc::new(());
49 //! Rc::downgrade(&my_rc);
52 //! `Weak<T>` does not auto-dereference to `T`, because the value may have
53 //! already been destroyed.
55 //! [rc]: struct.Rc.html
56 //! [weak]: struct.Weak.html
57 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
58 //! [cell]: ../../std/cell/struct.Cell.html
59 //! [refcell]: ../../std/cell/struct.RefCell.html
60 //! [send]: ../../std/marker/trait.Send.html
61 //! [arc]: ../../std/sync/struct.Arc.html
62 //! [deref]: ../../std/ops/trait.Deref.html
63 //! [downgrade]: struct.Rc.html#method.downgrade
64 //! [upgrade]: struct.Weak.html#method.upgrade
65 //! [option]: ../../std/option/enum.Option.html
66 //! [assoc]: ../../book/method-syntax.html#associated-functions
70 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
71 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
72 //! unique ownership, because more than one gadget may belong to the same
73 //! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s,
74 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
81 //! // ...other fields
87 //! // ...other fields
91 //! // Create a reference-counted `Owner`.
92 //! let gadget_owner: Rc<Owner> = Rc::new(
94 //! name: "Gadget Man".to_string(),
98 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
99 //! // value gives us a new pointer to the same `Owner` value, incrementing
100 //! // the reference count in the process.
101 //! let gadget1 = Gadget {
103 //! owner: gadget_owner.clone(),
105 //! let gadget2 = Gadget {
107 //! owner: gadget_owner.clone(),
110 //! // Dispose of our local variable `gadget_owner`.
111 //! drop(gadget_owner);
113 //! // Despite dropping `gadget_owner`, we're still able to print out the name
114 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
115 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
116 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
117 //! // allocated. The field projection `gadget1.owner.name` works because
118 //! // `Rc<Owner>` automatically dereferences to `Owner`.
119 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
120 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
122 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
123 //! // with them the last counted references to our `Owner`. Gadget Man now
124 //! // gets destroyed as well.
128 //! If our requirements change, and we also need to be able to traverse from
129 //! `Owner` to `Gadget`, we will run into problems. An `Rc` pointer from `Owner`
130 //! to `Gadget` introduces a cycle between the values. This means that their
131 //! reference counts can never reach 0, and the values will remain allocated
132 //! forever: a memory leak. In order to get around this, we can use `Weak`
135 //! Rust actually makes it somewhat difficult to produce this loop in the first
136 //! place. In order to end up with two values that point at each other, one of
137 //! them needs to be mutable. This is difficult because `Rc` enforces
138 //! memory safety by only giving out shared references to the value it wraps,
139 //! and these don't allow direct mutation. We need to wrap the part of the
140 //! value we wish to mutate in a [`RefCell`][refcell], which provides *interior
141 //! mutability*: a method to achieve mutability through a shared reference.
142 //! `RefCell` enforces Rust's borrowing rules at runtime.
146 //! use std::rc::Weak;
147 //! use std::cell::RefCell;
151 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
152 //! // ...other fields
157 //! owner: Rc<Owner>,
158 //! // ...other fields
162 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
163 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
164 //! // a shared reference.
165 //! let gadget_owner: Rc<Owner> = Rc::new(
167 //! name: "Gadget Man".to_string(),
168 //! gadgets: RefCell::new(vec![]),
172 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
173 //! let gadget1 = Rc::new(
176 //! owner: gadget_owner.clone(),
179 //! let gadget2 = Rc::new(
182 //! owner: gadget_owner.clone(),
186 //! // Add the `Gadget`s to their `Owner`.
188 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
189 //! gadgets.push(Rc::downgrade(&gadget1));
190 //! gadgets.push(Rc::downgrade(&gadget2));
192 //! // `RefCell` dynamic borrow ends here.
195 //! // Iterate over our `Gadget`s, printing their details out.
196 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
198 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
199 //! // guarantee the value is still allocated, we need to call
200 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
202 //! // In this case we know the value still exists, so we simply
203 //! // `unwrap` the `Option`. In a more complicated program, you might
204 //! // need graceful error handling for a `None` result.
206 //! let gadget = gadget_weak.upgrade().unwrap();
207 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
210 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
211 //! // are destroyed. There are now no strong (`Rc`) pointers to the
212 //! // gadgets, so they are destroyed. This zeroes the reference count on
213 //! // Gadget Man, so he gets destroyed as well.
217 #![stable(feature = "rust1", since = "1.0.0")]
225 use core
::cell
::Cell
;
226 use core
::cmp
::Ordering
;
228 use core
::hash
::{Hash, Hasher}
;
229 use core
::intrinsics
::{abort, assume}
;
231 use core
::marker
::Unsize
;
232 use core
::mem
::{self, align_of_val, forget, size_of_val, uninitialized}
;
233 use core
::ops
::Deref
;
234 use core
::ops
::CoerceUnsized
;
235 use core
::ptr
::{self, Shared}
;
236 use core
::convert
::From
;
238 use heap
::deallocate
;
240 struct RcBox
<T
: ?Sized
> {
247 /// A single-threaded reference-counting pointer.
249 /// See the [module-level documentation](./index.html) for more details.
251 /// The inherent methods of `Rc` are all associated functions, which means
252 /// that you have to call them as e.g. `Rc::get_mut(&value)` instead of
253 /// `value.get_mut()`. This avoids conflicts with methods of the inner
255 #[cfg_attr(stage0, unsafe_no_drop_flag)]
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` is returned with the same `Rc` that was passed in.
300 /// This will succeed even if there are outstanding weak references.
307 /// let x = Rc::new(3);
308 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
310 /// let x = Rc::new(4);
311 /// let _y = x.clone();
312 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
315 #[stable(feature = "rc_unique", since = "1.4.0")]
316 pub fn try_unwrap(this
: Self) -> Result
<T
, Self> {
317 if Rc
::would_unwrap(&this
) {
319 let val
= ptr
::read(&*this
); // copy the contained object
321 // Indicate to Weaks that they can't be promoted by decrememting
322 // the strong count, and then remove the implicit "strong weak"
323 // pointer while also handling drop logic by just crafting a
326 let _weak
= Weak { ptr: this.ptr }
;
335 /// Checks whether `Rc::try_unwrap` would return `Ok`.
340 /// #![feature(rc_would_unwrap)]
344 /// let x = Rc::new(3);
345 /// assert!(Rc::would_unwrap(&x));
346 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
348 /// let x = Rc::new(4);
349 /// let _y = x.clone();
350 /// assert!(!Rc::would_unwrap(&x));
351 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
353 #[unstable(feature = "rc_would_unwrap",
354 reason
= "just added for niche usecase",
356 pub fn would_unwrap(this
: &Self) -> bool
{
357 Rc
::strong_count(&this
) == 1
361 impl<T
: ?Sized
> Rc
<T
> {
362 /// Creates a new [`Weak`][weak] pointer to this value.
364 /// [weak]: struct.Weak.html
371 /// let five = Rc::new(5);
373 /// let weak_five = Rc::downgrade(&five);
375 #[stable(feature = "rc_weak", since = "1.4.0")]
376 pub fn downgrade(this
: &Self) -> Weak
<T
> {
378 Weak { ptr: this.ptr }
381 /// Gets the number of [`Weak`][weak] pointers to this value.
383 /// [weak]: struct.Weak.html
388 /// #![feature(rc_counts)]
392 /// let five = Rc::new(5);
393 /// let _weak_five = Rc::downgrade(&five);
395 /// assert_eq!(1, Rc::weak_count(&five));
398 #[unstable(feature = "rc_counts", reason = "not clearly useful",
400 pub fn weak_count(this
: &Self) -> usize {
404 /// Gets the number of strong (`Rc`) pointers to this value.
409 /// #![feature(rc_counts)]
413 /// let five = Rc::new(5);
414 /// let _also_five = five.clone();
416 /// assert_eq!(2, Rc::strong_count(&five));
419 #[unstable(feature = "rc_counts", reason = "not clearly useful",
421 pub fn strong_count(this
: &Self) -> usize {
425 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
426 /// this inner value.
428 /// [weak]: struct.Weak.html
433 /// #![feature(rc_counts)]
437 /// let five = Rc::new(5);
439 /// assert!(Rc::is_unique(&five));
442 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
444 pub fn is_unique(this
: &Self) -> bool
{
445 Rc
::weak_count(this
) == 0 && Rc
::strong_count(this
) == 1
448 /// Returns a mutable reference to the inner value, if there are
449 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
451 /// Returns [`None`][option] otherwise, because it is not safe to
452 /// mutate a shared value.
454 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
455 /// the inner value when it's shared.
457 /// [weak]: struct.Weak.html
458 /// [option]: ../../std/option/enum.Option.html
459 /// [make_mut]: struct.Rc.html#method.make_mut
460 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
467 /// let mut x = Rc::new(3);
468 /// *Rc::get_mut(&mut x).unwrap() = 4;
469 /// assert_eq!(*x, 4);
471 /// let _y = x.clone();
472 /// assert!(Rc::get_mut(&mut x).is_none());
475 #[stable(feature = "rc_unique", since = "1.4.0")]
476 pub fn get_mut(this
: &mut Self) -> Option
<&mut T
> {
477 if Rc
::is_unique(this
) {
478 let inner
= unsafe { &mut **this.ptr }
;
479 Some(&mut inner
.value
)
486 #[unstable(feature = "ptr_eq",
487 reason
= "newly added",
489 /// Returns true if the two `Rc`s point to the same value (not
490 /// just values that compare as equal).
495 /// #![feature(ptr_eq)]
499 /// let five = Rc::new(5);
500 /// let same_five = five.clone();
501 /// let other_five = Rc::new(5);
503 /// assert!(Rc::ptr_eq(&five, &same_five));
504 /// assert!(!Rc::ptr_eq(&five, &other_five));
506 pub fn ptr_eq(this
: &Self, other
: &Self) -> bool
{
507 let this_ptr
: *const RcBox
<T
> = *this
.ptr
;
508 let other_ptr
: *const RcBox
<T
> = *other
.ptr
;
509 this_ptr
== other_ptr
513 impl<T
: Clone
> Rc
<T
> {
514 /// Makes a mutable reference into the given `Rc`.
516 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
517 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
518 /// ensure unique ownership. This is also referred to as clone-on-write.
520 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
522 /// [weak]: struct.Weak.html
523 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
524 /// [get_mut]: struct.Rc.html#method.get_mut
531 /// let mut data = Rc::new(5);
533 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
534 /// let mut other_data = data.clone(); // Won't clone inner data
535 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
536 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
537 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
539 /// // Now `data` and `other_data` point to different values.
540 /// assert_eq!(*data, 8);
541 /// assert_eq!(*other_data, 12);
544 #[stable(feature = "rc_unique", since = "1.4.0")]
545 pub fn make_mut(this
: &mut Self) -> &mut T
{
546 if Rc
::strong_count(this
) != 1 {
547 // Gotta clone the data, there are other Rcs
548 *this
= Rc
::new((**this
).clone())
549 } else if Rc
::weak_count(this
) != 0 {
550 // Can just steal the data, all that's left is Weaks
552 let mut swap
= Rc
::new(ptr
::read(&(**this
.ptr
).value
));
553 mem
::swap(this
, &mut swap
);
555 // Remove implicit strong-weak ref (no need to craft a fake
556 // Weak here -- we know other Weaks can clean up for us)
561 // This unsafety is ok because we're guaranteed that the pointer
562 // returned is the *only* pointer that will ever be returned to T. Our
563 // reference count is guaranteed to be 1 at this point, and we required
564 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
565 // reference to the inner value.
566 let inner
= unsafe { &mut **this.ptr }
;
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<T
: ?Sized
> Deref
for Rc
<T
> {
576 fn deref(&self) -> &T
{
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T
: ?Sized
> Drop
for Rc
<T
> {
585 /// This will decrement the strong reference count. If the strong reference
586 /// count reaches zero then the only other references (if any) are `Weak`,
587 /// so we `drop` the inner value.
596 /// impl Drop for Foo {
597 /// fn drop(&mut self) {
598 /// println!("dropped!");
602 /// let foo = Rc::new(Foo);
603 /// let foo2 = foo.clone();
605 /// drop(foo); // Doesn't print anything
606 /// drop(foo2); // Prints "dropped!"
608 #[unsafe_destructor_blind_to_params]
614 if self.strong() == 0 {
615 // destroy the contained object
616 ptr
::drop_in_place(&mut (*ptr
).value
);
618 // remove the implicit "strong weak" pointer now that we've
619 // destroyed the contents.
622 if self.weak() == 0 {
623 deallocate(ptr
as *mut u8, size_of_val(&*ptr
), align_of_val(&*ptr
))
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<T
: ?Sized
> Clone
for Rc
<T
> {
632 /// Makes a clone of the `Rc` pointer.
634 /// This creates another pointer to the same inner value, increasing the
635 /// strong reference count.
642 /// let five = Rc::new(5);
647 fn clone(&self) -> Rc
<T
> {
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl<T
: Default
> Default
for Rc
<T
> {
655 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
662 /// let x: Rc<i32> = Default::default();
663 /// assert_eq!(*x, 0);
666 fn default() -> Rc
<T
> {
667 Rc
::new(Default
::default())
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Rc
<T
> {
673 /// Equality for two `Rc`s.
675 /// Two `Rc`s are equal if their inner values are equal.
682 /// let five = Rc::new(5);
684 /// assert!(five == Rc::new(5));
687 fn eq(&self, other
: &Rc
<T
>) -> bool
{
691 /// Inequality for two `Rc`s.
693 /// Two `Rc`s are unequal if their inner values are unequal.
700 /// let five = Rc::new(5);
702 /// assert!(five != Rc::new(6));
705 fn ne(&self, other
: &Rc
<T
>) -> bool
{
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T
: ?Sized
+ Eq
> Eq
for Rc
<T
> {}
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Rc
<T
> {
715 /// Partial comparison for two `Rc`s.
717 /// The two are compared by calling `partial_cmp()` on their inner values.
723 /// use std::cmp::Ordering;
725 /// let five = Rc::new(5);
727 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
730 fn partial_cmp(&self, other
: &Rc
<T
>) -> Option
<Ordering
> {
731 (**self).partial_cmp(&**other
)
734 /// Less-than comparison for two `Rc`s.
736 /// The two are compared by calling `<` on their inner values.
743 /// let five = Rc::new(5);
745 /// assert!(five < Rc::new(6));
748 fn lt(&self, other
: &Rc
<T
>) -> bool
{
752 /// 'Less than or equal to' comparison for two `Rc`s.
754 /// The two are compared by calling `<=` on their inner values.
761 /// let five = Rc::new(5);
763 /// assert!(five <= Rc::new(5));
766 fn le(&self, other
: &Rc
<T
>) -> bool
{
770 /// Greater-than comparison for two `Rc`s.
772 /// The two are compared by calling `>` on their inner values.
779 /// let five = Rc::new(5);
781 /// assert!(five > Rc::new(4));
784 fn gt(&self, other
: &Rc
<T
>) -> bool
{
788 /// 'Greater than or equal to' comparison for two `Rc`s.
790 /// The two are compared by calling `>=` on their inner values.
797 /// let five = Rc::new(5);
799 /// assert!(five >= Rc::new(5));
802 fn ge(&self, other
: &Rc
<T
>) -> bool
{
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<T
: ?Sized
+ Ord
> Ord
for Rc
<T
> {
809 /// Comparison for two `Rc`s.
811 /// The two are compared by calling `cmp()` on their inner values.
817 /// use std::cmp::Ordering;
819 /// let five = Rc::new(5);
821 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
824 fn cmp(&self, other
: &Rc
<T
>) -> Ordering
{
825 (**self).cmp(&**other
)
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<T
: ?Sized
+ Hash
> Hash
for Rc
<T
> {
831 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
832 (**self).hash(state
);
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<T
: ?Sized
+ fmt
::Display
> fmt
::Display
for Rc
<T
> {
838 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
839 fmt
::Display
::fmt(&**self, f
)
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Rc
<T
> {
845 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
846 fmt
::Debug
::fmt(&**self, f
)
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<T
: ?Sized
> fmt
::Pointer
for Rc
<T
> {
852 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
853 fmt
::Pointer
::fmt(&*self.ptr
, f
)
857 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
858 impl<T
> From
<T
> for Rc
<T
> {
859 fn from(t
: T
) -> Self {
864 /// A weak version of [`Rc`][rc].
866 /// `Weak` pointers do not count towards determining if the inner value
867 /// should be dropped.
869 /// The typical way to obtain a `Weak` pointer is to call
870 /// [`Rc::downgrade`][downgrade].
872 /// See the [module-level documentation](./index.html) for more details.
874 /// [rc]: struct.Rc.html
875 /// [downgrade]: struct.Rc.html#method.downgrade
876 #[cfg_attr(stage0, unsafe_no_drop_flag)]
877 #[stable(feature = "rc_weak", since = "1.4.0")]
878 pub struct Weak
<T
: ?Sized
> {
879 ptr
: Shared
<RcBox
<T
>>,
882 #[stable(feature = "rc_weak", since = "1.4.0")]
883 impl<T
: ?Sized
> !marker
::Send
for Weak
<T
> {}
884 #[stable(feature = "rc_weak", since = "1.4.0")]
885 impl<T
: ?Sized
> !marker
::Sync
for Weak
<T
> {}
887 #[unstable(feature = "coerce_unsized", issue = "27732")]
888 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Weak
<U
>> for Weak
<T
> {}
891 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
893 /// This allocates memory for `T`, but does not initialize it. Calling
894 /// [`upgrade`][upgrade] on the return value always gives
895 /// [`None`][option].
897 /// [upgrade]: struct.Weak.html#method.upgrade
898 /// [option]: ../../std/option/enum.Option.html
903 /// use std::rc::Weak;
905 /// let empty: Weak<i64> = Weak::new();
906 /// assert!(empty.upgrade().is_none());
908 #[stable(feature = "downgraded_weak", since = "1.10.0")]
909 pub fn new() -> Weak
<T
> {
912 ptr
: Shared
::new(Box
::into_raw(box RcBox
{
913 strong
: Cell
::new(0),
915 value
: uninitialized(),
922 impl<T
: ?Sized
> Weak
<T
> {
923 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
925 /// Returns [`None`][option] if the strong count has reached zero and the
926 /// inner value was destroyed.
928 /// [rc]: struct.Rc.html
929 /// [option]: ../../std/option/enum.Option.html
936 /// let five = Rc::new(5);
938 /// let weak_five = Rc::downgrade(&five);
940 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
941 /// assert!(strong_five.is_some());
943 /// // Destroy all strong pointers.
944 /// drop(strong_five);
947 /// assert!(weak_five.upgrade().is_none());
949 #[stable(feature = "rc_weak", since = "1.4.0")]
950 pub fn upgrade(&self) -> Option
<Rc
<T
>> {
951 if self.strong() == 0 {
955 Some(Rc { ptr: self.ptr }
)
960 #[stable(feature = "rc_weak", since = "1.4.0")]
961 impl<T
: ?Sized
> Drop
for Weak
<T
> {
962 /// Drops the `Weak` pointer.
964 /// This will decrement the weak reference count.
973 /// impl Drop for Foo {
974 /// fn drop(&mut self) {
975 /// println!("dropped!");
979 /// let foo = Rc::new(Foo);
980 /// let weak_foo = Rc::downgrade(&foo);
981 /// let other_weak_foo = weak_foo.clone();
983 /// drop(weak_foo); // Doesn't print anything
984 /// drop(foo); // Prints "dropped!"
986 /// assert!(other_weak_foo.upgrade().is_none());
993 // the weak count starts at 1, and will only go to zero if all
994 // the strong pointers have disappeared.
995 if self.weak() == 0 {
996 deallocate(ptr
as *mut u8, size_of_val(&*ptr
), align_of_val(&*ptr
))
1002 #[stable(feature = "rc_weak", since = "1.4.0")]
1003 impl<T
: ?Sized
> Clone
for Weak
<T
> {
1004 /// Makes a clone of the `Weak` pointer.
1006 /// This creates another pointer to the same inner value, increasing the
1007 /// weak reference count.
1012 /// use std::rc::Rc;
1014 /// let weak_five = Rc::downgrade(&Rc::new(5));
1016 /// weak_five.clone();
1019 fn clone(&self) -> Weak
<T
> {
1021 Weak { ptr: self.ptr }
1025 #[stable(feature = "rc_weak", since = "1.4.0")]
1026 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Weak
<T
> {
1027 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1032 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1033 impl<T
> Default
for Weak
<T
> {
1034 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1036 /// This allocates memory for `T`, but does not initialize it. Calling
1037 /// [`upgrade`][upgrade] on the return value always gives
1038 /// [`None`][option].
1040 /// [upgrade]: struct.Weak.html#method.upgrade
1041 /// [option]: ../../std/option/enum.Option.html
1046 /// use std::rc::Weak;
1048 /// let empty: Weak<i64> = Default::default();
1049 /// assert!(empty.upgrade().is_none());
1051 fn default() -> Weak
<T
> {
1056 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1057 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1058 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1059 // We abort because this is such a degenerate scenario that we don't care about
1060 // what happens -- no real program should ever experience this.
1062 // This should have negligible overhead since you don't actually need to
1063 // clone these much in Rust thanks to ownership and move-semantics.
1066 trait RcBoxPtr
<T
: ?Sized
> {
1067 fn inner(&self) -> &RcBox
<T
>;
1070 fn strong(&self) -> usize {
1071 self.inner().strong
.get()
1075 fn inc_strong(&self) {
1076 self.inner().strong
.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }
));
1080 fn dec_strong(&self) {
1081 self.inner().strong
.set(self.strong() - 1);
1085 fn weak(&self) -> usize {
1086 self.inner().weak
.get()
1090 fn inc_weak(&self) {
1091 self.inner().weak
.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }
));
1095 fn dec_weak(&self) {
1096 self.inner().weak
.set(self.weak() - 1);
1100 impl<T
: ?Sized
> RcBoxPtr
<T
> for Rc
<T
> {
1102 fn inner(&self) -> &RcBox
<T
> {
1104 // Safe to assume this here, as if it weren't true, we'd be breaking
1105 // the contract anyway.
1106 // This allows the null check to be elided in the destructor if we
1107 // manipulated the reference count in the same function.
1108 assume(!(*(&self.ptr
as *const _
as *const *const ())).is_null());
1114 impl<T
: ?Sized
> RcBoxPtr
<T
> for Weak
<T
> {
1116 fn inner(&self) -> &RcBox
<T
> {
1118 // Safe to assume this here, as if it weren't true, we'd be breaking
1119 // the contract anyway.
1120 // This allows the null check to be elided in the destructor if we
1121 // manipulated the reference count in the same function.
1122 assume(!(*(&self.ptr
as *const _
as *const *const ())).is_null());
1130 use super::{Rc, Weak}
;
1131 use std
::boxed
::Box
;
1132 use std
::cell
::RefCell
;
1133 use std
::option
::Option
;
1134 use std
::option
::Option
::{None, Some}
;
1135 use std
::result
::Result
::{Err, Ok}
;
1137 use std
::clone
::Clone
;
1138 use std
::convert
::From
;
1142 let x
= Rc
::new(RefCell
::new(5));
1144 *x
.borrow_mut() = 20;
1145 assert_eq
!(*y
.borrow(), 20);
1155 fn test_simple_clone() {
1163 fn test_destructor() {
1164 let x
: Rc
<Box
<_
>> = Rc
::new(box 5);
1171 let y
= Rc
::downgrade(&x
);
1172 assert
!(y
.upgrade().is_some());
1178 let y
= Rc
::downgrade(&x
);
1180 assert
!(y
.upgrade().is_none());
1184 fn weak_self_cyclic() {
1186 x
: RefCell
<Option
<Weak
<Cycle
>>>,
1189 let a
= Rc
::new(Cycle { x: RefCell::new(None) }
);
1190 let b
= Rc
::downgrade(&a
.clone());
1191 *a
.x
.borrow_mut() = Some(b
);
1193 // hopefully we don't double-free (or leak)...
1199 assert
!(Rc
::is_unique(&x
));
1201 assert
!(!Rc
::is_unique(&x
));
1203 assert
!(Rc
::is_unique(&x
));
1204 let w
= Rc
::downgrade(&x
);
1205 assert
!(!Rc
::is_unique(&x
));
1207 assert
!(Rc
::is_unique(&x
));
1211 fn test_strong_count() {
1213 assert
!(Rc
::strong_count(&a
) == 1);
1214 let w
= Rc
::downgrade(&a
);
1215 assert
!(Rc
::strong_count(&a
) == 1);
1216 let b
= w
.upgrade().expect("upgrade of live rc failed");
1217 assert
!(Rc
::strong_count(&b
) == 2);
1218 assert
!(Rc
::strong_count(&a
) == 2);
1221 assert
!(Rc
::strong_count(&b
) == 1);
1223 assert
!(Rc
::strong_count(&b
) == 2);
1224 assert
!(Rc
::strong_count(&c
) == 2);
1228 fn test_weak_count() {
1230 assert
!(Rc
::strong_count(&a
) == 1);
1231 assert
!(Rc
::weak_count(&a
) == 0);
1232 let w
= Rc
::downgrade(&a
);
1233 assert
!(Rc
::strong_count(&a
) == 1);
1234 assert
!(Rc
::weak_count(&a
) == 1);
1236 assert
!(Rc
::strong_count(&a
) == 1);
1237 assert
!(Rc
::weak_count(&a
) == 0);
1239 assert
!(Rc
::strong_count(&a
) == 2);
1240 assert
!(Rc
::weak_count(&a
) == 0);
1247 assert_eq
!(Rc
::try_unwrap(x
), Ok(3));
1250 assert_eq
!(Rc
::try_unwrap(x
), Err(Rc
::new(4)));
1252 let _w
= Rc
::downgrade(&x
);
1253 assert_eq
!(Rc
::try_unwrap(x
), Ok(5));
1258 let mut x
= Rc
::new(3);
1259 *Rc
::get_mut(&mut x
).unwrap() = 4;
1262 assert
!(Rc
::get_mut(&mut x
).is_none());
1264 assert
!(Rc
::get_mut(&mut x
).is_some());
1265 let _w
= Rc
::downgrade(&x
);
1266 assert
!(Rc
::get_mut(&mut x
).is_none());
1270 fn test_cowrc_clone_make_unique() {
1271 let mut cow0
= Rc
::new(75);
1272 let mut cow1
= cow0
.clone();
1273 let mut cow2
= cow1
.clone();
1275 assert
!(75 == *Rc
::make_mut(&mut cow0
));
1276 assert
!(75 == *Rc
::make_mut(&mut cow1
));
1277 assert
!(75 == *Rc
::make_mut(&mut cow2
));
1279 *Rc
::make_mut(&mut cow0
) += 1;
1280 *Rc
::make_mut(&mut cow1
) += 2;
1281 *Rc
::make_mut(&mut cow2
) += 3;
1283 assert
!(76 == *cow0
);
1284 assert
!(77 == *cow1
);
1285 assert
!(78 == *cow2
);
1287 // none should point to the same backing memory
1288 assert
!(*cow0
!= *cow1
);
1289 assert
!(*cow0
!= *cow2
);
1290 assert
!(*cow1
!= *cow2
);
1294 fn test_cowrc_clone_unique2() {
1295 let mut cow0
= Rc
::new(75);
1296 let cow1
= cow0
.clone();
1297 let cow2
= cow1
.clone();
1299 assert
!(75 == *cow0
);
1300 assert
!(75 == *cow1
);
1301 assert
!(75 == *cow2
);
1303 *Rc
::make_mut(&mut cow0
) += 1;
1305 assert
!(76 == *cow0
);
1306 assert
!(75 == *cow1
);
1307 assert
!(75 == *cow2
);
1309 // cow1 and cow2 should share the same contents
1310 // cow0 should have a unique reference
1311 assert
!(*cow0
!= *cow1
);
1312 assert
!(*cow0
!= *cow2
);
1313 assert
!(*cow1
== *cow2
);
1317 fn test_cowrc_clone_weak() {
1318 let mut cow0
= Rc
::new(75);
1319 let cow1_weak
= Rc
::downgrade(&cow0
);
1321 assert
!(75 == *cow0
);
1322 assert
!(75 == *cow1_weak
.upgrade().unwrap());
1324 *Rc
::make_mut(&mut cow0
) += 1;
1326 assert
!(76 == *cow0
);
1327 assert
!(cow1_weak
.upgrade().is_none());
1332 let foo
= Rc
::new(75);
1333 assert_eq
!(format
!("{:?}", foo
), "75");
1338 let foo
: Rc
<[i32]> = Rc
::new([1, 2, 3]);
1339 assert_eq
!(foo
, foo
.clone());
1343 fn test_from_owned() {
1345 let foo_rc
= Rc
::from(foo
);
1346 assert
!(123 == *foo_rc
);
1350 fn test_new_weak() {
1351 let foo
: Weak
<usize> = Weak
::new();
1352 assert
!(foo
.upgrade().is_none());
1357 let five
= Rc
::new(5);
1358 let same_five
= five
.clone();
1359 let other_five
= Rc
::new(5);
1361 assert
!(Rc
::ptr_eq(&five
, &same_five
));
1362 assert
!(!Rc
::ptr_eq(&five
, &other_five
));
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl<T
: ?Sized
> borrow
::Borrow
<T
> for Rc
<T
> {
1368 fn borrow(&self) -> &T
{
1373 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1374 impl<T
: ?Sized
> AsRef
<T
> for Rc
<T
> {
1375 fn as_ref(&self) -> &T
{