1 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
4 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
5 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
6 //! pointer to the same allocation in the heap. When the last [`Rc`] pointer to a
7 //! given allocation is destroyed, the value stored in that allocation (often
8 //! referred to as "inner value") is also dropped.
10 //! Shared references in Rust disallow mutation by default, and [`Rc`]
11 //! is no exception: you cannot generally obtain a mutable reference to
12 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
13 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
14 //! inside an Rc][mutability].
16 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
17 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
18 //! does not implement [`Send`][send]. As a result, the Rust compiler
19 //! will check *at compile time* that you are not sending [`Rc`]s between
20 //! threads. If you need multi-threaded, atomic reference counting, use
21 //! [`sync::Arc`][arc].
23 //! The [`downgrade`][downgrade] method can be used to create a non-owning
24 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
25 //! to an [`Rc`], but this will return [`None`] if the value stored in the allocation has
26 //! already been dropped. In other words, `Weak` pointers do not keep the value
27 //! inside the allocation alive; however, they *do* keep the allocation
28 //! (the backing store for the inner value) alive.
30 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
31 //! [`Weak`] is used to break cycles. For example, a tree could have strong
32 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
33 //! children back to their parents.
35 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
36 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
37 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
38 //! functions, called using function-like syntax:
42 //! let my_rc = Rc::new(());
44 //! Rc::downgrade(&my_rc);
47 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
48 //! already been dropped.
50 //! # Cloning references
52 //! Creating a new reference to the same allocation as an existing reference counted pointer
53 //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
57 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
58 //! // The two syntaxes below are equivalent.
59 //! let a = foo.clone();
60 //! let b = Rc::clone(&foo);
61 //! // a and b both point to the same memory location as foo.
64 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
65 //! the meaning of the code. In the example above, this syntax makes it easier to see that
66 //! this code is creating a new reference rather than copying the whole content of foo.
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 //! // gives us a new pointer to the same `Owner` allocation, incrementing
100 //! // the reference count in the process.
101 //! let gadget1 = Gadget {
103 //! owner: Rc::clone(&gadget_owner),
105 //! let gadget2 = Gadget {
107 //! owner: Rc::clone(&gadget_owner),
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>` pointing at the same `Owner` allocation, it will remain
117 //! // live. 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. This means that their
131 //! reference counts can never reach 0, and the allocation will never be destroyed:
132 //! 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`], 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: Rc::clone(&gadget_owner),
179 //! let gadget2 = Rc::new(
182 //! owner: Rc::clone(&gadget_owner),
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 allocation still exists, we need to call
200 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
202 //! // In this case we know the allocation 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 //! [`Rc`]: struct.Rc.html
218 //! [`Weak`]: struct.Weak.html
219 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
220 //! [`Cell`]: ../../std/cell/struct.Cell.html
221 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
222 //! [send]: ../../std/marker/trait.Send.html
223 //! [arc]: ../../std/sync/struct.Arc.html
224 //! [`Deref`]: ../../std/ops/trait.Deref.html
225 //! [downgrade]: struct.Rc.html#method.downgrade
226 //! [upgrade]: struct.Weak.html#method.upgrade
227 //! [`None`]: ../../std/option/enum.Option.html#variant.None
228 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
230 #![stable(feature = "rust1", since = "1.0.0")]
233 use crate::boxed
::Box
;
238 use core
::array
::LengthAtMost32
;
240 use core
::cell
::Cell
;
241 use core
::cmp
::Ordering
;
243 use core
::hash
::{Hash, Hasher}
;
244 use core
::intrinsics
::abort
;
246 use core
::marker
::{self, Unpin, Unsize, PhantomData}
;
247 use core
::mem
::{self, align_of, align_of_val, forget, size_of_val}
;
248 use core
::ops
::{Deref, Receiver, CoerceUnsized, DispatchFromDyn}
;
250 use core
::ptr
::{self, NonNull}
;
251 use core
::slice
::{self, from_raw_parts_mut}
;
252 use core
::convert
::{From, TryFrom}
;
255 use crate::alloc
::{Global, Alloc, Layout, box_free, handle_alloc_error}
;
256 use crate::string
::String
;
262 struct RcBox
<T
: ?Sized
> {
268 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
271 /// See the [module-level documentation](./index.html) for more details.
273 /// The inherent methods of `Rc` are all associated functions, which means
274 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
275 /// `value.get_mut()`. This avoids conflicts with methods of the inner
278 /// [get_mut]: #method.get_mut
279 #[cfg_attr(not(test), lang = "rc")]
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub struct Rc
<T
: ?Sized
> {
282 ptr
: NonNull
<RcBox
<T
>>,
283 phantom
: PhantomData
<RcBox
<T
>>,
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T
: ?Sized
> !marker
::Send
for Rc
<T
> {}
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T
: ?Sized
> !marker
::Sync
for Rc
<T
> {}
291 #[unstable(feature = "coerce_unsized", issue = "27732")]
292 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Rc
<U
>> for Rc
<T
> {}
294 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
295 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> DispatchFromDyn
<Rc
<U
>> for Rc
<T
> {}
297 impl<T
: ?Sized
> Rc
<T
> {
298 fn from_inner(ptr
: NonNull
<RcBox
<T
>>) -> Self {
301 phantom
: PhantomData
,
305 unsafe fn from_ptr(ptr
: *mut RcBox
<T
>) -> Self {
306 Self::from_inner(NonNull
::new_unchecked(ptr
))
311 /// Constructs a new `Rc<T>`.
318 /// let five = Rc::new(5);
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn new(value
: T
) -> Rc
<T
> {
322 // There is an implicit weak pointer owned by all the strong
323 // pointers, which ensures that the weak destructor never frees
324 // the allocation while the strong destructor is running, even
325 // if the weak pointer is stored inside the strong one.
326 Self::from_inner(Box
::into_raw_non_null(box RcBox
{
327 strong
: Cell
::new(1),
333 /// Constructs a new `Rc` with uninitialized contents.
338 /// #![feature(new_uninit)]
339 /// #![feature(get_mut_unchecked)]
343 /// let mut five = Rc::<u32>::new_uninit();
345 /// let five = unsafe {
346 /// // Deferred initialization:
347 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
349 /// five.assume_init()
352 /// assert_eq!(*five, 5)
354 #[unstable(feature = "new_uninit", issue = "63291")]
355 pub fn new_uninit() -> Rc
<mem
::MaybeUninit
<T
>> {
357 Rc
::from_ptr(Rc
::allocate_for_layout(
359 |mem
| mem
as *mut RcBox
<mem
::MaybeUninit
<T
>>,
364 /// Constructs a new `Rc` with uninitialized contents, with the memory
365 /// being filled with `0` bytes.
367 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
368 /// incorrect usage of this method.
373 /// #![feature(new_uninit)]
377 /// let zero = Rc::<u32>::new_zeroed();
378 /// let zero = unsafe { zero.assume_init() };
380 /// assert_eq!(*zero, 0)
383 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
384 #[unstable(feature = "new_uninit", issue = "63291")]
385 pub fn new_zeroed() -> Rc
<mem
::MaybeUninit
<T
>> {
387 let mut uninit
= Self::new_uninit();
388 ptr
::write_bytes
::<T
>(Rc
::get_mut_unchecked(&mut uninit
).as_mut_ptr(), 0, 1);
393 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
394 /// `value` will be pinned in memory and unable to be moved.
395 #[stable(feature = "pin", since = "1.33.0")]
396 pub fn pin(value
: T
) -> Pin
<Rc
<T
>> {
397 unsafe { Pin::new_unchecked(Rc::new(value)) }
400 /// Returns the inner value, if the `Rc` has exactly one strong reference.
402 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
405 /// This will succeed even if there are outstanding weak references.
407 /// [result]: ../../std/result/enum.Result.html
414 /// let x = Rc::new(3);
415 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
417 /// let x = Rc::new(4);
418 /// let _y = Rc::clone(&x);
419 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
422 #[stable(feature = "rc_unique", since = "1.4.0")]
423 pub fn try_unwrap(this
: Self) -> Result
<T
, Self> {
424 if Rc
::strong_count(&this
) == 1 {
426 let val
= ptr
::read(&*this
); // copy the contained object
428 // Indicate to Weaks that they can't be promoted by decrementing
429 // the strong count, and then remove the implicit "strong weak"
430 // pointer while also handling drop logic by just crafting a
433 let _weak
= Weak { ptr: this.ptr }
;
444 /// Constructs a new reference-counted slice with uninitialized contents.
449 /// #![feature(new_uninit)]
450 /// #![feature(get_mut_unchecked)]
454 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
456 /// let values = unsafe {
457 /// // Deferred initialization:
458 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
459 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
460 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
462 /// values.assume_init()
465 /// assert_eq!(*values, [1, 2, 3])
467 #[unstable(feature = "new_uninit", issue = "63291")]
468 pub fn new_uninit_slice(len
: usize) -> Rc
<[mem
::MaybeUninit
<T
>]> {
470 Rc
::from_ptr(Rc
::allocate_for_slice(len
))
475 impl<T
> Rc
<mem
::MaybeUninit
<T
>> {
476 /// Converts to `Rc<T>`.
480 /// As with [`MaybeUninit::assume_init`],
481 /// it is up to the caller to guarantee that the inner value
482 /// really is in an initialized state.
483 /// Calling this when the content is not yet fully initialized
484 /// causes immediate undefined behavior.
486 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
491 /// #![feature(new_uninit)]
492 /// #![feature(get_mut_unchecked)]
496 /// let mut five = Rc::<u32>::new_uninit();
498 /// let five = unsafe {
499 /// // Deferred initialization:
500 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
502 /// five.assume_init()
505 /// assert_eq!(*five, 5)
507 #[unstable(feature = "new_uninit", issue = "63291")]
509 pub unsafe fn assume_init(self) -> Rc
<T
> {
510 Rc
::from_inner(mem
::ManuallyDrop
::new(self).ptr
.cast())
514 impl<T
> Rc
<[mem
::MaybeUninit
<T
>]> {
515 /// Converts to `Rc<[T]>`.
519 /// As with [`MaybeUninit::assume_init`],
520 /// it is up to the caller to guarantee that the inner value
521 /// really is in an initialized state.
522 /// Calling this when the content is not yet fully initialized
523 /// causes immediate undefined behavior.
525 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
530 /// #![feature(new_uninit)]
531 /// #![feature(get_mut_unchecked)]
535 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
537 /// let values = unsafe {
538 /// // Deferred initialization:
539 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
540 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
541 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
543 /// values.assume_init()
546 /// assert_eq!(*values, [1, 2, 3])
548 #[unstable(feature = "new_uninit", issue = "63291")]
550 pub unsafe fn assume_init(self) -> Rc
<[T
]> {
551 Rc
::from_ptr(mem
::ManuallyDrop
::new(self).ptr
.as_ptr() as _
)
555 impl<T
: ?Sized
> Rc
<T
> {
556 /// Consumes the `Rc`, returning the wrapped pointer.
558 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
559 /// [`Rc::from_raw`][from_raw].
561 /// [from_raw]: struct.Rc.html#method.from_raw
568 /// let x = Rc::new("hello".to_owned());
569 /// let x_ptr = Rc::into_raw(x);
570 /// assert_eq!(unsafe { &*x_ptr }, "hello");
572 #[stable(feature = "rc_raw", since = "1.17.0")]
573 pub fn into_raw(this
: Self) -> *const T
{
574 let ptr
: *const T
= &*this
;
579 /// Constructs an `Rc` from a raw pointer.
581 /// The raw pointer must have been previously returned by a call to a
582 /// [`Rc::into_raw`][into_raw].
584 /// This function is unsafe because improper use may lead to memory problems. For example, a
585 /// double-free may occur if the function is called twice on the same raw pointer.
587 /// [into_raw]: struct.Rc.html#method.into_raw
594 /// let x = Rc::new("hello".to_owned());
595 /// let x_ptr = Rc::into_raw(x);
598 /// // Convert back to an `Rc` to prevent leak.
599 /// let x = Rc::from_raw(x_ptr);
600 /// assert_eq!(&*x, "hello");
602 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
605 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
607 #[stable(feature = "rc_raw", since = "1.17.0")]
608 pub unsafe fn from_raw(ptr
: *const T
) -> Self {
609 let offset
= data_offset(ptr
);
611 // Reverse the offset to find the original RcBox.
612 let fake_ptr
= ptr
as *mut RcBox
<T
>;
613 let rc_ptr
= set_data_ptr(fake_ptr
, (ptr
as *mut u8).offset(-offset
));
615 Self::from_ptr(rc_ptr
)
618 /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
623 /// #![feature(rc_into_raw_non_null)]
627 /// let x = Rc::new("hello".to_owned());
628 /// let ptr = Rc::into_raw_non_null(x);
629 /// let deref = unsafe { ptr.as_ref() };
630 /// assert_eq!(deref, "hello");
632 #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
634 pub fn into_raw_non_null(this
: Self) -> NonNull
<T
> {
635 // safe because Rc guarantees its pointer is non-null
636 unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
639 /// Creates a new [`Weak`][weak] pointer to this allocation.
641 /// [weak]: struct.Weak.html
648 /// let five = Rc::new(5);
650 /// let weak_five = Rc::downgrade(&five);
652 #[stable(feature = "rc_weak", since = "1.4.0")]
653 pub fn downgrade(this
: &Self) -> Weak
<T
> {
655 // Make sure we do not create a dangling Weak
656 debug_assert
!(!is_dangling(this
.ptr
));
657 Weak { ptr: this.ptr }
660 /// Gets the number of [`Weak`][weak] pointers to this allocation.
662 /// [weak]: struct.Weak.html
669 /// let five = Rc::new(5);
670 /// let _weak_five = Rc::downgrade(&five);
672 /// assert_eq!(1, Rc::weak_count(&five));
675 #[stable(feature = "rc_counts", since = "1.15.0")]
676 pub fn weak_count(this
: &Self) -> usize {
680 /// Gets the number of strong (`Rc`) pointers to this allocation.
687 /// let five = Rc::new(5);
688 /// let _also_five = Rc::clone(&five);
690 /// assert_eq!(2, Rc::strong_count(&five));
693 #[stable(feature = "rc_counts", since = "1.15.0")]
694 pub fn strong_count(this
: &Self) -> usize {
698 /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
701 /// [weak]: struct.Weak.html
703 fn is_unique(this
: &Self) -> bool
{
704 Rc
::weak_count(this
) == 0 && Rc
::strong_count(this
) == 1
707 /// Returns a mutable reference into the given `Rc`, if there are
708 /// no other `Rc` or [`Weak`][weak] pointers to the same allocation.
710 /// Returns [`None`] otherwise, because it is not safe to
711 /// mutate a shared value.
713 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
714 /// the inner value when there are other pointers.
716 /// [weak]: struct.Weak.html
717 /// [`None`]: ../../std/option/enum.Option.html#variant.None
718 /// [make_mut]: struct.Rc.html#method.make_mut
719 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
726 /// let mut x = Rc::new(3);
727 /// *Rc::get_mut(&mut x).unwrap() = 4;
728 /// assert_eq!(*x, 4);
730 /// let _y = Rc::clone(&x);
731 /// assert!(Rc::get_mut(&mut x).is_none());
734 #[stable(feature = "rc_unique", since = "1.4.0")]
735 pub fn get_mut(this
: &mut Self) -> Option
<&mut T
> {
736 if Rc
::is_unique(this
) {
738 Some(Rc
::get_mut_unchecked(this
))
745 /// Returns a mutable reference into the given `Rc`,
746 /// without any check.
748 /// See also [`get_mut`], which is safe and does appropriate checks.
750 /// [`get_mut`]: struct.Rc.html#method.get_mut
754 /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced
755 /// for the duration of the returned borrow.
756 /// This is trivially the case if no such pointers exist,
757 /// for example immediately after `Rc::new`.
762 /// #![feature(get_mut_unchecked)]
766 /// let mut x = Rc::new(String::new());
768 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
770 /// assert_eq!(*x, "foo");
773 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
774 pub unsafe fn get_mut_unchecked(this
: &mut Self) -> &mut T
{
775 &mut this
.ptr
.as_mut().value
779 #[stable(feature = "ptr_eq", since = "1.17.0")]
780 /// Returns `true` if the two `Rc`s point to the same allocation
781 /// (in a vein similar to [`ptr::eq`]).
788 /// let five = Rc::new(5);
789 /// let same_five = Rc::clone(&five);
790 /// let other_five = Rc::new(5);
792 /// assert!(Rc::ptr_eq(&five, &same_five));
793 /// assert!(!Rc::ptr_eq(&five, &other_five));
796 /// [`ptr::eq`]: ../../std/ptr/fn.eq.html
797 pub fn ptr_eq(this
: &Self, other
: &Self) -> bool
{
798 this
.ptr
.as_ptr() == other
.ptr
.as_ptr()
802 impl<T
: Clone
> Rc
<T
> {
803 /// Makes a mutable reference into the given `Rc`.
805 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
806 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
807 /// referred to as clone-on-write.
809 /// If there are no other `Rc` pointers to this allocation, then [`Weak`]
810 /// pointers to this allocation will be disassociated.
812 /// See also [`get_mut`], which will fail rather than cloning.
814 /// [`Weak`]: struct.Weak.html
815 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
816 /// [`get_mut`]: struct.Rc.html#method.get_mut
823 /// let mut data = Rc::new(5);
825 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
826 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
827 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
828 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
829 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
831 /// // Now `data` and `other_data` point to different allocations.
832 /// assert_eq!(*data, 8);
833 /// assert_eq!(*other_data, 12);
836 /// [`Weak`] pointers will be disassociated:
841 /// let mut data = Rc::new(75);
842 /// let weak = Rc::downgrade(&data);
844 /// assert!(75 == *data);
845 /// assert!(75 == *weak.upgrade().unwrap());
847 /// *Rc::make_mut(&mut data) += 1;
849 /// assert!(76 == *data);
850 /// assert!(weak.upgrade().is_none());
853 #[stable(feature = "rc_unique", since = "1.4.0")]
854 pub fn make_mut(this
: &mut Self) -> &mut T
{
855 if Rc
::strong_count(this
) != 1 {
856 // Gotta clone the data, there are other Rcs
857 *this
= Rc
::new((**this
).clone())
858 } else if Rc
::weak_count(this
) != 0 {
859 // Can just steal the data, all that's left is Weaks
861 let mut swap
= Rc
::new(ptr
::read(&this
.ptr
.as_ref().value
));
862 mem
::swap(this
, &mut swap
);
864 // Remove implicit strong-weak ref (no need to craft a fake
865 // Weak here -- we know other Weaks can clean up for us)
870 // This unsafety is ok because we're guaranteed that the pointer
871 // returned is the *only* pointer that will ever be returned to T. Our
872 // reference count is guaranteed to be 1 at this point, and we required
873 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
874 // reference to the allocation.
876 &mut this
.ptr
.as_mut().value
883 #[stable(feature = "rc_downcast", since = "1.29.0")]
884 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
889 /// use std::any::Any;
892 /// fn print_if_string(value: Rc<dyn Any>) {
893 /// if let Ok(string) = value.downcast::<String>() {
894 /// println!("String ({}): {}", string.len(), string);
898 /// let my_string = "Hello World".to_string();
899 /// print_if_string(Rc::new(my_string));
900 /// print_if_string(Rc::new(0i8));
902 pub fn downcast
<T
: Any
>(self) -> Result
<Rc
<T
>, Rc
<dyn Any
>> {
903 if (*self).is
::<T
>() {
904 let ptr
= self.ptr
.cast
::<RcBox
<T
>>();
906 Ok(Rc
::from_inner(ptr
))
913 impl<T
: ?Sized
> Rc
<T
> {
914 /// Allocates an `RcBox<T>` with sufficient space for
915 /// a possibly-unsized inner value where the value has the layout provided.
917 /// The function `mem_to_rcbox` is called with the data pointer
918 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
919 unsafe fn allocate_for_layout(
920 value_layout
: Layout
,
921 mem_to_rcbox
: impl FnOnce(*mut u8) -> *mut RcBox
<T
>
923 // Calculate layout using the given value layout.
924 // Previously, layout was calculated on the expression
925 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
926 // reference (see #54908).
927 let layout
= Layout
::new
::<RcBox
<()>>()
928 .extend(value_layout
).unwrap().0
931 // Allocate for the layout.
932 let mem
= Global
.alloc(layout
)
933 .unwrap_or_else(|_
| handle_alloc_error(layout
));
935 // Initialize the RcBox
936 let inner
= mem_to_rcbox(mem
.as_ptr());
937 debug_assert_eq
!(Layout
::for_value(&*inner
), layout
);
939 ptr
::write(&mut (*inner
).strong
, Cell
::new(1));
940 ptr
::write(&mut (*inner
).weak
, Cell
::new(1));
945 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
946 unsafe fn allocate_for_ptr(ptr
: *const T
) -> *mut RcBox
<T
> {
947 // Allocate for the `RcBox<T>` using the given value.
948 Self::allocate_for_layout(
949 Layout
::for_value(&*ptr
),
950 |mem
| set_data_ptr(ptr
as *mut T
, mem
) as *mut RcBox
<T
>,
954 fn from_box(v
: Box
<T
>) -> Rc
<T
> {
956 let box_unique
= Box
::into_unique(v
);
957 let bptr
= box_unique
.as_ptr();
959 let value_size
= size_of_val(&*bptr
);
960 let ptr
= Self::allocate_for_ptr(bptr
);
962 // Copy value as bytes
963 ptr
::copy_nonoverlapping(
964 bptr
as *const T
as *const u8,
965 &mut (*ptr
).value
as *mut _
as *mut u8,
968 // Free the allocation without dropping its contents
969 box_free(box_unique
);
977 /// Allocates an `RcBox<[T]>` with the given length.
978 unsafe fn allocate_for_slice(len
: usize) -> *mut RcBox
<[T
]> {
979 Self::allocate_for_layout(
980 Layout
::array
::<T
>(len
).unwrap(),
981 |mem
| ptr
::slice_from_raw_parts_mut(mem
as *mut T
, len
) as *mut RcBox
<[T
]>,
986 /// Sets the data pointer of a `?Sized` raw pointer.
988 /// For a slice/trait object, this sets the `data` field and leaves the rest
989 /// unchanged. For a sized raw pointer, this simply sets the pointer.
990 unsafe fn set_data_ptr
<T
: ?Sized
, U
>(mut ptr
: *mut T
, data
: *mut U
) -> *mut T
{
991 ptr
::write(&mut ptr
as *mut _
as *mut *mut u8, data
as *mut u8);
996 /// Copy elements from slice into newly allocated Rc<[T]>
998 /// Unsafe because the caller must either take ownership or bind `T: Copy`
999 unsafe fn copy_from_slice(v
: &[T
]) -> Rc
<[T
]> {
1000 let ptr
= Self::allocate_for_slice(v
.len());
1002 ptr
::copy_nonoverlapping(
1004 &mut (*ptr
).value
as *mut [T
] as *mut T
,
1010 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1012 /// Behavior is undefined should the size be wrong.
1013 unsafe fn from_iter_exact(iter
: impl iter
::Iterator
<Item
= T
>, len
: usize) -> Rc
<[T
]> {
1014 // Panic guard while cloning T elements.
1015 // In the event of a panic, elements that have been written
1016 // into the new RcBox will be dropped, then the memory freed.
1024 impl<T
> Drop
for Guard
<T
> {
1025 fn drop(&mut self) {
1027 let slice
= from_raw_parts_mut(self.elems
, self.n_elems
);
1028 ptr
::drop_in_place(slice
);
1030 Global
.dealloc(self.mem
, self.layout
);
1035 let ptr
= Self::allocate_for_slice(len
);
1037 let mem
= ptr
as *mut _
as *mut u8;
1038 let layout
= Layout
::for_value(&*ptr
);
1040 // Pointer to first element
1041 let elems
= &mut (*ptr
).value
as *mut [T
] as *mut T
;
1043 let mut guard
= Guard
{
1044 mem
: NonNull
::new_unchecked(mem
),
1050 for (i
, item
) in iter
.enumerate() {
1051 ptr
::write(elems
.add(i
), item
);
1055 // All clear. Forget the guard so it doesn't free the new RcBox.
1062 /// Specialization trait used for `From<&[T]>`.
1063 trait RcFromSlice
<T
> {
1064 fn from_slice(slice
: &[T
]) -> Self;
1067 impl<T
: Clone
> RcFromSlice
<T
> for Rc
<[T
]> {
1069 default fn from_slice(v
: &[T
]) -> Self {
1071 Self::from_iter_exact(v
.iter().cloned(), v
.len())
1076 impl<T
: Copy
> RcFromSlice
<T
> for Rc
<[T
]> {
1078 fn from_slice(v
: &[T
]) -> Self {
1079 unsafe { Rc::copy_from_slice(v) }
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<T
: ?Sized
> Deref
for Rc
<T
> {
1088 fn deref(&self) -> &T
{
1093 #[unstable(feature = "receiver_trait", issue = "0")]
1094 impl<T
: ?Sized
> Receiver
for Rc
<T
> {}
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1100 /// This will decrement the strong reference count. If the strong reference
1101 /// count reaches zero then the only other references (if any) are
1102 /// [`Weak`], so we `drop` the inner value.
1107 /// use std::rc::Rc;
1111 /// impl Drop for Foo {
1112 /// fn drop(&mut self) {
1113 /// println!("dropped!");
1117 /// let foo = Rc::new(Foo);
1118 /// let foo2 = Rc::clone(&foo);
1120 /// drop(foo); // Doesn't print anything
1121 /// drop(foo2); // Prints "dropped!"
1124 /// [`Weak`]: ../../std/rc/struct.Weak.html
1125 fn drop(&mut self) {
1128 if self.strong() == 0 {
1129 // destroy the contained object
1130 ptr
::drop_in_place(self.ptr
.as_mut());
1132 // remove the implicit "strong weak" pointer now that we've
1133 // destroyed the contents.
1136 if self.weak() == 0 {
1137 Global
.dealloc(self.ptr
.cast(), Layout
::for_value(self.ptr
.as_ref()));
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 impl<T
: ?Sized
> Clone
for Rc
<T
> {
1146 /// Makes a clone of the `Rc` pointer.
1148 /// This creates another pointer to the same allocation, increasing the
1149 /// strong reference count.
1154 /// use std::rc::Rc;
1156 /// let five = Rc::new(5);
1158 /// let _ = Rc::clone(&five);
1161 fn clone(&self) -> Rc
<T
> {
1163 Self::from_inner(self.ptr
)
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<T
: Default
> Default
for Rc
<T
> {
1169 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1174 /// use std::rc::Rc;
1176 /// let x: Rc<i32> = Default::default();
1177 /// assert_eq!(*x, 0);
1180 fn default() -> Rc
<T
> {
1181 Rc
::new(Default
::default())
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 trait RcEqIdent
<T
: ?Sized
+ PartialEq
> {
1187 fn eq(&self, other
: &Rc
<T
>) -> bool
;
1188 fn ne(&self, other
: &Rc
<T
>) -> bool
;
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<T
: ?Sized
+ PartialEq
> RcEqIdent
<T
> for Rc
<T
> {
1194 default fn eq(&self, other
: &Rc
<T
>) -> bool
{
1199 default fn ne(&self, other
: &Rc
<T
>) -> bool
{
1204 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1205 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1206 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1207 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1208 /// the same value, than two `&T`s.
1210 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl<T
: ?Sized
+ Eq
> RcEqIdent
<T
> for Rc
<T
> {
1214 fn eq(&self, other
: &Rc
<T
>) -> bool
{
1215 Rc
::ptr_eq(self, other
) || **self == **other
1219 fn ne(&self, other
: &Rc
<T
>) -> bool
{
1220 !Rc
::ptr_eq(self, other
) && **self != **other
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Rc
<T
> {
1226 /// Equality for two `Rc`s.
1228 /// Two `Rc`s are equal if their inner values are equal, even if they are
1229 /// stored in different allocation.
1231 /// If `T` also implements `Eq` (implying reflexivity of equality),
1232 /// two `Rc`s that point to the same allocation are
1238 /// use std::rc::Rc;
1240 /// let five = Rc::new(5);
1242 /// assert!(five == Rc::new(5));
1245 fn eq(&self, other
: &Rc
<T
>) -> bool
{
1246 RcEqIdent
::eq(self, other
)
1249 /// Inequality for two `Rc`s.
1251 /// Two `Rc`s are unequal if their inner values are unequal.
1253 /// If `T` also implements `Eq` (implying reflexivity of equality),
1254 /// two `Rc`s that point to the same allocation are
1260 /// use std::rc::Rc;
1262 /// let five = Rc::new(5);
1264 /// assert!(five != Rc::new(6));
1267 fn ne(&self, other
: &Rc
<T
>) -> bool
{
1268 RcEqIdent
::ne(self, other
)
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<T
: ?Sized
+ Eq
> Eq
for Rc
<T
> {}
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Rc
<T
> {
1277 /// Partial comparison for two `Rc`s.
1279 /// The two are compared by calling `partial_cmp()` on their inner values.
1284 /// use std::rc::Rc;
1285 /// use std::cmp::Ordering;
1287 /// let five = Rc::new(5);
1289 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1292 fn partial_cmp(&self, other
: &Rc
<T
>) -> Option
<Ordering
> {
1293 (**self).partial_cmp(&**other
)
1296 /// Less-than comparison for two `Rc`s.
1298 /// The two are compared by calling `<` on their inner values.
1303 /// use std::rc::Rc;
1305 /// let five = Rc::new(5);
1307 /// assert!(five < Rc::new(6));
1310 fn lt(&self, other
: &Rc
<T
>) -> bool
{
1314 /// 'Less than or equal to' comparison for two `Rc`s.
1316 /// The two are compared by calling `<=` on their inner values.
1321 /// use std::rc::Rc;
1323 /// let five = Rc::new(5);
1325 /// assert!(five <= Rc::new(5));
1328 fn le(&self, other
: &Rc
<T
>) -> bool
{
1332 /// Greater-than comparison for two `Rc`s.
1334 /// The two are compared by calling `>` on their inner values.
1339 /// use std::rc::Rc;
1341 /// let five = Rc::new(5);
1343 /// assert!(five > Rc::new(4));
1346 fn gt(&self, other
: &Rc
<T
>) -> bool
{
1350 /// 'Greater than or equal to' comparison for two `Rc`s.
1352 /// The two are compared by calling `>=` on their inner values.
1357 /// use std::rc::Rc;
1359 /// let five = Rc::new(5);
1361 /// assert!(five >= Rc::new(5));
1364 fn ge(&self, other
: &Rc
<T
>) -> bool
{
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<T
: ?Sized
+ Ord
> Ord
for Rc
<T
> {
1371 /// Comparison for two `Rc`s.
1373 /// The two are compared by calling `cmp()` on their inner values.
1378 /// use std::rc::Rc;
1379 /// use std::cmp::Ordering;
1381 /// let five = Rc::new(5);
1383 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1386 fn cmp(&self, other
: &Rc
<T
>) -> Ordering
{
1387 (**self).cmp(&**other
)
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<T
: ?Sized
+ Hash
> Hash
for Rc
<T
> {
1393 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
1394 (**self).hash(state
);
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<T
: ?Sized
+ fmt
::Display
> fmt
::Display
for Rc
<T
> {
1400 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1401 fmt
::Display
::fmt(&**self, f
)
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Rc
<T
> {
1407 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1408 fmt
::Debug
::fmt(&**self, f
)
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl<T
: ?Sized
> fmt
::Pointer
for Rc
<T
> {
1414 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1415 fmt
::Pointer
::fmt(&(&**self as *const T
), f
)
1419 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1420 impl<T
> From
<T
> for Rc
<T
> {
1421 fn from(t
: T
) -> Self {
1426 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1427 impl<T
: Clone
> From
<&[T
]> for Rc
<[T
]> {
1429 fn from(v
: &[T
]) -> Rc
<[T
]> {
1430 <Self as RcFromSlice
<T
>>::from_slice(v
)
1434 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1435 impl From
<&str> for Rc
<str> {
1437 fn from(v
: &str) -> Rc
<str> {
1438 let rc
= Rc
::<[u8]>::from(v
.as_bytes());
1439 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1443 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1444 impl From
<String
> for Rc
<str> {
1446 fn from(v
: String
) -> Rc
<str> {
1451 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1452 impl<T
: ?Sized
> From
<Box
<T
>> for Rc
<T
> {
1454 fn from(v
: Box
<T
>) -> Rc
<T
> {
1459 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1460 impl<T
> From
<Vec
<T
>> for Rc
<[T
]> {
1462 fn from(mut v
: Vec
<T
>) -> Rc
<[T
]> {
1464 let rc
= Rc
::copy_from_slice(&v
);
1466 // Allow the Vec to free its memory, but not destroy its contents
1474 #[unstable(feature = "boxed_slice_try_from", issue = "0")]
1475 impl<T
, const N
: usize> TryFrom
<Rc
<[T
]>> for Rc
<[T
; N
]>
1477 [T
; N
]: LengthAtMost32
,
1479 type Error
= Rc
<[T
]>;
1481 fn try_from(boxed_slice
: Rc
<[T
]>) -> Result
<Self, Self::Error
> {
1482 if boxed_slice
.len() == N
{
1483 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) }
)
1490 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1491 impl<T
> iter
::FromIterator
<T
> for Rc
<[T
]> {
1492 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1494 /// # Performance characteristics
1496 /// ## The general case
1498 /// In the general case, collecting into `Rc<[T]>` is done by first
1499 /// collecting into a `Vec<T>`. That is, when writing the following:
1502 /// # use std::rc::Rc;
1503 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1504 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1507 /// this behaves as if we wrote:
1510 /// # use std::rc::Rc;
1511 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1512 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1513 /// .into(); // A second allocation for `Rc<[T]>` happens here.
1514 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1517 /// This will allocate as many times as needed for constructing the `Vec<T>`
1518 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1520 /// ## Iterators of known length
1522 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1523 /// a single allocation will be made for the `Rc<[T]>`. For example:
1526 /// # use std::rc::Rc;
1527 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1528 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1530 fn from_iter
<I
: iter
::IntoIterator
<Item
= T
>>(iter
: I
) -> Self {
1531 RcFromIter
::from_iter(iter
.into_iter())
1535 /// Specialization trait used for collecting into `Rc<[T]>`.
1536 trait RcFromIter
<T
, I
> {
1537 fn from_iter(iter
: I
) -> Self;
1540 impl<T
, I
: Iterator
<Item
= T
>> RcFromIter
<T
, I
> for Rc
<[T
]> {
1541 default fn from_iter(iter
: I
) -> Self {
1542 iter
.collect
::<Vec
<T
>>().into()
1546 impl<T
, I
: iter
::TrustedLen
<Item
= T
>> RcFromIter
<T
, I
> for Rc
<[T
]> {
1547 default fn from_iter(iter
: I
) -> Self {
1548 // This is the case for a `TrustedLen` iterator.
1549 let (low
, high
) = iter
.size_hint();
1550 if let Some(high
) = high
{
1553 "TrustedLen iterator's size hint is not exact: {:?}",
1558 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1559 Rc
::from_iter_exact(iter
, low
)
1562 // Fall back to normal implementation.
1563 iter
.collect
::<Vec
<T
>>().into()
1568 impl<'a
, T
: 'a
+ Clone
> RcFromIter
<&'a T
, slice
::Iter
<'a
, T
>> for Rc
<[T
]> {
1569 fn from_iter(iter
: slice
::Iter
<'a
, T
>) -> Self {
1570 // Delegate to `impl<T: Clone> From<&[T]> for Rc<[T]>`.
1572 // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1573 // which is even more performant.
1575 // In the fall-back case we have `T: Clone`. This is still better
1576 // than the `TrustedLen` implementation as slices have a known length
1577 // and so we get to avoid calling `size_hint` and avoid the branching.
1578 iter
.as_slice().into()
1582 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1583 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
1584 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1586 /// Since a `Weak` reference does not count towards ownership, it will not
1587 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
1588 /// guarantees about the value still being present. Thus it may return [`None`]
1589 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
1590 /// itself (the backing store) from being deallocated.
1592 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
1593 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
1594 /// prevent circular references between [`Rc`] pointers, since mutual owning references
1595 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1596 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1597 /// pointers from children back to their parents.
1599 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1601 /// [`Rc`]: struct.Rc.html
1602 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1603 /// [`upgrade`]: struct.Weak.html#method.upgrade
1604 /// [`Option`]: ../../std/option/enum.Option.html
1605 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1606 #[stable(feature = "rc_weak", since = "1.4.0")]
1607 pub struct Weak
<T
: ?Sized
> {
1608 // This is a `NonNull` to allow optimizing the size of this type in enums,
1609 // but it is not necessarily a valid pointer.
1610 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1611 // to allocate space on the heap. That's not a value a real pointer
1612 // will ever have because RcBox has alignment at least 2.
1613 ptr
: NonNull
<RcBox
<T
>>,
1616 #[stable(feature = "rc_weak", since = "1.4.0")]
1617 impl<T
: ?Sized
> !marker
::Send
for Weak
<T
> {}
1618 #[stable(feature = "rc_weak", since = "1.4.0")]
1619 impl<T
: ?Sized
> !marker
::Sync
for Weak
<T
> {}
1621 #[unstable(feature = "coerce_unsized", issue = "27732")]
1622 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Weak
<U
>> for Weak
<T
> {}
1624 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1625 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> DispatchFromDyn
<Weak
<U
>> for Weak
<T
> {}
1628 /// Constructs a new `Weak<T>`, without allocating any memory.
1629 /// Calling [`upgrade`] on the return value always gives [`None`].
1631 /// [`upgrade`]: #method.upgrade
1632 /// [`None`]: ../../std/option/enum.Option.html
1637 /// use std::rc::Weak;
1639 /// let empty: Weak<i64> = Weak::new();
1640 /// assert!(empty.upgrade().is_none());
1642 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1643 pub fn new() -> Weak
<T
> {
1645 ptr
: NonNull
::new(usize::MAX
as *mut RcBox
<T
>).expect("MAX is not 0"),
1649 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1651 /// The pointer is valid only if there are some strong references. The pointer may be dangling
1652 /// or even [`null`] otherwise.
1657 /// #![feature(weak_into_raw)]
1659 /// use std::rc::Rc;
1662 /// let strong = Rc::new("hello".to_owned());
1663 /// let weak = Rc::downgrade(&strong);
1664 /// // Both point to the same object
1665 /// assert!(ptr::eq(&*strong, weak.as_raw()));
1666 /// // The strong here keeps it alive, so we can still access the object.
1667 /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1670 /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1671 /// // undefined behaviour.
1672 /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1675 /// [`null`]: ../../std/ptr/fn.null.html
1676 #[unstable(feature = "weak_into_raw", issue = "60728")]
1677 pub fn as_raw(&self) -> *const T
{
1678 match self.inner() {
1679 None
=> ptr
::null(),
1681 let offset
= data_offset_sized
::<T
>();
1682 let ptr
= inner
as *const RcBox
<T
>;
1683 // Note: while the pointer we create may already point to dropped value, the
1684 // allocation still lives (it must hold the weak point as long as we are alive).
1685 // Therefore, the offset is OK to do, it won't get out of the allocation.
1686 let ptr
= unsafe { (ptr as *const u8).offset(offset) }
;
1692 /// Consumes the `Weak<T>` and turns it into a raw pointer.
1694 /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1695 /// can be turned back into the `Weak<T>` with [`from_raw`].
1697 /// The same restrictions of accessing the target of the pointer as with
1698 /// [`as_raw`] apply.
1703 /// #![feature(weak_into_raw)]
1705 /// use std::rc::{Rc, Weak};
1707 /// let strong = Rc::new("hello".to_owned());
1708 /// let weak = Rc::downgrade(&strong);
1709 /// let raw = weak.into_raw();
1711 /// assert_eq!(1, Rc::weak_count(&strong));
1712 /// assert_eq!("hello", unsafe { &*raw });
1714 /// drop(unsafe { Weak::from_raw(raw) });
1715 /// assert_eq!(0, Rc::weak_count(&strong));
1718 /// [`from_raw`]: struct.Weak.html#method.from_raw
1719 /// [`as_raw`]: struct.Weak.html#method.as_raw
1720 #[unstable(feature = "weak_into_raw", issue = "60728")]
1721 pub fn into_raw(self) -> *const T
{
1722 let result
= self.as_raw();
1727 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1729 /// This can be used to safely get a strong reference (by calling [`upgrade`]
1730 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1732 /// It takes ownership of one weak count (with the exception of pointers created by [`new`],
1733 /// as these don't have any corresponding weak count).
1737 /// The pointer must have originated from the [`into_raw`] (or [`as_raw`], provided there was
1738 /// a corresponding [`forget`] on the `Weak<T>`) and must still own its potential weak reference
1741 /// It is allowed for the strong count to be 0 at the time of calling this, but the weak count
1742 /// must be non-zero or the pointer must have originated from a dangling `Weak<T>` (one created
1748 /// #![feature(weak_into_raw)]
1750 /// use std::rc::{Rc, Weak};
1752 /// let strong = Rc::new("hello".to_owned());
1754 /// let raw_1 = Rc::downgrade(&strong).into_raw();
1755 /// let raw_2 = Rc::downgrade(&strong).into_raw();
1757 /// assert_eq!(2, Rc::weak_count(&strong));
1759 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1760 /// assert_eq!(1, Rc::weak_count(&strong));
1764 /// // Decrement the last weak count.
1765 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1768 /// [`into_raw`]: struct.Weak.html#method.into_raw
1769 /// [`upgrade`]: struct.Weak.html#method.upgrade
1770 /// [`Rc`]: struct.Rc.html
1771 /// [`Weak`]: struct.Weak.html
1772 /// [`as_raw`]: struct.Weak.html#method.as_raw
1773 /// [`new`]: struct.Weak.html#method.new
1774 /// [`forget`]: ../../std/mem/fn.forget.html
1775 #[unstable(feature = "weak_into_raw", issue = "60728")]
1776 pub unsafe fn from_raw(ptr
: *const T
) -> Self {
1780 // See Rc::from_raw for details
1781 let offset
= data_offset(ptr
);
1782 let fake_ptr
= ptr
as *mut RcBox
<T
>;
1783 let ptr
= set_data_ptr(fake_ptr
, (ptr
as *mut u8).offset(-offset
));
1785 ptr
: NonNull
::new(ptr
).expect("Invalid pointer passed to from_raw"),
1791 pub(crate) fn is_dangling
<T
: ?Sized
>(ptr
: NonNull
<T
>) -> bool
{
1792 let address
= ptr
.as_ptr() as *mut () as usize;
1793 address
== usize::MAX
1796 impl<T
: ?Sized
> Weak
<T
> {
1797 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
1798 /// dropping of the inner value if successful.
1800 /// Returns [`None`] if the inner value has since been dropped.
1802 /// [`Rc`]: struct.Rc.html
1803 /// [`None`]: ../../std/option/enum.Option.html
1808 /// use std::rc::Rc;
1810 /// let five = Rc::new(5);
1812 /// let weak_five = Rc::downgrade(&five);
1814 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1815 /// assert!(strong_five.is_some());
1817 /// // Destroy all strong pointers.
1818 /// drop(strong_five);
1821 /// assert!(weak_five.upgrade().is_none());
1823 #[stable(feature = "rc_weak", since = "1.4.0")]
1824 pub fn upgrade(&self) -> Option
<Rc
<T
>> {
1825 let inner
= self.inner()?
;
1826 if inner
.strong() == 0 {
1830 Some(Rc
::from_inner(self.ptr
))
1834 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
1836 /// If `self` was created using [`Weak::new`], this will return 0.
1838 /// [`Weak::new`]: #method.new
1839 #[stable(feature = "weak_counts", since = "1.41.0")]
1840 pub fn strong_count(&self) -> usize {
1841 if let Some(inner
) = self.inner() {
1848 /// Gets the number of `Weak` pointers pointing to this allocation.
1850 /// If no strong pointers remain, this will return zero.
1851 #[stable(feature = "weak_counts", since = "1.41.0")]
1852 pub fn weak_count(&self) -> usize {
1853 self.inner().map(|inner
| {
1854 if inner
.strong() > 0 {
1855 inner
.weak() - 1 // subtract the implicit weak ptr
1862 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1863 /// (i.e., when this `Weak` was created by `Weak::new`).
1865 fn inner(&self) -> Option
<&RcBox
<T
>> {
1866 if is_dangling(self.ptr
) {
1869 Some(unsafe { self.ptr.as_ref() }
)
1873 /// Returns `true` if the two `Weak`s point to the same allocation (similar to
1874 /// [`ptr::eq`]), or if both don't point to any allocation
1875 /// (because they were created with `Weak::new()`).
1879 /// Since this compares pointers it means that `Weak::new()` will equal each
1880 /// other, even though they don't point to any allocation.
1885 /// use std::rc::Rc;
1887 /// let first_rc = Rc::new(5);
1888 /// let first = Rc::downgrade(&first_rc);
1889 /// let second = Rc::downgrade(&first_rc);
1891 /// assert!(first.ptr_eq(&second));
1893 /// let third_rc = Rc::new(5);
1894 /// let third = Rc::downgrade(&third_rc);
1896 /// assert!(!first.ptr_eq(&third));
1899 /// Comparing `Weak::new`.
1902 /// use std::rc::{Rc, Weak};
1904 /// let first = Weak::new();
1905 /// let second = Weak::new();
1906 /// assert!(first.ptr_eq(&second));
1908 /// let third_rc = Rc::new(());
1909 /// let third = Rc::downgrade(&third_rc);
1910 /// assert!(!first.ptr_eq(&third));
1913 /// [`ptr::eq`]: ../../std/ptr/fn.eq.html
1915 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1916 pub fn ptr_eq(&self, other
: &Self) -> bool
{
1917 self.ptr
.as_ptr() == other
.ptr
.as_ptr()
1921 #[stable(feature = "rc_weak", since = "1.4.0")]
1922 impl<T
: ?Sized
> Drop
for Weak
<T
> {
1923 /// Drops the `Weak` pointer.
1928 /// use std::rc::{Rc, Weak};
1932 /// impl Drop for Foo {
1933 /// fn drop(&mut self) {
1934 /// println!("dropped!");
1938 /// let foo = Rc::new(Foo);
1939 /// let weak_foo = Rc::downgrade(&foo);
1940 /// let other_weak_foo = Weak::clone(&weak_foo);
1942 /// drop(weak_foo); // Doesn't print anything
1943 /// drop(foo); // Prints "dropped!"
1945 /// assert!(other_weak_foo.upgrade().is_none());
1947 fn drop(&mut self) {
1948 if let Some(inner
) = self.inner() {
1950 // the weak count starts at 1, and will only go to zero if all
1951 // the strong pointers have disappeared.
1952 if inner
.weak() == 0 {
1954 Global
.dealloc(self.ptr
.cast(), Layout
::for_value(self.ptr
.as_ref()));
1961 #[stable(feature = "rc_weak", since = "1.4.0")]
1962 impl<T
: ?Sized
> Clone
for Weak
<T
> {
1963 /// Makes a clone of the `Weak` pointer that points to the same allocation.
1968 /// use std::rc::{Rc, Weak};
1970 /// let weak_five = Rc::downgrade(&Rc::new(5));
1972 /// let _ = Weak::clone(&weak_five);
1975 fn clone(&self) -> Weak
<T
> {
1976 if let Some(inner
) = self.inner() {
1979 Weak { ptr: self.ptr }
1983 #[stable(feature = "rc_weak", since = "1.4.0")]
1984 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Weak
<T
> {
1985 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1990 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1991 impl<T
> Default
for Weak
<T
> {
1992 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1993 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1995 /// [`None`]: ../../std/option/enum.Option.html
1996 /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
2001 /// use std::rc::Weak;
2003 /// let empty: Weak<i64> = Default::default();
2004 /// assert!(empty.upgrade().is_none());
2006 fn default() -> Weak
<T
> {
2011 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2012 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2013 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2014 // We abort because this is such a degenerate scenario that we don't care about
2015 // what happens -- no real program should ever experience this.
2017 // This should have negligible overhead since you don't actually need to
2018 // clone these much in Rust thanks to ownership and move-semantics.
2021 trait RcBoxPtr
<T
: ?Sized
> {
2022 fn inner(&self) -> &RcBox
<T
>;
2025 fn strong(&self) -> usize {
2026 self.inner().strong
.get()
2030 fn inc_strong(&self) {
2031 let strong
= self.strong();
2033 // We want to abort on overflow instead of dropping the value.
2034 // The reference count will never be zero when this is called;
2035 // nevertheless, we insert an abort here to hint LLVM at
2036 // an otherwise missed optimization.
2037 if strong
== 0 || strong
== usize::max_value() {
2040 self.inner().strong
.set(strong
+ 1);
2044 fn dec_strong(&self) {
2045 self.inner().strong
.set(self.strong() - 1);
2049 fn weak(&self) -> usize {
2050 self.inner().weak
.get()
2054 fn inc_weak(&self) {
2055 let weak
= self.weak();
2057 // We want to abort on overflow instead of dropping the value.
2058 // The reference count will never be zero when this is called;
2059 // nevertheless, we insert an abort here to hint LLVM at
2060 // an otherwise missed optimization.
2061 if weak
== 0 || weak
== usize::max_value() {
2064 self.inner().weak
.set(weak
+ 1);
2068 fn dec_weak(&self) {
2069 self.inner().weak
.set(self.weak() - 1);
2073 impl<T
: ?Sized
> RcBoxPtr
<T
> for Rc
<T
> {
2075 fn inner(&self) -> &RcBox
<T
> {
2082 impl<T
: ?Sized
> RcBoxPtr
<T
> for RcBox
<T
> {
2084 fn inner(&self) -> &RcBox
<T
> {
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 impl<T
: ?Sized
> borrow
::Borrow
<T
> for Rc
<T
> {
2091 fn borrow(&self) -> &T
{
2096 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2097 impl<T
: ?Sized
> AsRef
<T
> for Rc
<T
> {
2098 fn as_ref(&self) -> &T
{
2103 #[stable(feature = "pin", since = "1.33.0")]
2104 impl<T
: ?Sized
> Unpin
for Rc
<T
> { }
2106 unsafe fn data_offset
<T
: ?Sized
>(ptr
: *const T
) -> isize {
2107 // Align the unsized value to the end of the `RcBox`.
2108 // Because it is ?Sized, it will always be the last field in memory.
2109 data_offset_align(align_of_val(&*ptr
))
2112 /// Computes the offset of the data field within `RcBox`.
2114 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
2115 fn data_offset_sized
<T
>() -> isize {
2116 data_offset_align(align_of
::<T
>())
2120 fn data_offset_align(align
: usize) -> isize {
2121 let layout
= Layout
::new
::<RcBox
<()>>();
2122 (layout
.size() + layout
.padding_needed_for(align
)) as isize