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 [fully qualified syntax]:
43 //! let my_rc = Rc::new(());
44 //! Rc::downgrade(&my_rc);
47 //! `Rc<T>`'s implementations of traits like `Clone` may also be called using
48 //! fully qualified syntax. Some people prefer to use fully qualified syntax,
49 //! while others prefer using method-call syntax.
54 //! let rc = Rc::new(());
55 //! // Method-call syntax
56 //! let rc2 = rc.clone();
57 //! // Fully qualified syntax
58 //! let rc3 = Rc::clone(&rc);
61 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
62 //! already been dropped.
64 //! # Cloning references
66 //! Creating a new reference to the same allocation as an existing reference counted pointer
67 //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
72 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
73 //! // The two syntaxes below are equivalent.
74 //! let a = foo.clone();
75 //! let b = Rc::clone(&foo);
76 //! // a and b both point to the same memory location as foo.
79 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
80 //! the meaning of the code. In the example above, this syntax makes it easier to see that
81 //! this code is creating a new reference rather than copying the whole content of foo.
85 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
86 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
87 //! unique ownership, because more than one gadget may belong to the same
88 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
89 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
96 //! // ...other fields
101 //! owner: Rc<Owner>,
102 //! // ...other fields
106 //! // Create a reference-counted `Owner`.
107 //! let gadget_owner: Rc<Owner> = Rc::new(
109 //! name: "Gadget Man".to_string(),
113 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
114 //! // gives us a new pointer to the same `Owner` allocation, incrementing
115 //! // the reference count in the process.
116 //! let gadget1 = Gadget {
118 //! owner: Rc::clone(&gadget_owner),
120 //! let gadget2 = Gadget {
122 //! owner: Rc::clone(&gadget_owner),
125 //! // Dispose of our local variable `gadget_owner`.
126 //! drop(gadget_owner);
128 //! // Despite dropping `gadget_owner`, we're still able to print out the name
129 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
130 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
131 //! // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain
132 //! // live. The field projection `gadget1.owner.name` works because
133 //! // `Rc<Owner>` automatically dereferences to `Owner`.
134 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
135 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
137 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
138 //! // with them the last counted references to our `Owner`. Gadget Man now
139 //! // gets destroyed as well.
143 //! If our requirements change, and we also need to be able to traverse from
144 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
145 //! to `Gadget` introduces a cycle. This means that their
146 //! reference counts can never reach 0, and the allocation will never be destroyed:
147 //! a memory leak. In order to get around this, we can use [`Weak`]
150 //! Rust actually makes it somewhat difficult to produce this loop in the first
151 //! place. In order to end up with two values that point at each other, one of
152 //! them needs to be mutable. This is difficult because [`Rc`] enforces
153 //! memory safety by only giving out shared references to the value it wraps,
154 //! and these don't allow direct mutation. We need to wrap the part of the
155 //! value we wish to mutate in a [`RefCell`], which provides *interior
156 //! mutability*: a method to achieve mutability through a shared reference.
157 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
161 //! use std::rc::Weak;
162 //! use std::cell::RefCell;
166 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
167 //! // ...other fields
172 //! owner: Rc<Owner>,
173 //! // ...other fields
177 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
178 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
179 //! // a shared reference.
180 //! let gadget_owner: Rc<Owner> = Rc::new(
182 //! name: "Gadget Man".to_string(),
183 //! gadgets: RefCell::new(vec![]),
187 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
188 //! let gadget1 = Rc::new(
191 //! owner: Rc::clone(&gadget_owner),
194 //! let gadget2 = Rc::new(
197 //! owner: Rc::clone(&gadget_owner),
201 //! // Add the `Gadget`s to their `Owner`.
203 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
204 //! gadgets.push(Rc::downgrade(&gadget1));
205 //! gadgets.push(Rc::downgrade(&gadget2));
207 //! // `RefCell` dynamic borrow ends here.
210 //! // Iterate over our `Gadget`s, printing their details out.
211 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
213 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
214 //! // guarantee the allocation still exists, we need to call
215 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
217 //! // In this case we know the allocation still exists, so we simply
218 //! // `unwrap` the `Option`. In a more complicated program, you might
219 //! // need graceful error handling for a `None` result.
221 //! let gadget = gadget_weak.upgrade().unwrap();
222 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
225 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
226 //! // are destroyed. There are now no strong (`Rc`) pointers to the
227 //! // gadgets, so they are destroyed. This zeroes the reference count on
228 //! // Gadget Man, so he gets destroyed as well.
232 //! [clone]: Clone::clone
233 //! [`Cell`]: core::cell::Cell
234 //! [`RefCell`]: core::cell::RefCell
235 //! [send]: core::marker::Send
236 //! [arc]: crate::sync::Arc
237 //! [`Deref`]: core::ops::Deref
238 //! [downgrade]: Rc::downgrade
239 //! [upgrade]: Weak::upgrade
240 //! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
241 //! [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name
243 #![stable(feature = "rust1", since = "1.0.0")]
246 use crate::boxed::Box;
252 use core::cell::Cell;
253 use core::cmp::Ordering;
254 use core::convert::{From, TryFrom};
256 use core::hash::{Hash, Hasher};
257 use core::intrinsics::abort;
258 #[cfg(not(no_global_oom_handling))]
260 use core::marker::{self, PhantomData, Unpin, Unsize};
261 #[cfg(not(no_global_oom_handling))]
262 use core::mem::size_of_val;
263 use core::mem::{self, align_of_val_raw, forget};
264 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
265 use core::panic::{RefUnwindSafe, UnwindSafe};
266 #[cfg(not(no_global_oom_handling))]
268 use core::ptr::{self, NonNull};
269 #[cfg(not(no_global_oom_handling))]
270 use core::slice::from_raw_parts_mut;
272 #[cfg(not(no_global_oom_handling))]
273 use crate::alloc::handle_alloc_error;
274 #[cfg(not(no_global_oom_handling))]
275 use crate::alloc::{box_free, WriteCloneIntoRaw};
276 use crate::alloc::{AllocError, Allocator, Global, Layout};
277 use crate::borrow::{Cow, ToOwned};
278 #[cfg(not(no_global_oom_handling))]
279 use crate::string::String;
280 #[cfg(not(no_global_oom_handling))]
286 // This is repr(C) to future-proof against possible field-reordering, which
287 // would interfere with otherwise safe [into|from]_raw() of transmutable
290 struct RcBox<T: ?Sized> {
296 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
299 /// See the [module-level documentation](./index.html) for more details.
301 /// The inherent methods of `Rc` are all associated functions, which means
302 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
303 /// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
305 /// [get_mut]: Rc::get_mut
306 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub struct Rc<T: ?Sized> {
309 ptr: NonNull<RcBox<T>>,
310 phantom: PhantomData<RcBox<T>>,
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<T: ?Sized> !marker::Send for Rc<T> {}
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<T: ?Sized> !marker::Sync for Rc<T> {}
318 #[stable(feature = "catch_unwind", since = "1.9.0")]
319 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
321 #[unstable(feature = "coerce_unsized", issue = "27732")]
322 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
324 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
325 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
327 impl<T: ?Sized> Rc<T> {
329 fn inner(&self) -> &RcBox<T> {
330 // This unsafety is ok because while this Rc is alive we're guaranteed
331 // that the inner pointer is valid.
332 unsafe { self.ptr.as_ref() }
335 fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
336 Self { ptr, phantom: PhantomData }
339 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
340 Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
345 /// Constructs a new `Rc<T>`.
352 /// let five = Rc::new(5);
354 #[cfg(not(no_global_oom_handling))]
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn new(value: T) -> Rc<T> {
357 // There is an implicit weak pointer owned by all the strong
358 // pointers, which ensures that the weak destructor never frees
359 // the allocation while the strong destructor is running, even
360 // if the weak pointer is stored inside the strong one.
362 Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(),
366 /// Constructs a new `Rc<T>` using a weak reference to itself. Attempting
367 /// to upgrade the weak reference before this function returns will result
368 /// in a `None` value. However, the weak reference may be cloned freely and
369 /// stored for use at a later time.
374 /// #![feature(arc_new_cyclic)]
375 /// #![allow(dead_code)]
376 /// use std::rc::{Rc, Weak};
379 /// self_weak: Weak<Self>,
380 /// // ... more fields
383 /// pub fn new() -> Rc<Self> {
384 /// Rc::new_cyclic(|self_weak| {
385 /// Gadget { self_weak: self_weak.clone(), /* ... */ }
390 #[cfg(not(no_global_oom_handling))]
391 #[unstable(feature = "arc_new_cyclic", issue = "75861")]
392 pub fn new_cyclic(data_fn: impl FnOnce(&Weak<T>) -> T) -> Rc<T> {
393 // Construct the inner in the "uninitialized" state with a single
395 let uninit_ptr: NonNull<_> = Box::leak(box RcBox {
396 strong: Cell::new(0),
398 value: mem::MaybeUninit::<T>::uninit(),
402 let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast();
404 let weak = Weak { ptr: init_ptr };
406 // It's important we don't give up ownership of the weak pointer, or
407 // else the memory might be freed by the time `data_fn` returns. If
408 // we really wanted to pass ownership, we could create an additional
409 // weak pointer for ourselves, but this would result in additional
410 // updates to the weak reference count which might not be necessary
412 let data = data_fn(&weak);
415 let inner = init_ptr.as_ptr();
416 ptr::write(ptr::addr_of_mut!((*inner).value), data);
418 let prev_value = (*inner).strong.get();
419 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
420 (*inner).strong.set(1);
423 let strong = Rc::from_inner(init_ptr);
425 // Strong references should collectively own a shared weak reference,
426 // so don't run the destructor for our old weak reference.
431 /// Constructs a new `Rc` with uninitialized contents.
436 /// #![feature(new_uninit)]
437 /// #![feature(get_mut_unchecked)]
441 /// let mut five = Rc::<u32>::new_uninit();
443 /// let five = unsafe {
444 /// // Deferred initialization:
445 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
447 /// five.assume_init()
450 /// assert_eq!(*five, 5)
452 #[cfg(not(no_global_oom_handling))]
453 #[unstable(feature = "new_uninit", issue = "63291")]
454 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
456 Rc::from_ptr(Rc::allocate_for_layout(
458 |layout| Global.allocate(layout),
459 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
464 /// Constructs a new `Rc` with uninitialized contents, with the memory
465 /// being filled with `0` bytes.
467 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
468 /// incorrect usage of this method.
473 /// #![feature(new_uninit)]
477 /// let zero = Rc::<u32>::new_zeroed();
478 /// let zero = unsafe { zero.assume_init() };
480 /// assert_eq!(*zero, 0)
483 /// [zeroed]: mem::MaybeUninit::zeroed
484 #[cfg(not(no_global_oom_handling))]
485 #[unstable(feature = "new_uninit", issue = "63291")]
486 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
488 Rc::from_ptr(Rc::allocate_for_layout(
490 |layout| Global.allocate_zeroed(layout),
491 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
496 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
501 /// #![feature(allocator_api)]
504 /// let five = Rc::try_new(5);
505 /// # Ok::<(), std::alloc::AllocError>(())
507 #[unstable(feature = "allocator_api", issue = "32838")]
508 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
509 // There is an implicit weak pointer owned by all the strong
510 // pointers, which ensures that the weak destructor never frees
511 // the allocation while the strong destructor is running, even
512 // if the weak pointer is stored inside the strong one.
514 Box::leak(Box::try_new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value })?)
519 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
524 /// #![feature(allocator_api, new_uninit)]
525 /// #![feature(get_mut_unchecked)]
529 /// let mut five = Rc::<u32>::try_new_uninit()?;
531 /// let five = unsafe {
532 /// // Deferred initialization:
533 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
535 /// five.assume_init()
538 /// assert_eq!(*five, 5);
539 /// # Ok::<(), std::alloc::AllocError>(())
541 #[unstable(feature = "allocator_api", issue = "32838")]
542 // #[unstable(feature = "new_uninit", issue = "63291")]
543 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
545 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
547 |layout| Global.allocate(layout),
548 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
553 /// Constructs a new `Rc` with uninitialized contents, with the memory
554 /// being filled with `0` bytes, returning an error if the allocation fails
556 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
557 /// incorrect usage of this method.
562 /// #![feature(allocator_api, new_uninit)]
566 /// let zero = Rc::<u32>::try_new_zeroed()?;
567 /// let zero = unsafe { zero.assume_init() };
569 /// assert_eq!(*zero, 0);
570 /// # Ok::<(), std::alloc::AllocError>(())
573 /// [zeroed]: mem::MaybeUninit::zeroed
574 #[unstable(feature = "allocator_api", issue = "32838")]
575 //#[unstable(feature = "new_uninit", issue = "63291")]
576 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
578 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
580 |layout| Global.allocate_zeroed(layout),
581 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
585 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
586 /// `value` will be pinned in memory and unable to be moved.
587 #[cfg(not(no_global_oom_handling))]
588 #[stable(feature = "pin", since = "1.33.0")]
589 pub fn pin(value: T) -> Pin<Rc<T>> {
590 unsafe { Pin::new_unchecked(Rc::new(value)) }
593 /// Returns the inner value, if the `Rc` has exactly one strong reference.
595 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
598 /// This will succeed even if there are outstanding weak references.
605 /// let x = Rc::new(3);
606 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
608 /// let x = Rc::new(4);
609 /// let _y = Rc::clone(&x);
610 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
613 #[stable(feature = "rc_unique", since = "1.4.0")]
614 pub fn try_unwrap(this: Self) -> Result<T, Self> {
615 if Rc::strong_count(&this) == 1 {
617 let val = ptr::read(&*this); // copy the contained object
619 // Indicate to Weaks that they can't be promoted by decrementing
620 // the strong count, and then remove the implicit "strong weak"
621 // pointer while also handling drop logic by just crafting a
623 this.inner().dec_strong();
624 let _weak = Weak { ptr: this.ptr };
635 /// Constructs a new reference-counted slice with uninitialized contents.
640 /// #![feature(new_uninit)]
641 /// #![feature(get_mut_unchecked)]
645 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
647 /// let values = unsafe {
648 /// // Deferred initialization:
649 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
650 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
651 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
653 /// values.assume_init()
656 /// assert_eq!(*values, [1, 2, 3])
658 #[cfg(not(no_global_oom_handling))]
659 #[unstable(feature = "new_uninit", issue = "63291")]
660 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
661 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
664 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
665 /// filled with `0` bytes.
667 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
668 /// incorrect usage of this method.
673 /// #![feature(new_uninit)]
677 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
678 /// let values = unsafe { values.assume_init() };
680 /// assert_eq!(*values, [0, 0, 0])
683 /// [zeroed]: mem::MaybeUninit::zeroed
684 #[cfg(not(no_global_oom_handling))]
685 #[unstable(feature = "new_uninit", issue = "63291")]
686 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
688 Rc::from_ptr(Rc::allocate_for_layout(
689 Layout::array::<T>(len).unwrap(),
690 |layout| Global.allocate_zeroed(layout),
692 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
693 as *mut RcBox<[mem::MaybeUninit<T>]>
700 impl<T> Rc<mem::MaybeUninit<T>> {
701 /// Converts to `Rc<T>`.
705 /// As with [`MaybeUninit::assume_init`],
706 /// it is up to the caller to guarantee that the inner value
707 /// really is in an initialized state.
708 /// Calling this when the content is not yet fully initialized
709 /// causes immediate undefined behavior.
711 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
716 /// #![feature(new_uninit)]
717 /// #![feature(get_mut_unchecked)]
721 /// let mut five = Rc::<u32>::new_uninit();
723 /// let five = unsafe {
724 /// // Deferred initialization:
725 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
727 /// five.assume_init()
730 /// assert_eq!(*five, 5)
732 #[unstable(feature = "new_uninit", issue = "63291")]
734 pub unsafe fn assume_init(self) -> Rc<T> {
735 Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
739 impl<T> Rc<[mem::MaybeUninit<T>]> {
740 /// Converts to `Rc<[T]>`.
744 /// As with [`MaybeUninit::assume_init`],
745 /// it is up to the caller to guarantee that the inner value
746 /// really is in an initialized state.
747 /// Calling this when the content is not yet fully initialized
748 /// causes immediate undefined behavior.
750 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
755 /// #![feature(new_uninit)]
756 /// #![feature(get_mut_unchecked)]
760 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
762 /// let values = unsafe {
763 /// // Deferred initialization:
764 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
765 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
766 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
768 /// values.assume_init()
771 /// assert_eq!(*values, [1, 2, 3])
773 #[unstable(feature = "new_uninit", issue = "63291")]
775 pub unsafe fn assume_init(self) -> Rc<[T]> {
776 unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
780 impl<T: ?Sized> Rc<T> {
781 /// Consumes the `Rc`, returning the wrapped pointer.
783 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
784 /// [`Rc::from_raw`][from_raw].
786 /// [from_raw]: Rc::from_raw
793 /// let x = Rc::new("hello".to_owned());
794 /// let x_ptr = Rc::into_raw(x);
795 /// assert_eq!(unsafe { &*x_ptr }, "hello");
797 #[stable(feature = "rc_raw", since = "1.17.0")]
798 pub fn into_raw(this: Self) -> *const T {
799 let ptr = Self::as_ptr(&this);
804 /// Provides a raw pointer to the data.
806 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
807 /// for as long there are strong counts in the `Rc`.
814 /// let x = Rc::new("hello".to_owned());
815 /// let y = Rc::clone(&x);
816 /// let x_ptr = Rc::as_ptr(&x);
817 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
818 /// assert_eq!(unsafe { &*x_ptr }, "hello");
820 #[stable(feature = "weak_into_raw", since = "1.45.0")]
821 pub fn as_ptr(this: &Self) -> *const T {
822 let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
824 // SAFETY: This cannot go through Deref::deref or Rc::inner because
825 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
826 // write through the pointer after the Rc is recovered through `from_raw`.
827 unsafe { ptr::addr_of_mut!((*ptr).value) }
830 /// Constructs an `Rc<T>` from a raw pointer.
832 /// The raw pointer must have been previously returned by a call to
833 /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
834 /// and alignment as `T`. This is trivially true if `U` is `T`.
835 /// Note that if `U` is not `T` but has the same size and alignment, this is
836 /// basically like transmuting references of different types. See
837 /// [`mem::transmute`][transmute] for more information on what
838 /// restrictions apply in this case.
840 /// The user of `from_raw` has to make sure a specific value of `T` is only
843 /// This function is unsafe because improper use may lead to memory unsafety,
844 /// even if the returned `Rc<T>` is never accessed.
846 /// [into_raw]: Rc::into_raw
847 /// [transmute]: core::mem::transmute
854 /// let x = Rc::new("hello".to_owned());
855 /// let x_ptr = Rc::into_raw(x);
858 /// // Convert back to an `Rc` to prevent leak.
859 /// let x = Rc::from_raw(x_ptr);
860 /// assert_eq!(&*x, "hello");
862 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
865 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
867 #[stable(feature = "rc_raw", since = "1.17.0")]
868 pub unsafe fn from_raw(ptr: *const T) -> Self {
869 let offset = unsafe { data_offset(ptr) };
871 // Reverse the offset to find the original RcBox.
873 unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) };
875 unsafe { Self::from_ptr(rc_ptr) }
878 /// Creates a new [`Weak`] pointer to this allocation.
885 /// let five = Rc::new(5);
887 /// let weak_five = Rc::downgrade(&five);
889 #[stable(feature = "rc_weak", since = "1.4.0")]
890 pub fn downgrade(this: &Self) -> Weak<T> {
891 this.inner().inc_weak();
892 // Make sure we do not create a dangling Weak
893 debug_assert!(!is_dangling(this.ptr.as_ptr()));
894 Weak { ptr: this.ptr }
897 /// Gets the number of [`Weak`] pointers to this allocation.
904 /// let five = Rc::new(5);
905 /// let _weak_five = Rc::downgrade(&five);
907 /// assert_eq!(1, Rc::weak_count(&five));
910 #[stable(feature = "rc_counts", since = "1.15.0")]
911 pub fn weak_count(this: &Self) -> usize {
912 this.inner().weak() - 1
915 /// Gets the number of strong (`Rc`) pointers to this allocation.
922 /// let five = Rc::new(5);
923 /// let _also_five = Rc::clone(&five);
925 /// assert_eq!(2, Rc::strong_count(&five));
928 #[stable(feature = "rc_counts", since = "1.15.0")]
929 pub fn strong_count(this: &Self) -> usize {
930 this.inner().strong()
933 /// Increments the strong reference count on the `Rc<T>` associated with the
934 /// provided pointer by one.
938 /// The pointer must have been obtained through `Rc::into_raw`, and the
939 /// associated `Rc` instance must be valid (i.e. the strong count must be at
940 /// least 1) for the duration of this method.
947 /// let five = Rc::new(5);
950 /// let ptr = Rc::into_raw(five);
951 /// Rc::increment_strong_count(ptr);
953 /// let five = Rc::from_raw(ptr);
954 /// assert_eq!(2, Rc::strong_count(&five));
958 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
959 pub unsafe fn increment_strong_count(ptr: *const T) {
960 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
961 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
962 // Now increase refcount, but don't drop new refcount either
963 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
966 /// Decrements the strong reference count on the `Rc<T>` associated with the
967 /// provided pointer by one.
971 /// The pointer must have been obtained through `Rc::into_raw`, and the
972 /// associated `Rc` instance must be valid (i.e. the strong count must be at
973 /// least 1) when invoking this method. This method can be used to release
974 /// the final `Rc` and backing storage, but **should not** be called after
975 /// the final `Rc` has been released.
982 /// let five = Rc::new(5);
985 /// let ptr = Rc::into_raw(five);
986 /// Rc::increment_strong_count(ptr);
988 /// let five = Rc::from_raw(ptr);
989 /// assert_eq!(2, Rc::strong_count(&five));
990 /// Rc::decrement_strong_count(ptr);
991 /// assert_eq!(1, Rc::strong_count(&five));
995 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
996 pub unsafe fn decrement_strong_count(ptr: *const T) {
997 unsafe { mem::drop(Rc::from_raw(ptr)) };
1000 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1001 /// this allocation.
1003 fn is_unique(this: &Self) -> bool {
1004 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1007 /// Returns a mutable reference into the given `Rc`, if there are
1008 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1010 /// Returns [`None`] otherwise, because it is not safe to
1011 /// mutate a shared value.
1013 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1014 /// the inner value when there are other pointers.
1016 /// [make_mut]: Rc::make_mut
1017 /// [clone]: Clone::clone
1022 /// use std::rc::Rc;
1024 /// let mut x = Rc::new(3);
1025 /// *Rc::get_mut(&mut x).unwrap() = 4;
1026 /// assert_eq!(*x, 4);
1028 /// let _y = Rc::clone(&x);
1029 /// assert!(Rc::get_mut(&mut x).is_none());
1032 #[stable(feature = "rc_unique", since = "1.4.0")]
1033 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1034 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1037 /// Returns a mutable reference into the given `Rc`,
1038 /// without any check.
1040 /// See also [`get_mut`], which is safe and does appropriate checks.
1042 /// [`get_mut`]: Rc::get_mut
1046 /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced
1047 /// for the duration of the returned borrow.
1048 /// This is trivially the case if no such pointers exist,
1049 /// for example immediately after `Rc::new`.
1054 /// #![feature(get_mut_unchecked)]
1056 /// use std::rc::Rc;
1058 /// let mut x = Rc::new(String::new());
1060 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1062 /// assert_eq!(*x, "foo");
1065 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1066 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1067 // We are careful to *not* create a reference covering the "count" fields, as
1068 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1069 unsafe { &mut (*this.ptr.as_ptr()).value }
1073 #[stable(feature = "ptr_eq", since = "1.17.0")]
1074 /// Returns `true` if the two `Rc`s point to the same allocation
1075 /// (in a vein similar to [`ptr::eq`]).
1080 /// use std::rc::Rc;
1082 /// let five = Rc::new(5);
1083 /// let same_five = Rc::clone(&five);
1084 /// let other_five = Rc::new(5);
1086 /// assert!(Rc::ptr_eq(&five, &same_five));
1087 /// assert!(!Rc::ptr_eq(&five, &other_five));
1090 /// [`ptr::eq`]: core::ptr::eq
1091 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1092 this.ptr.as_ptr() == other.ptr.as_ptr()
1096 impl<T: Clone> Rc<T> {
1097 /// Makes a mutable reference into the given `Rc`.
1099 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1100 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1101 /// referred to as clone-on-write.
1103 /// If there are no other `Rc` pointers to this allocation, then [`Weak`]
1104 /// pointers to this allocation will be disassociated.
1106 /// See also [`get_mut`], which will fail rather than cloning.
1108 /// [`clone`]: Clone::clone
1109 /// [`get_mut`]: Rc::get_mut
1114 /// use std::rc::Rc;
1116 /// let mut data = Rc::new(5);
1118 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1119 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1120 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1121 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1122 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1124 /// // Now `data` and `other_data` point to different allocations.
1125 /// assert_eq!(*data, 8);
1126 /// assert_eq!(*other_data, 12);
1129 /// [`Weak`] pointers will be disassociated:
1132 /// use std::rc::Rc;
1134 /// let mut data = Rc::new(75);
1135 /// let weak = Rc::downgrade(&data);
1137 /// assert!(75 == *data);
1138 /// assert!(75 == *weak.upgrade().unwrap());
1140 /// *Rc::make_mut(&mut data) += 1;
1142 /// assert!(76 == *data);
1143 /// assert!(weak.upgrade().is_none());
1145 #[cfg(not(no_global_oom_handling))]
1147 #[stable(feature = "rc_unique", since = "1.4.0")]
1148 pub fn make_mut(this: &mut Self) -> &mut T {
1149 if Rc::strong_count(this) != 1 {
1150 // Gotta clone the data, there are other Rcs.
1151 // Pre-allocate memory to allow writing the cloned value directly.
1152 let mut rc = Self::new_uninit();
1154 let data = Rc::get_mut_unchecked(&mut rc);
1155 (**this).write_clone_into_raw(data.as_mut_ptr());
1156 *this = rc.assume_init();
1158 } else if Rc::weak_count(this) != 0 {
1159 // Can just steal the data, all that's left is Weaks
1160 let mut rc = Self::new_uninit();
1162 let data = Rc::get_mut_unchecked(&mut rc);
1163 data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
1165 this.inner().dec_strong();
1166 // Remove implicit strong-weak ref (no need to craft a fake
1167 // Weak here -- we know other Weaks can clean up for us)
1168 this.inner().dec_weak();
1169 ptr::write(this, rc.assume_init());
1172 // This unsafety is ok because we're guaranteed that the pointer
1173 // returned is the *only* pointer that will ever be returned to T. Our
1174 // reference count is guaranteed to be 1 at this point, and we required
1175 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1176 // reference to the allocation.
1177 unsafe { &mut this.ptr.as_mut().value }
1183 #[stable(feature = "rc_downcast", since = "1.29.0")]
1184 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
1189 /// use std::any::Any;
1190 /// use std::rc::Rc;
1192 /// fn print_if_string(value: Rc<dyn Any>) {
1193 /// if let Ok(string) = value.downcast::<String>() {
1194 /// println!("String ({}): {}", string.len(), string);
1198 /// let my_string = "Hello World".to_string();
1199 /// print_if_string(Rc::new(my_string));
1200 /// print_if_string(Rc::new(0i8));
1202 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
1203 if (*self).is::<T>() {
1204 let ptr = self.ptr.cast::<RcBox<T>>();
1206 Ok(Rc::from_inner(ptr))
1213 impl<T: ?Sized> Rc<T> {
1214 /// Allocates an `RcBox<T>` with sufficient space for
1215 /// a possibly-unsized inner value where the value has the layout provided.
1217 /// The function `mem_to_rcbox` is called with the data pointer
1218 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1219 #[cfg(not(no_global_oom_handling))]
1220 unsafe fn allocate_for_layout(
1221 value_layout: Layout,
1222 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1223 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1224 ) -> *mut RcBox<T> {
1225 // Calculate layout using the given value layout.
1226 // Previously, layout was calculated on the expression
1227 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
1228 // reference (see #54908).
1229 let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align();
1231 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox)
1232 .unwrap_or_else(|_| handle_alloc_error(layout))
1236 /// Allocates an `RcBox<T>` with sufficient space for
1237 /// a possibly-unsized inner value where the value has the layout provided,
1238 /// returning an error if allocation fails.
1240 /// The function `mem_to_rcbox` is called with the data pointer
1241 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1243 unsafe fn try_allocate_for_layout(
1244 value_layout: Layout,
1245 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1246 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1247 ) -> Result<*mut RcBox<T>, AllocError> {
1248 // Calculate layout using the given value layout.
1249 // Previously, layout was calculated on the expression
1250 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
1251 // reference (see #54908).
1252 let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align();
1254 // Allocate for the layout.
1255 let ptr = allocate(layout)?;
1257 // Initialize the RcBox
1258 let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr());
1260 debug_assert_eq!(Layout::for_value(&*inner), layout);
1262 ptr::write(&mut (*inner).strong, Cell::new(1));
1263 ptr::write(&mut (*inner).weak, Cell::new(1));
1269 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
1270 #[cfg(not(no_global_oom_handling))]
1271 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
1272 // Allocate for the `RcBox<T>` using the given value.
1274 Self::allocate_for_layout(
1275 Layout::for_value(&*ptr),
1276 |layout| Global.allocate(layout),
1277 |mem| (ptr as *mut RcBox<T>).set_ptr_value(mem),
1282 #[cfg(not(no_global_oom_handling))]
1283 fn from_box(v: Box<T>) -> Rc<T> {
1285 let (box_unique, alloc) = Box::into_unique(v);
1286 let bptr = box_unique.as_ptr();
1288 let value_size = size_of_val(&*bptr);
1289 let ptr = Self::allocate_for_ptr(bptr);
1291 // Copy value as bytes
1292 ptr::copy_nonoverlapping(
1293 bptr as *const T as *const u8,
1294 &mut (*ptr).value as *mut _ as *mut u8,
1298 // Free the allocation without dropping its contents
1299 box_free(box_unique, alloc);
1307 /// Allocates an `RcBox<[T]>` with the given length.
1308 #[cfg(not(no_global_oom_handling))]
1309 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1311 Self::allocate_for_layout(
1312 Layout::array::<T>(len).unwrap(),
1313 |layout| Global.allocate(layout),
1314 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
1319 /// Copy elements from slice into newly allocated Rc<\[T\]>
1321 /// Unsafe because the caller must either take ownership or bind `T: Copy`
1322 #[cfg(not(no_global_oom_handling))]
1323 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1325 let ptr = Self::allocate_for_slice(v.len());
1326 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1331 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1333 /// Behavior is undefined should the size be wrong.
1334 #[cfg(not(no_global_oom_handling))]
1335 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1336 // Panic guard while cloning T elements.
1337 // In the event of a panic, elements that have been written
1338 // into the new RcBox will be dropped, then the memory freed.
1346 impl<T> Drop for Guard<T> {
1347 fn drop(&mut self) {
1349 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1350 ptr::drop_in_place(slice);
1352 Global.deallocate(self.mem, self.layout);
1358 let ptr = Self::allocate_for_slice(len);
1360 let mem = ptr as *mut _ as *mut u8;
1361 let layout = Layout::for_value(&*ptr);
1363 // Pointer to first element
1364 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1366 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1368 for (i, item) in iter.enumerate() {
1369 ptr::write(elems.add(i), item);
1373 // All clear. Forget the guard so it doesn't free the new RcBox.
1381 /// Specialization trait used for `From<&[T]>`.
1382 trait RcFromSlice<T> {
1383 fn from_slice(slice: &[T]) -> Self;
1386 #[cfg(not(no_global_oom_handling))]
1387 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1389 default fn from_slice(v: &[T]) -> Self {
1390 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1394 #[cfg(not(no_global_oom_handling))]
1395 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1397 fn from_slice(v: &[T]) -> Self {
1398 unsafe { Rc::copy_from_slice(v) }
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<T: ?Sized> Deref for Rc<T> {
1407 fn deref(&self) -> &T {
1412 #[unstable(feature = "receiver_trait", issue = "none")]
1413 impl<T: ?Sized> Receiver for Rc<T> {}
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1419 /// This will decrement the strong reference count. If the strong reference
1420 /// count reaches zero then the only other references (if any) are
1421 /// [`Weak`], so we `drop` the inner value.
1426 /// use std::rc::Rc;
1430 /// impl Drop for Foo {
1431 /// fn drop(&mut self) {
1432 /// println!("dropped!");
1436 /// let foo = Rc::new(Foo);
1437 /// let foo2 = Rc::clone(&foo);
1439 /// drop(foo); // Doesn't print anything
1440 /// drop(foo2); // Prints "dropped!"
1442 fn drop(&mut self) {
1444 self.inner().dec_strong();
1445 if self.inner().strong() == 0 {
1446 // destroy the contained object
1447 ptr::drop_in_place(Self::get_mut_unchecked(self));
1449 // remove the implicit "strong weak" pointer now that we've
1450 // destroyed the contents.
1451 self.inner().dec_weak();
1453 if self.inner().weak() == 0 {
1454 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<T: ?Sized> Clone for Rc<T> {
1463 /// Makes a clone of the `Rc` pointer.
1465 /// This creates another pointer to the same allocation, increasing the
1466 /// strong reference count.
1471 /// use std::rc::Rc;
1473 /// let five = Rc::new(5);
1475 /// let _ = Rc::clone(&five);
1478 fn clone(&self) -> Rc<T> {
1479 self.inner().inc_strong();
1480 Self::from_inner(self.ptr)
1484 #[cfg(not(no_global_oom_handling))]
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: Default> Default for Rc<T> {
1487 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1492 /// use std::rc::Rc;
1494 /// let x: Rc<i32> = Default::default();
1495 /// assert_eq!(*x, 0);
1498 fn default() -> Rc<T> {
1499 Rc::new(Default::default())
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 trait RcEqIdent<T: ?Sized + PartialEq> {
1505 fn eq(&self, other: &Rc<T>) -> bool;
1506 fn ne(&self, other: &Rc<T>) -> bool;
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1512 default fn eq(&self, other: &Rc<T>) -> bool {
1517 default fn ne(&self, other: &Rc<T>) -> bool {
1522 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1523 #[rustc_unsafe_specialization_marker]
1524 pub(crate) trait MarkerEq: PartialEq<Self> {}
1526 impl<T: Eq> MarkerEq for T {}
1528 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1529 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1530 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1531 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1532 /// the same value, than two `&T`s.
1534 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1538 fn eq(&self, other: &Rc<T>) -> bool {
1539 Rc::ptr_eq(self, other) || **self == **other
1543 fn ne(&self, other: &Rc<T>) -> bool {
1544 !Rc::ptr_eq(self, other) && **self != **other
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1550 /// Equality for two `Rc`s.
1552 /// Two `Rc`s are equal if their inner values are equal, even if they are
1553 /// stored in different allocation.
1555 /// If `T` also implements `Eq` (implying reflexivity of equality),
1556 /// two `Rc`s that point to the same allocation are
1562 /// use std::rc::Rc;
1564 /// let five = Rc::new(5);
1566 /// assert!(five == Rc::new(5));
1569 fn eq(&self, other: &Rc<T>) -> bool {
1570 RcEqIdent::eq(self, other)
1573 /// Inequality for two `Rc`s.
1575 /// Two `Rc`s are unequal if their inner values are unequal.
1577 /// If `T` also implements `Eq` (implying reflexivity of equality),
1578 /// two `Rc`s that point to the same allocation are
1584 /// use std::rc::Rc;
1586 /// let five = Rc::new(5);
1588 /// assert!(five != Rc::new(6));
1591 fn ne(&self, other: &Rc<T>) -> bool {
1592 RcEqIdent::ne(self, other)
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1601 /// Partial comparison for two `Rc`s.
1603 /// The two are compared by calling `partial_cmp()` on their inner values.
1608 /// use std::rc::Rc;
1609 /// use std::cmp::Ordering;
1611 /// let five = Rc::new(5);
1613 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1616 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1617 (**self).partial_cmp(&**other)
1620 /// Less-than comparison for two `Rc`s.
1622 /// The two are compared by calling `<` on their inner values.
1627 /// use std::rc::Rc;
1629 /// let five = Rc::new(5);
1631 /// assert!(five < Rc::new(6));
1634 fn lt(&self, other: &Rc<T>) -> bool {
1638 /// 'Less than or equal to' comparison for two `Rc`s.
1640 /// The two are compared by calling `<=` on their inner values.
1645 /// use std::rc::Rc;
1647 /// let five = Rc::new(5);
1649 /// assert!(five <= Rc::new(5));
1652 fn le(&self, other: &Rc<T>) -> bool {
1656 /// Greater-than comparison for two `Rc`s.
1658 /// The two are compared by calling `>` on their inner values.
1663 /// use std::rc::Rc;
1665 /// let five = Rc::new(5);
1667 /// assert!(five > Rc::new(4));
1670 fn gt(&self, other: &Rc<T>) -> bool {
1674 /// 'Greater than or equal to' comparison for two `Rc`s.
1676 /// The two are compared by calling `>=` on their inner values.
1681 /// use std::rc::Rc;
1683 /// let five = Rc::new(5);
1685 /// assert!(five >= Rc::new(5));
1688 fn ge(&self, other: &Rc<T>) -> bool {
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl<T: ?Sized + Ord> Ord for Rc<T> {
1695 /// Comparison for two `Rc`s.
1697 /// The two are compared by calling `cmp()` on their inner values.
1702 /// use std::rc::Rc;
1703 /// use std::cmp::Ordering;
1705 /// let five = Rc::new(5);
1707 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1710 fn cmp(&self, other: &Rc<T>) -> Ordering {
1711 (**self).cmp(&**other)
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<T: ?Sized + Hash> Hash for Rc<T> {
1717 fn hash<H: Hasher>(&self, state: &mut H) {
1718 (**self).hash(state);
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1725 fmt::Display::fmt(&**self, f)
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1732 fmt::Debug::fmt(&**self, f)
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1739 fmt::Pointer::fmt(&(&**self as *const T), f)
1743 #[cfg(not(no_global_oom_handling))]
1744 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1745 impl<T> From<T> for Rc<T> {
1746 /// Converts a generic type `T` into a `Rc<T>`
1748 /// The conversion allocates on the heap and moves `t`
1749 /// from the stack into it.
1753 /// # use std::rc::Rc;
1755 /// let rc = Rc::new(5);
1757 /// assert_eq!(Rc::from(x), rc);
1759 fn from(t: T) -> Self {
1764 #[cfg(not(no_global_oom_handling))]
1765 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1766 impl<T: Clone> From<&[T]> for Rc<[T]> {
1767 /// Allocate a reference-counted slice and fill it by cloning `v`'s items.
1772 /// # use std::rc::Rc;
1773 /// let original: &[i32] = &[1, 2, 3];
1774 /// let shared: Rc<[i32]> = Rc::from(original);
1775 /// assert_eq!(&[1, 2, 3], &shared[..]);
1778 fn from(v: &[T]) -> Rc<[T]> {
1779 <Self as RcFromSlice<T>>::from_slice(v)
1783 #[cfg(not(no_global_oom_handling))]
1784 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1785 impl From<&str> for Rc<str> {
1786 /// Allocate a reference-counted string slice and copy `v` into it.
1791 /// # use std::rc::Rc;
1792 /// let shared: Rc<str> = Rc::from("statue");
1793 /// assert_eq!("statue", &shared[..]);
1796 fn from(v: &str) -> Rc<str> {
1797 let rc = Rc::<[u8]>::from(v.as_bytes());
1798 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1802 #[cfg(not(no_global_oom_handling))]
1803 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1804 impl From<String> for Rc<str> {
1805 /// Allocate a reference-counted string slice and copy `v` into it.
1810 /// # use std::rc::Rc;
1811 /// let original: String = "statue".to_owned();
1812 /// let shared: Rc<str> = Rc::from(original);
1813 /// assert_eq!("statue", &shared[..]);
1816 fn from(v: String) -> Rc<str> {
1821 #[cfg(not(no_global_oom_handling))]
1822 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1823 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1824 /// Move a boxed object to a new, reference counted, allocation.
1829 /// # use std::rc::Rc;
1830 /// let original: Box<i32> = Box::new(1);
1831 /// let shared: Rc<i32> = Rc::from(original);
1832 /// assert_eq!(1, *shared);
1835 fn from(v: Box<T>) -> Rc<T> {
1840 #[cfg(not(no_global_oom_handling))]
1841 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1842 impl<T> From<Vec<T>> for Rc<[T]> {
1843 /// Allocate a reference-counted slice and move `v`'s items into it.
1848 /// # use std::rc::Rc;
1849 /// let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
1850 /// let shared: Rc<Vec<i32>> = Rc::from(original);
1851 /// assert_eq!(vec![1, 2, 3], *shared);
1854 fn from(mut v: Vec<T>) -> Rc<[T]> {
1856 let rc = Rc::copy_from_slice(&v);
1858 // Allow the Vec to free its memory, but not destroy its contents
1866 #[stable(feature = "shared_from_cow", since = "1.45.0")]
1867 impl<'a, B> From<Cow<'a, B>> for Rc<B>
1869 B: ToOwned + ?Sized,
1870 Rc<B>: From<&'a B> + From<B::Owned>,
1872 /// Create a reference-counted pointer from
1873 /// a clone-on-write pointer by copying its content.
1878 /// # use std::rc::Rc;
1879 /// # use std::borrow::Cow;
1880 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
1881 /// let shared: Rc<str> = Rc::from(cow);
1882 /// assert_eq!("eggplant", &shared[..]);
1885 fn from(cow: Cow<'a, B>) -> Rc<B> {
1887 Cow::Borrowed(s) => Rc::from(s),
1888 Cow::Owned(s) => Rc::from(s),
1893 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1894 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
1895 type Error = Rc<[T]>;
1897 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
1898 if boxed_slice.len() == N {
1899 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
1906 #[cfg(not(no_global_oom_handling))]
1907 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1908 impl<T> iter::FromIterator<T> for Rc<[T]> {
1909 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1911 /// # Performance characteristics
1913 /// ## The general case
1915 /// In the general case, collecting into `Rc<[T]>` is done by first
1916 /// collecting into a `Vec<T>`. That is, when writing the following:
1919 /// # use std::rc::Rc;
1920 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1921 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1924 /// this behaves as if we wrote:
1927 /// # use std::rc::Rc;
1928 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1929 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1930 /// .into(); // A second allocation for `Rc<[T]>` happens here.
1931 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1934 /// This will allocate as many times as needed for constructing the `Vec<T>`
1935 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1937 /// ## Iterators of known length
1939 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1940 /// a single allocation will be made for the `Rc<[T]>`. For example:
1943 /// # use std::rc::Rc;
1944 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1945 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1947 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1948 ToRcSlice::to_rc_slice(iter.into_iter())
1952 /// Specialization trait used for collecting into `Rc<[T]>`.
1953 #[cfg(not(no_global_oom_handling))]
1954 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
1955 fn to_rc_slice(self) -> Rc<[T]>;
1958 #[cfg(not(no_global_oom_handling))]
1959 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
1960 default fn to_rc_slice(self) -> Rc<[T]> {
1961 self.collect::<Vec<T>>().into()
1965 #[cfg(not(no_global_oom_handling))]
1966 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
1967 fn to_rc_slice(self) -> Rc<[T]> {
1968 // This is the case for a `TrustedLen` iterator.
1969 let (low, high) = self.size_hint();
1970 if let Some(high) = high {
1974 "TrustedLen iterator's size hint is not exact: {:?}",
1979 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1980 Rc::from_iter_exact(self, low)
1983 // TrustedLen contract guarantees that `upper_bound == `None` implies an iterator
1984 // length exceeding `usize::MAX`.
1985 // The default implementation would collect into a vec which would panic.
1986 // Thus we panic here immediately without invoking `Vec` code.
1987 panic!("capacity overflow");
1992 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1993 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
1994 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1996 /// Since a `Weak` reference does not count towards ownership, it will not
1997 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
1998 /// guarantees about the value still being present. Thus it may return [`None`]
1999 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
2000 /// itself (the backing store) from being deallocated.
2002 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
2003 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2004 /// prevent circular references between [`Rc`] pointers, since mutual owning references
2005 /// would never allow either [`Rc`] to be dropped. For example, a tree could
2006 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2007 /// pointers from children back to their parents.
2009 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2011 /// [`upgrade`]: Weak::upgrade
2012 #[stable(feature = "rc_weak", since = "1.4.0")]
2013 pub struct Weak<T: ?Sized> {
2014 // This is a `NonNull` to allow optimizing the size of this type in enums,
2015 // but it is not necessarily a valid pointer.
2016 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
2017 // to allocate space on the heap. That's not a value a real pointer
2018 // will ever have because RcBox has alignment at least 2.
2019 // This is only possible when `T: Sized`; unsized `T` never dangle.
2020 ptr: NonNull<RcBox<T>>,
2023 #[stable(feature = "rc_weak", since = "1.4.0")]
2024 impl<T: ?Sized> !marker::Send for Weak<T> {}
2025 #[stable(feature = "rc_weak", since = "1.4.0")]
2026 impl<T: ?Sized> !marker::Sync for Weak<T> {}
2028 #[unstable(feature = "coerce_unsized", issue = "27732")]
2029 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
2031 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2032 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
2035 /// Constructs a new `Weak<T>`, without allocating any memory.
2036 /// Calling [`upgrade`] on the return value always gives [`None`].
2038 /// [`upgrade`]: Weak::upgrade
2043 /// use std::rc::Weak;
2045 /// let empty: Weak<i64> = Weak::new();
2046 /// assert!(empty.upgrade().is_none());
2048 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2049 pub fn new() -> Weak<T> {
2050 Weak { ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0") }
2054 pub(crate) fn is_dangling<T: ?Sized>(ptr: *mut T) -> bool {
2055 let address = ptr as *mut () as usize;
2056 address == usize::MAX
2059 /// Helper type to allow accessing the reference counts without
2060 /// making any assertions about the data field.
2061 struct WeakInner<'a> {
2062 weak: &'a Cell<usize>,
2063 strong: &'a Cell<usize>,
2066 impl<T: ?Sized> Weak<T> {
2067 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
2069 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
2070 /// unaligned or even [`null`] otherwise.
2075 /// use std::rc::Rc;
2078 /// let strong = Rc::new("hello".to_owned());
2079 /// let weak = Rc::downgrade(&strong);
2080 /// // Both point to the same object
2081 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
2082 /// // The strong here keeps it alive, so we can still access the object.
2083 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
2086 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
2087 /// // undefined behaviour.
2088 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
2091 /// [`null`]: core::ptr::null
2092 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
2093 pub fn as_ptr(&self) -> *const T {
2094 let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
2096 if is_dangling(ptr) {
2097 // If the pointer is dangling, we return the sentinel directly. This cannot be
2098 // a valid payload address, as the payload is at least as aligned as RcBox (usize).
2101 // SAFETY: if is_dangling returns false, then the pointer is dereferencable.
2102 // The payload may be dropped at this point, and we have to maintain provenance,
2103 // so use raw pointer manipulation.
2104 unsafe { ptr::addr_of_mut!((*ptr).value) }
2108 /// Consumes the `Weak<T>` and turns it into a raw pointer.
2110 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
2111 /// one weak reference (the weak count is not modified by this operation). It can be turned
2112 /// back into the `Weak<T>` with [`from_raw`].
2114 /// The same restrictions of accessing the target of the pointer as with
2115 /// [`as_ptr`] apply.
2120 /// use std::rc::{Rc, Weak};
2122 /// let strong = Rc::new("hello".to_owned());
2123 /// let weak = Rc::downgrade(&strong);
2124 /// let raw = weak.into_raw();
2126 /// assert_eq!(1, Rc::weak_count(&strong));
2127 /// assert_eq!("hello", unsafe { &*raw });
2129 /// drop(unsafe { Weak::from_raw(raw) });
2130 /// assert_eq!(0, Rc::weak_count(&strong));
2133 /// [`from_raw`]: Weak::from_raw
2134 /// [`as_ptr`]: Weak::as_ptr
2135 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2136 pub fn into_raw(self) -> *const T {
2137 let result = self.as_ptr();
2142 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
2144 /// This can be used to safely get a strong reference (by calling [`upgrade`]
2145 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
2147 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
2148 /// as these don't own anything; the method still works on them).
2152 /// The pointer must have originated from the [`into_raw`] and must still own its potential
2155 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
2156 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
2157 /// count is not modified by this operation) and therefore it must be paired with a previous
2158 /// call to [`into_raw`].
2163 /// use std::rc::{Rc, Weak};
2165 /// let strong = Rc::new("hello".to_owned());
2167 /// let raw_1 = Rc::downgrade(&strong).into_raw();
2168 /// let raw_2 = Rc::downgrade(&strong).into_raw();
2170 /// assert_eq!(2, Rc::weak_count(&strong));
2172 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
2173 /// assert_eq!(1, Rc::weak_count(&strong));
2177 /// // Decrement the last weak count.
2178 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
2181 /// [`into_raw`]: Weak::into_raw
2182 /// [`upgrade`]: Weak::upgrade
2183 /// [`new`]: Weak::new
2184 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2185 pub unsafe fn from_raw(ptr: *const T) -> Self {
2186 // See Weak::as_ptr for context on how the input pointer is derived.
2188 let ptr = if is_dangling(ptr as *mut T) {
2189 // This is a dangling Weak.
2190 ptr as *mut RcBox<T>
2192 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
2193 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
2194 let offset = unsafe { data_offset(ptr) };
2195 // Thus, we reverse the offset to get the whole RcBox.
2196 // SAFETY: the pointer originated from a Weak, so this offset is safe.
2197 unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) }
2200 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
2201 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } }
2204 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
2205 /// dropping of the inner value if successful.
2207 /// Returns [`None`] if the inner value has since been dropped.
2212 /// use std::rc::Rc;
2214 /// let five = Rc::new(5);
2216 /// let weak_five = Rc::downgrade(&five);
2218 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
2219 /// assert!(strong_five.is_some());
2221 /// // Destroy all strong pointers.
2222 /// drop(strong_five);
2225 /// assert!(weak_five.upgrade().is_none());
2227 #[stable(feature = "rc_weak", since = "1.4.0")]
2228 pub fn upgrade(&self) -> Option<Rc<T>> {
2229 let inner = self.inner()?;
2230 if inner.strong() == 0 {
2234 Some(Rc::from_inner(self.ptr))
2238 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
2240 /// If `self` was created using [`Weak::new`], this will return 0.
2241 #[stable(feature = "weak_counts", since = "1.41.0")]
2242 pub fn strong_count(&self) -> usize {
2243 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
2246 /// Gets the number of `Weak` pointers pointing to this allocation.
2248 /// If no strong pointers remain, this will return zero.
2249 #[stable(feature = "weak_counts", since = "1.41.0")]
2250 pub fn weak_count(&self) -> usize {
2253 if inner.strong() > 0 {
2254 inner.weak() - 1 // subtract the implicit weak ptr
2262 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`,
2263 /// (i.e., when this `Weak` was created by `Weak::new`).
2265 fn inner(&self) -> Option<WeakInner<'_>> {
2266 if is_dangling(self.ptr.as_ptr()) {
2269 // We are careful to *not* create a reference covering the "data" field, as
2270 // the field may be mutated concurrently (for example, if the last `Rc`
2271 // is dropped, the data field will be dropped in-place).
2273 let ptr = self.ptr.as_ptr();
2274 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
2279 /// Returns `true` if the two `Weak`s point to the same allocation (similar to
2280 /// [`ptr::eq`]), or if both don't point to any allocation
2281 /// (because they were created with `Weak::new()`).
2285 /// Since this compares pointers it means that `Weak::new()` will equal each
2286 /// other, even though they don't point to any allocation.
2291 /// use std::rc::Rc;
2293 /// let first_rc = Rc::new(5);
2294 /// let first = Rc::downgrade(&first_rc);
2295 /// let second = Rc::downgrade(&first_rc);
2297 /// assert!(first.ptr_eq(&second));
2299 /// let third_rc = Rc::new(5);
2300 /// let third = Rc::downgrade(&third_rc);
2302 /// assert!(!first.ptr_eq(&third));
2305 /// Comparing `Weak::new`.
2308 /// use std::rc::{Rc, Weak};
2310 /// let first = Weak::new();
2311 /// let second = Weak::new();
2312 /// assert!(first.ptr_eq(&second));
2314 /// let third_rc = Rc::new(());
2315 /// let third = Rc::downgrade(&third_rc);
2316 /// assert!(!first.ptr_eq(&third));
2319 /// [`ptr::eq`]: core::ptr::eq
2321 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
2322 pub fn ptr_eq(&self, other: &Self) -> bool {
2323 self.ptr.as_ptr() == other.ptr.as_ptr()
2327 #[stable(feature = "rc_weak", since = "1.4.0")]
2328 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
2329 /// Drops the `Weak` pointer.
2334 /// use std::rc::{Rc, Weak};
2338 /// impl Drop for Foo {
2339 /// fn drop(&mut self) {
2340 /// println!("dropped!");
2344 /// let foo = Rc::new(Foo);
2345 /// let weak_foo = Rc::downgrade(&foo);
2346 /// let other_weak_foo = Weak::clone(&weak_foo);
2348 /// drop(weak_foo); // Doesn't print anything
2349 /// drop(foo); // Prints "dropped!"
2351 /// assert!(other_weak_foo.upgrade().is_none());
2353 fn drop(&mut self) {
2354 let inner = if let Some(inner) = self.inner() { inner } else { return };
2357 // the weak count starts at 1, and will only go to zero if all
2358 // the strong pointers have disappeared.
2359 if inner.weak() == 0 {
2361 Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
2367 #[stable(feature = "rc_weak", since = "1.4.0")]
2368 impl<T: ?Sized> Clone for Weak<T> {
2369 /// Makes a clone of the `Weak` pointer that points to the same allocation.
2374 /// use std::rc::{Rc, Weak};
2376 /// let weak_five = Rc::downgrade(&Rc::new(5));
2378 /// let _ = Weak::clone(&weak_five);
2381 fn clone(&self) -> Weak<T> {
2382 if let Some(inner) = self.inner() {
2385 Weak { ptr: self.ptr }
2389 #[stable(feature = "rc_weak", since = "1.4.0")]
2390 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
2391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2396 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2397 impl<T> Default for Weak<T> {
2398 /// Constructs a new `Weak<T>`, without allocating any memory.
2399 /// Calling [`upgrade`] on the return value always gives [`None`].
2401 /// [`None`]: Option
2402 /// [`upgrade`]: Weak::upgrade
2407 /// use std::rc::Weak;
2409 /// let empty: Weak<i64> = Default::default();
2410 /// assert!(empty.upgrade().is_none());
2412 fn default() -> Weak<T> {
2417 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2418 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2419 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2420 // We abort because this is such a degenerate scenario that we don't care about
2421 // what happens -- no real program should ever experience this.
2423 // This should have negligible overhead since you don't actually need to
2424 // clone these much in Rust thanks to ownership and move-semantics.
2428 fn weak_ref(&self) -> &Cell<usize>;
2429 fn strong_ref(&self) -> &Cell<usize>;
2432 fn strong(&self) -> usize {
2433 self.strong_ref().get()
2437 fn inc_strong(&self) {
2438 let strong = self.strong();
2440 // We want to abort on overflow instead of dropping the value.
2441 // The reference count will never be zero when this is called;
2442 // nevertheless, we insert an abort here to hint LLVM at
2443 // an otherwise missed optimization.
2444 if strong == 0 || strong == usize::MAX {
2447 self.strong_ref().set(strong + 1);
2451 fn dec_strong(&self) {
2452 self.strong_ref().set(self.strong() - 1);
2456 fn weak(&self) -> usize {
2457 self.weak_ref().get()
2461 fn inc_weak(&self) {
2462 let weak = self.weak();
2464 // We want to abort on overflow instead of dropping the value.
2465 // The reference count will never be zero when this is called;
2466 // nevertheless, we insert an abort here to hint LLVM at
2467 // an otherwise missed optimization.
2468 if weak == 0 || weak == usize::MAX {
2471 self.weak_ref().set(weak + 1);
2475 fn dec_weak(&self) {
2476 self.weak_ref().set(self.weak() - 1);
2480 impl<T: ?Sized> RcInnerPtr for RcBox<T> {
2482 fn weak_ref(&self) -> &Cell<usize> {
2487 fn strong_ref(&self) -> &Cell<usize> {
2492 impl<'a> RcInnerPtr for WeakInner<'a> {
2494 fn weak_ref(&self) -> &Cell<usize> {
2499 fn strong_ref(&self) -> &Cell<usize> {
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2506 fn borrow(&self) -> &T {
2511 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2512 impl<T: ?Sized> AsRef<T> for Rc<T> {
2513 fn as_ref(&self) -> &T {
2518 #[stable(feature = "pin", since = "1.33.0")]
2519 impl<T: ?Sized> Unpin for Rc<T> {}
2521 /// Get the offset within an `RcBox` for the payload behind a pointer.
2525 /// The pointer must point to (and have valid metadata for) a previously
2526 /// valid instance of T, but the T is allowed to be dropped.
2527 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2528 // Align the unsized value to the end of the RcBox.
2529 // Because RcBox is repr(C), it will always be the last field in memory.
2530 // SAFETY: since the only unsized types possible are slices, trait objects,
2531 // and extern types, the input safety requirement is currently enough to
2532 // satisfy the requirements of align_of_val_raw; this is an implementation
2533 // detail of the language that must not be relied upon outside of std.
2534 unsafe { data_offset_align(align_of_val_raw(ptr)) }
2538 fn data_offset_align(align: usize) -> isize {
2539 let layout = Layout::new::<RcBox<()>>();
2540 (layout.size() + layout.padding_needed_for(align)) as isize