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 //! let my_weak = 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 /// Calculate layout for `RcBox<T>` using the inner value's layout
297 fn rcbox_layout_for_value_layout(layout: Layout) -> Layout {
298 // Calculate layout using the given value layout.
299 // Previously, layout was calculated on the expression
300 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
301 // reference (see #54908).
302 Layout::new::<RcBox<()>>().extend(layout).unwrap().0.pad_to_align()
305 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
308 /// See the [module-level documentation](./index.html) for more details.
310 /// The inherent methods of `Rc` are all associated functions, which means
311 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
312 /// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
314 /// [get_mut]: Rc::get_mut
315 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
316 #[stable(feature = "rust1", since = "1.0.0")]
317 #[rustc_insignificant_dtor]
318 pub struct Rc<T: ?Sized> {
319 ptr: NonNull<RcBox<T>>,
320 phantom: PhantomData<RcBox<T>>,
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<T: ?Sized> !marker::Send for Rc<T> {}
326 // Note that this negative impl isn't strictly necessary for correctness,
327 // as `Rc` transitively contains a `Cell`, which is itself `!Sync`.
328 // However, given how important `Rc`'s `!Sync`-ness is,
329 // having an explicit negative impl is nice for documentation purposes
330 // and results in nicer error messages.
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<T: ?Sized> !marker::Sync for Rc<T> {}
334 #[stable(feature = "catch_unwind", since = "1.9.0")]
335 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
336 #[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")]
337 impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for Rc<T> {}
339 #[unstable(feature = "coerce_unsized", issue = "27732")]
340 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
342 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
343 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
345 impl<T: ?Sized> Rc<T> {
347 fn inner(&self) -> &RcBox<T> {
348 // This unsafety is ok because while this Rc is alive we're guaranteed
349 // that the inner pointer is valid.
350 unsafe { self.ptr.as_ref() }
353 unsafe fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
354 Self { ptr, phantom: PhantomData }
357 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
358 unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
363 /// Constructs a new `Rc<T>`.
370 /// let five = Rc::new(5);
372 #[cfg(not(no_global_oom_handling))]
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn new(value: T) -> Rc<T> {
375 // There is an implicit weak pointer owned by all the strong
376 // pointers, which ensures that the weak destructor never frees
377 // the allocation while the strong destructor is running, even
378 // if the weak pointer is stored inside the strong one.
381 Box::leak(Box::new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value }))
387 /// Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation,
388 /// to allow you to construct a `T` which holds a weak pointer to itself.
390 /// Generally, a structure circularly referencing itself, either directly or
391 /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
392 /// Using this function, you get access to the weak pointer during the
393 /// initialization of `T`, before the `Rc<T>` is created, such that you can
394 /// clone and store it inside the `T`.
396 /// `new_cyclic` first allocates the managed allocation for the `Rc<T>`,
397 /// then calls your closure, giving it a `Weak<T>` to this allocation,
398 /// and only afterwards completes the construction of the `Rc<T>` by placing
399 /// the `T` returned from your closure into the allocation.
401 /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
402 /// returns, calling [`upgrade`] on the weak reference inside your closure will
403 /// fail and result in a `None` value.
407 /// If `data_fn` panics, the panic is propagated to the caller, and the
408 /// temporary [`Weak<T>`] is dropped normally.
413 /// # #![allow(dead_code)]
414 /// use std::rc::{Rc, Weak};
417 /// me: Weak<Gadget>,
421 /// /// Construct a reference counted Gadget.
422 /// fn new() -> Rc<Self> {
423 /// // `me` is a `Weak<Gadget>` pointing at the new allocation of the
424 /// // `Rc` we're constructing.
425 /// Rc::new_cyclic(|me| {
426 /// // Create the actual struct here.
427 /// Gadget { me: me.clone() }
431 /// /// Return a reference counted pointer to Self.
432 /// fn me(&self) -> Rc<Self> {
433 /// self.me.upgrade().unwrap()
437 /// [`upgrade`]: Weak::upgrade
438 #[cfg(not(no_global_oom_handling))]
439 #[stable(feature = "arc_new_cyclic", since = "1.60.0")]
440 pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
442 F: FnOnce(&Weak<T>) -> T,
444 // Construct the inner in the "uninitialized" state with a single
446 let uninit_ptr: NonNull<_> = Box::leak(Box::new(RcBox {
447 strong: Cell::new(0),
449 value: mem::MaybeUninit::<T>::uninit(),
453 let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast();
455 let weak = Weak { ptr: init_ptr };
457 // It's important we don't give up ownership of the weak pointer, or
458 // else the memory might be freed by the time `data_fn` returns. If
459 // we really wanted to pass ownership, we could create an additional
460 // weak pointer for ourselves, but this would result in additional
461 // updates to the weak reference count which might not be necessary
463 let data = data_fn(&weak);
465 let strong = unsafe {
466 let inner = init_ptr.as_ptr();
467 ptr::write(ptr::addr_of_mut!((*inner).value), data);
469 let prev_value = (*inner).strong.get();
470 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
471 (*inner).strong.set(1);
473 Rc::from_inner(init_ptr)
476 // Strong references should collectively own a shared weak reference,
477 // so don't run the destructor for our old weak reference.
482 /// Constructs a new `Rc` with uninitialized contents.
487 /// #![feature(new_uninit)]
488 /// #![feature(get_mut_unchecked)]
492 /// let mut five = Rc::<u32>::new_uninit();
494 /// // Deferred initialization:
495 /// Rc::get_mut(&mut five).unwrap().write(5);
497 /// let five = unsafe { five.assume_init() };
499 /// assert_eq!(*five, 5)
501 #[cfg(not(no_global_oom_handling))]
502 #[unstable(feature = "new_uninit", issue = "63291")]
504 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
506 Rc::from_ptr(Rc::allocate_for_layout(
508 |layout| Global.allocate(layout),
509 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
514 /// Constructs a new `Rc` with uninitialized contents, with the memory
515 /// being filled with `0` bytes.
517 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
518 /// incorrect usage of this method.
523 /// #![feature(new_uninit)]
527 /// let zero = Rc::<u32>::new_zeroed();
528 /// let zero = unsafe { zero.assume_init() };
530 /// assert_eq!(*zero, 0)
533 /// [zeroed]: mem::MaybeUninit::zeroed
534 #[cfg(not(no_global_oom_handling))]
535 #[unstable(feature = "new_uninit", issue = "63291")]
537 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
539 Rc::from_ptr(Rc::allocate_for_layout(
541 |layout| Global.allocate_zeroed(layout),
542 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
547 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
552 /// #![feature(allocator_api)]
555 /// let five = Rc::try_new(5);
556 /// # Ok::<(), std::alloc::AllocError>(())
558 #[unstable(feature = "allocator_api", issue = "32838")]
559 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
560 // There is an implicit weak pointer owned by all the strong
561 // pointers, which ensures that the weak destructor never frees
562 // the allocation while the strong destructor is running, even
563 // if the weak pointer is stored inside the strong one.
566 Box::leak(Box::try_new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value })?)
572 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
577 /// #![feature(allocator_api, new_uninit)]
578 /// #![feature(get_mut_unchecked)]
582 /// let mut five = Rc::<u32>::try_new_uninit()?;
584 /// // Deferred initialization:
585 /// Rc::get_mut(&mut five).unwrap().write(5);
587 /// let five = unsafe { five.assume_init() };
589 /// assert_eq!(*five, 5);
590 /// # Ok::<(), std::alloc::AllocError>(())
592 #[unstable(feature = "allocator_api", issue = "32838")]
593 // #[unstable(feature = "new_uninit", issue = "63291")]
594 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
596 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
598 |layout| Global.allocate(layout),
599 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
604 /// Constructs a new `Rc` with uninitialized contents, with the memory
605 /// being filled with `0` bytes, returning an error if the allocation fails
607 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
608 /// incorrect usage of this method.
613 /// #![feature(allocator_api, new_uninit)]
617 /// let zero = Rc::<u32>::try_new_zeroed()?;
618 /// let zero = unsafe { zero.assume_init() };
620 /// assert_eq!(*zero, 0);
621 /// # Ok::<(), std::alloc::AllocError>(())
624 /// [zeroed]: mem::MaybeUninit::zeroed
625 #[unstable(feature = "allocator_api", issue = "32838")]
626 //#[unstable(feature = "new_uninit", issue = "63291")]
627 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
629 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
631 |layout| Global.allocate_zeroed(layout),
632 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
636 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
637 /// `value` will be pinned in memory and unable to be moved.
638 #[cfg(not(no_global_oom_handling))]
639 #[stable(feature = "pin", since = "1.33.0")]
641 pub fn pin(value: T) -> Pin<Rc<T>> {
642 unsafe { Pin::new_unchecked(Rc::new(value)) }
645 /// Returns the inner value, if the `Rc` has exactly one strong reference.
647 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
650 /// This will succeed even if there are outstanding weak references.
657 /// let x = Rc::new(3);
658 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
660 /// let x = Rc::new(4);
661 /// let _y = Rc::clone(&x);
662 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
665 #[stable(feature = "rc_unique", since = "1.4.0")]
666 pub fn try_unwrap(this: Self) -> Result<T, Self> {
667 if Rc::strong_count(&this) == 1 {
669 let val = ptr::read(&*this); // copy the contained object
671 // Indicate to Weaks that they can't be promoted by decrementing
672 // the strong count, and then remove the implicit "strong weak"
673 // pointer while also handling drop logic by just crafting a
675 this.inner().dec_strong();
676 let _weak = Weak { ptr: this.ptr };
687 /// Constructs a new reference-counted slice with uninitialized contents.
692 /// #![feature(new_uninit)]
693 /// #![feature(get_mut_unchecked)]
697 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
699 /// // Deferred initialization:
700 /// let data = Rc::get_mut(&mut values).unwrap();
701 /// data[0].write(1);
702 /// data[1].write(2);
703 /// data[2].write(3);
705 /// let values = unsafe { values.assume_init() };
707 /// assert_eq!(*values, [1, 2, 3])
709 #[cfg(not(no_global_oom_handling))]
710 #[unstable(feature = "new_uninit", issue = "63291")]
712 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
713 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
716 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
717 /// filled with `0` bytes.
719 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
720 /// incorrect usage of this method.
725 /// #![feature(new_uninit)]
729 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
730 /// let values = unsafe { values.assume_init() };
732 /// assert_eq!(*values, [0, 0, 0])
735 /// [zeroed]: mem::MaybeUninit::zeroed
736 #[cfg(not(no_global_oom_handling))]
737 #[unstable(feature = "new_uninit", issue = "63291")]
739 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
741 Rc::from_ptr(Rc::allocate_for_layout(
742 Layout::array::<T>(len).unwrap(),
743 |layout| Global.allocate_zeroed(layout),
745 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
746 as *mut RcBox<[mem::MaybeUninit<T>]>
753 impl<T> Rc<mem::MaybeUninit<T>> {
754 /// Converts to `Rc<T>`.
758 /// As with [`MaybeUninit::assume_init`],
759 /// it is up to the caller to guarantee that the inner value
760 /// really is in an initialized state.
761 /// Calling this when the content is not yet fully initialized
762 /// causes immediate undefined behavior.
764 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
769 /// #![feature(new_uninit)]
770 /// #![feature(get_mut_unchecked)]
774 /// let mut five = Rc::<u32>::new_uninit();
776 /// // Deferred initialization:
777 /// Rc::get_mut(&mut five).unwrap().write(5);
779 /// let five = unsafe { five.assume_init() };
781 /// assert_eq!(*five, 5)
783 #[unstable(feature = "new_uninit", issue = "63291")]
785 pub unsafe fn assume_init(self) -> Rc<T> {
786 unsafe { Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast()) }
790 impl<T> Rc<[mem::MaybeUninit<T>]> {
791 /// Converts to `Rc<[T]>`.
795 /// As with [`MaybeUninit::assume_init`],
796 /// it is up to the caller to guarantee that the inner value
797 /// really is in an initialized state.
798 /// Calling this when the content is not yet fully initialized
799 /// causes immediate undefined behavior.
801 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
806 /// #![feature(new_uninit)]
807 /// #![feature(get_mut_unchecked)]
811 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
813 /// // Deferred initialization:
814 /// let data = Rc::get_mut(&mut values).unwrap();
815 /// data[0].write(1);
816 /// data[1].write(2);
817 /// data[2].write(3);
819 /// let values = unsafe { values.assume_init() };
821 /// assert_eq!(*values, [1, 2, 3])
823 #[unstable(feature = "new_uninit", issue = "63291")]
825 pub unsafe fn assume_init(self) -> Rc<[T]> {
826 unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
830 impl<T: ?Sized> Rc<T> {
831 /// Consumes the `Rc`, returning the wrapped pointer.
833 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
834 /// [`Rc::from_raw`].
841 /// let x = Rc::new("hello".to_owned());
842 /// let x_ptr = Rc::into_raw(x);
843 /// assert_eq!(unsafe { &*x_ptr }, "hello");
845 #[stable(feature = "rc_raw", since = "1.17.0")]
846 pub fn into_raw(this: Self) -> *const T {
847 let ptr = Self::as_ptr(&this);
852 /// Provides a raw pointer to the data.
854 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
855 /// for as long there are strong counts in the `Rc`.
862 /// let x = Rc::new("hello".to_owned());
863 /// let y = Rc::clone(&x);
864 /// let x_ptr = Rc::as_ptr(&x);
865 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
866 /// assert_eq!(unsafe { &*x_ptr }, "hello");
868 #[stable(feature = "weak_into_raw", since = "1.45.0")]
869 pub fn as_ptr(this: &Self) -> *const T {
870 let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
872 // SAFETY: This cannot go through Deref::deref or Rc::inner because
873 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
874 // write through the pointer after the Rc is recovered through `from_raw`.
875 unsafe { ptr::addr_of_mut!((*ptr).value) }
878 /// Constructs an `Rc<T>` from a raw pointer.
880 /// The raw pointer must have been previously returned by a call to
881 /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
882 /// and alignment as `T`. This is trivially true if `U` is `T`.
883 /// Note that if `U` is not `T` but has the same size and alignment, this is
884 /// basically like transmuting references of different types. See
885 /// [`mem::transmute`] for more information on what
886 /// restrictions apply in this case.
888 /// The user of `from_raw` has to make sure a specific value of `T` is only
891 /// This function is unsafe because improper use may lead to memory unsafety,
892 /// even if the returned `Rc<T>` is never accessed.
894 /// [into_raw]: Rc::into_raw
901 /// let x = Rc::new("hello".to_owned());
902 /// let x_ptr = Rc::into_raw(x);
905 /// // Convert back to an `Rc` to prevent leak.
906 /// let x = Rc::from_raw(x_ptr);
907 /// assert_eq!(&*x, "hello");
909 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
912 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
914 #[stable(feature = "rc_raw", since = "1.17.0")]
915 pub unsafe fn from_raw(ptr: *const T) -> Self {
916 let offset = unsafe { data_offset(ptr) };
918 // Reverse the offset to find the original RcBox.
919 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcBox<T> };
921 unsafe { Self::from_ptr(rc_ptr) }
924 /// Creates a new [`Weak`] pointer to this allocation.
931 /// let five = Rc::new(5);
933 /// let weak_five = Rc::downgrade(&five);
935 #[must_use = "this returns a new `Weak` pointer, \
936 without modifying the original `Rc`"]
937 #[stable(feature = "rc_weak", since = "1.4.0")]
938 pub fn downgrade(this: &Self) -> Weak<T> {
939 this.inner().inc_weak();
940 // Make sure we do not create a dangling Weak
941 debug_assert!(!is_dangling(this.ptr.as_ptr()));
942 Weak { ptr: this.ptr }
945 /// Gets the number of [`Weak`] pointers to this allocation.
952 /// let five = Rc::new(5);
953 /// let _weak_five = Rc::downgrade(&five);
955 /// assert_eq!(1, Rc::weak_count(&five));
958 #[stable(feature = "rc_counts", since = "1.15.0")]
959 pub fn weak_count(this: &Self) -> usize {
960 this.inner().weak() - 1
963 /// Gets the number of strong (`Rc`) pointers to this allocation.
970 /// let five = Rc::new(5);
971 /// let _also_five = Rc::clone(&five);
973 /// assert_eq!(2, Rc::strong_count(&five));
976 #[stable(feature = "rc_counts", since = "1.15.0")]
977 pub fn strong_count(this: &Self) -> usize {
978 this.inner().strong()
981 /// Increments the strong reference count on the `Rc<T>` associated with the
982 /// provided pointer by one.
986 /// The pointer must have been obtained through `Rc::into_raw`, and the
987 /// associated `Rc` instance must be valid (i.e. the strong count must be at
988 /// least 1) for the duration of this method.
995 /// let five = Rc::new(5);
998 /// let ptr = Rc::into_raw(five);
999 /// Rc::increment_strong_count(ptr);
1001 /// let five = Rc::from_raw(ptr);
1002 /// assert_eq!(2, Rc::strong_count(&five));
1006 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1007 pub unsafe fn increment_strong_count(ptr: *const T) {
1008 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1009 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
1010 // Now increase refcount, but don't drop new refcount either
1011 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1014 /// Decrements the strong reference count on the `Rc<T>` associated with the
1015 /// provided pointer by one.
1019 /// The pointer must have been obtained through `Rc::into_raw`, and the
1020 /// associated `Rc` instance must be valid (i.e. the strong count must be at
1021 /// least 1) when invoking this method. This method can be used to release
1022 /// the final `Rc` and backing storage, but **should not** be called after
1023 /// the final `Rc` has been released.
1028 /// use std::rc::Rc;
1030 /// let five = Rc::new(5);
1033 /// let ptr = Rc::into_raw(five);
1034 /// Rc::increment_strong_count(ptr);
1036 /// let five = Rc::from_raw(ptr);
1037 /// assert_eq!(2, Rc::strong_count(&five));
1038 /// Rc::decrement_strong_count(ptr);
1039 /// assert_eq!(1, Rc::strong_count(&five));
1043 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1044 pub unsafe fn decrement_strong_count(ptr: *const T) {
1045 unsafe { mem::drop(Rc::from_raw(ptr)) };
1048 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1049 /// this allocation.
1051 fn is_unique(this: &Self) -> bool {
1052 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1055 /// Returns a mutable reference into the given `Rc`, if there are
1056 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1058 /// Returns [`None`] otherwise, because it is not safe to
1059 /// mutate a shared value.
1061 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1062 /// the inner value when there are other `Rc` pointers.
1064 /// [make_mut]: Rc::make_mut
1065 /// [clone]: Clone::clone
1070 /// use std::rc::Rc;
1072 /// let mut x = Rc::new(3);
1073 /// *Rc::get_mut(&mut x).unwrap() = 4;
1074 /// assert_eq!(*x, 4);
1076 /// let _y = Rc::clone(&x);
1077 /// assert!(Rc::get_mut(&mut x).is_none());
1080 #[stable(feature = "rc_unique", since = "1.4.0")]
1081 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1082 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1085 /// Returns a mutable reference into the given `Rc`,
1086 /// without any check.
1088 /// See also [`get_mut`], which is safe and does appropriate checks.
1090 /// [`get_mut`]: Rc::get_mut
1094 /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced
1095 /// for the duration of the returned borrow.
1096 /// This is trivially the case if no such pointers exist,
1097 /// for example immediately after `Rc::new`.
1102 /// #![feature(get_mut_unchecked)]
1104 /// use std::rc::Rc;
1106 /// let mut x = Rc::new(String::new());
1108 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1110 /// assert_eq!(*x, "foo");
1113 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1114 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1115 // We are careful to *not* create a reference covering the "count" fields, as
1116 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1117 unsafe { &mut (*this.ptr.as_ptr()).value }
1121 #[stable(feature = "ptr_eq", since = "1.17.0")]
1122 /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
1123 /// [`ptr::eq`]. See [that function][`ptr::eq`] for caveats when comparing `dyn Trait` pointers.
1128 /// use std::rc::Rc;
1130 /// let five = Rc::new(5);
1131 /// let same_five = Rc::clone(&five);
1132 /// let other_five = Rc::new(5);
1134 /// assert!(Rc::ptr_eq(&five, &same_five));
1135 /// assert!(!Rc::ptr_eq(&five, &other_five));
1137 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1138 this.ptr.as_ptr() == other.ptr.as_ptr()
1142 impl<T: Clone> Rc<T> {
1143 /// Makes a mutable reference into the given `Rc`.
1145 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1146 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1147 /// referred to as clone-on-write.
1149 /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
1150 /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
1153 /// See also [`get_mut`], which will fail rather than cloning the inner value
1154 /// or disassociating [`Weak`] pointers.
1156 /// [`clone`]: Clone::clone
1157 /// [`get_mut`]: Rc::get_mut
1162 /// use std::rc::Rc;
1164 /// let mut data = Rc::new(5);
1166 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1167 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1168 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1169 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1170 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1172 /// // Now `data` and `other_data` point to different allocations.
1173 /// assert_eq!(*data, 8);
1174 /// assert_eq!(*other_data, 12);
1177 /// [`Weak`] pointers will be disassociated:
1180 /// use std::rc::Rc;
1182 /// let mut data = Rc::new(75);
1183 /// let weak = Rc::downgrade(&data);
1185 /// assert!(75 == *data);
1186 /// assert!(75 == *weak.upgrade().unwrap());
1188 /// *Rc::make_mut(&mut data) += 1;
1190 /// assert!(76 == *data);
1191 /// assert!(weak.upgrade().is_none());
1193 #[cfg(not(no_global_oom_handling))]
1195 #[stable(feature = "rc_unique", since = "1.4.0")]
1196 pub fn make_mut(this: &mut Self) -> &mut T {
1197 if Rc::strong_count(this) != 1 {
1198 // Gotta clone the data, there are other Rcs.
1199 // Pre-allocate memory to allow writing the cloned value directly.
1200 let mut rc = Self::new_uninit();
1202 let data = Rc::get_mut_unchecked(&mut rc);
1203 (**this).write_clone_into_raw(data.as_mut_ptr());
1204 *this = rc.assume_init();
1206 } else if Rc::weak_count(this) != 0 {
1207 // Can just steal the data, all that's left is Weaks
1208 let mut rc = Self::new_uninit();
1210 let data = Rc::get_mut_unchecked(&mut rc);
1211 data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
1213 this.inner().dec_strong();
1214 // Remove implicit strong-weak ref (no need to craft a fake
1215 // Weak here -- we know other Weaks can clean up for us)
1216 this.inner().dec_weak();
1217 ptr::write(this, rc.assume_init());
1220 // This unsafety is ok because we're guaranteed that the pointer
1221 // returned is the *only* pointer that will ever be returned to T. Our
1222 // reference count is guaranteed to be 1 at this point, and we required
1223 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1224 // reference to the allocation.
1225 unsafe { &mut this.ptr.as_mut().value }
1228 /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1231 /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
1232 /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
1237 /// #![feature(arc_unwrap_or_clone)]
1238 /// # use std::{ptr, rc::Rc};
1239 /// let inner = String::from("test");
1240 /// let ptr = inner.as_ptr();
1242 /// let rc = Rc::new(inner);
1243 /// let inner = Rc::unwrap_or_clone(rc);
1244 /// // The inner value was not cloned
1245 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1247 /// let rc = Rc::new(inner);
1248 /// let rc2 = rc.clone();
1249 /// let inner = Rc::unwrap_or_clone(rc);
1250 /// // Because there were 2 references, we had to clone the inner value.
1251 /// assert!(!ptr::eq(ptr, inner.as_ptr()));
1252 /// // `rc2` is the last reference, so when we unwrap it we get back
1253 /// // the original `String`.
1254 /// let inner = Rc::unwrap_or_clone(rc2);
1255 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1258 #[unstable(feature = "arc_unwrap_or_clone", issue = "93610")]
1259 pub fn unwrap_or_clone(this: Self) -> T {
1260 Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
1265 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
1270 /// use std::any::Any;
1271 /// use std::rc::Rc;
1273 /// fn print_if_string(value: Rc<dyn Any>) {
1274 /// if let Ok(string) = value.downcast::<String>() {
1275 /// println!("String ({}): {}", string.len(), string);
1279 /// let my_string = "Hello World".to_string();
1280 /// print_if_string(Rc::new(my_string));
1281 /// print_if_string(Rc::new(0i8));
1284 #[stable(feature = "rc_downcast", since = "1.29.0")]
1285 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
1286 if (*self).is::<T>() {
1288 let ptr = self.ptr.cast::<RcBox<T>>();
1290 Ok(Rc::from_inner(ptr))
1297 /// Downcasts the `Rc<dyn Any>` to a concrete type.
1299 /// For a safe alternative see [`downcast`].
1304 /// #![feature(downcast_unchecked)]
1306 /// use std::any::Any;
1307 /// use std::rc::Rc;
1309 /// let x: Rc<dyn Any> = Rc::new(1_usize);
1312 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1318 /// The contained value must be of type `T`. Calling this method
1319 /// with the incorrect type is *undefined behavior*.
1322 /// [`downcast`]: Self::downcast
1324 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1325 pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T> {
1327 let ptr = self.ptr.cast::<RcBox<T>>();
1334 impl<T: ?Sized> Rc<T> {
1335 /// Allocates an `RcBox<T>` with sufficient space for
1336 /// a possibly-unsized inner value where the value has the layout provided.
1338 /// The function `mem_to_rcbox` is called with the data pointer
1339 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1340 #[cfg(not(no_global_oom_handling))]
1341 unsafe fn allocate_for_layout(
1342 value_layout: Layout,
1343 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1344 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1345 ) -> *mut RcBox<T> {
1346 let layout = rcbox_layout_for_value_layout(value_layout);
1348 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox)
1349 .unwrap_or_else(|_| handle_alloc_error(layout))
1353 /// Allocates an `RcBox<T>` with sufficient space for
1354 /// a possibly-unsized inner value where the value has the layout provided,
1355 /// returning an error if allocation fails.
1357 /// The function `mem_to_rcbox` is called with the data pointer
1358 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1360 unsafe fn try_allocate_for_layout(
1361 value_layout: Layout,
1362 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1363 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1364 ) -> Result<*mut RcBox<T>, AllocError> {
1365 let layout = rcbox_layout_for_value_layout(value_layout);
1367 // Allocate for the layout.
1368 let ptr = allocate(layout)?;
1370 // Initialize the RcBox
1371 let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr());
1373 debug_assert_eq!(Layout::for_value(&*inner), layout);
1375 ptr::write(&mut (*inner).strong, Cell::new(1));
1376 ptr::write(&mut (*inner).weak, Cell::new(1));
1382 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
1383 #[cfg(not(no_global_oom_handling))]
1384 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
1385 // Allocate for the `RcBox<T>` using the given value.
1387 Self::allocate_for_layout(
1388 Layout::for_value(&*ptr),
1389 |layout| Global.allocate(layout),
1390 |mem| mem.with_metadata_of(ptr as *const RcBox<T>),
1395 #[cfg(not(no_global_oom_handling))]
1396 fn from_box(v: Box<T>) -> Rc<T> {
1398 let (box_unique, alloc) = Box::into_unique(v);
1399 let bptr = box_unique.as_ptr();
1401 let value_size = size_of_val(&*bptr);
1402 let ptr = Self::allocate_for_ptr(bptr);
1404 // Copy value as bytes
1405 ptr::copy_nonoverlapping(
1406 bptr as *const T as *const u8,
1407 &mut (*ptr).value as *mut _ as *mut u8,
1411 // Free the allocation without dropping its contents
1412 box_free(box_unique, alloc);
1420 /// Allocates an `RcBox<[T]>` with the given length.
1421 #[cfg(not(no_global_oom_handling))]
1422 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1424 Self::allocate_for_layout(
1425 Layout::array::<T>(len).unwrap(),
1426 |layout| Global.allocate(layout),
1427 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
1432 /// Copy elements from slice into newly allocated `Rc<[T]>`
1434 /// Unsafe because the caller must either take ownership or bind `T: Copy`
1435 #[cfg(not(no_global_oom_handling))]
1436 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1438 let ptr = Self::allocate_for_slice(v.len());
1439 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1444 /// Create an `Rc<[T]>` by reusing the underlying memory
1445 /// of a `Vec<T>`. This will return the vector if the existing allocation
1446 /// is not large enough.
1447 #[cfg(not(no_global_oom_handling))]
1448 fn try_from_vec_in_place(mut v: Vec<T>) -> Result<Rc<[T]>, Vec<T>> {
1449 let layout_elements = Layout::array::<T>(v.len()).unwrap();
1450 let layout_allocation = Layout::array::<T>(v.capacity()).unwrap();
1451 let layout_rcbox = rcbox_layout_for_value_layout(layout_elements);
1452 let mut ptr = NonNull::new(v.as_mut_ptr()).expect("`Vec<T>` stores `NonNull<T>`");
1453 if layout_rcbox.size() > layout_allocation.size()
1454 || layout_rcbox.align() > layout_allocation.align()
1456 // Can't fit - calling `grow` would involve `realloc`
1457 // (which copies the elements), followed by copying again.
1460 if layout_rcbox.size() < layout_allocation.size()
1461 || layout_rcbox.align() < layout_allocation.align()
1463 // We need to shrink the allocation so that it fits
1464 // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting
1466 // - Vec allocates by requesting `Layout::array::<T>(capacity)`, so this capacity matches
1467 // - `layout_rcbox` is smaller
1468 // If this fails, the ownership has not been transferred
1469 if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_rcbox) } {
1475 // Make sure the vec's memory isn't deallocated now
1476 let v = mem::ManuallyDrop::new(v);
1477 let ptr: *mut RcBox<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _;
1479 ptr::copy(ptr.cast::<T>(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1480 ptr::write(&mut (*ptr).strong, Cell::new(1));
1481 ptr::write(&mut (*ptr).weak, Cell::new(1));
1482 Ok(Self::from_ptr(ptr))
1486 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1488 /// Behavior is undefined should the size be wrong.
1489 #[cfg(not(no_global_oom_handling))]
1490 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1491 // Panic guard while cloning T elements.
1492 // In the event of a panic, elements that have been written
1493 // into the new RcBox will be dropped, then the memory freed.
1501 impl<T> Drop for Guard<T> {
1502 fn drop(&mut self) {
1504 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1505 ptr::drop_in_place(slice);
1507 Global.deallocate(self.mem, self.layout);
1513 let ptr = Self::allocate_for_slice(len);
1515 let mem = ptr as *mut _ as *mut u8;
1516 let layout = Layout::for_value(&*ptr);
1518 // Pointer to first element
1519 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1521 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1523 for (i, item) in iter.enumerate() {
1524 ptr::write(elems.add(i), item);
1528 // All clear. Forget the guard so it doesn't free the new RcBox.
1536 /// Specialization trait used for `From<&[T]>`.
1537 trait RcFromSlice<T> {
1538 fn from_slice(slice: &[T]) -> Self;
1541 #[cfg(not(no_global_oom_handling))]
1542 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1544 default fn from_slice(v: &[T]) -> Self {
1545 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1549 #[cfg(not(no_global_oom_handling))]
1550 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1552 fn from_slice(v: &[T]) -> Self {
1553 unsafe { Rc::copy_from_slice(v) }
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<T: ?Sized> Deref for Rc<T> {
1562 fn deref(&self) -> &T {
1567 #[unstable(feature = "receiver_trait", issue = "none")]
1568 impl<T: ?Sized> Receiver for Rc<T> {}
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1574 /// This will decrement the strong reference count. If the strong reference
1575 /// count reaches zero then the only other references (if any) are
1576 /// [`Weak`], so we `drop` the inner value.
1581 /// use std::rc::Rc;
1585 /// impl Drop for Foo {
1586 /// fn drop(&mut self) {
1587 /// println!("dropped!");
1591 /// let foo = Rc::new(Foo);
1592 /// let foo2 = Rc::clone(&foo);
1594 /// drop(foo); // Doesn't print anything
1595 /// drop(foo2); // Prints "dropped!"
1597 fn drop(&mut self) {
1599 self.inner().dec_strong();
1600 if self.inner().strong() == 0 {
1601 // destroy the contained object
1602 ptr::drop_in_place(Self::get_mut_unchecked(self));
1604 // remove the implicit "strong weak" pointer now that we've
1605 // destroyed the contents.
1606 self.inner().dec_weak();
1608 if self.inner().weak() == 0 {
1609 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<T: ?Sized> Clone for Rc<T> {
1618 /// Makes a clone of the `Rc` pointer.
1620 /// This creates another pointer to the same allocation, increasing the
1621 /// strong reference count.
1626 /// use std::rc::Rc;
1628 /// let five = Rc::new(5);
1630 /// let _ = Rc::clone(&five);
1633 fn clone(&self) -> Rc<T> {
1635 self.inner().inc_strong();
1636 Self::from_inner(self.ptr)
1641 #[cfg(not(no_global_oom_handling))]
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 impl<T: Default> Default for Rc<T> {
1644 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1649 /// use std::rc::Rc;
1651 /// let x: Rc<i32> = Default::default();
1652 /// assert_eq!(*x, 0);
1655 fn default() -> Rc<T> {
1656 Rc::new(Default::default())
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 trait RcEqIdent<T: ?Sized + PartialEq> {
1662 fn eq(&self, other: &Rc<T>) -> bool;
1663 fn ne(&self, other: &Rc<T>) -> bool;
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1669 default fn eq(&self, other: &Rc<T>) -> bool {
1674 default fn ne(&self, other: &Rc<T>) -> bool {
1679 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1680 #[rustc_unsafe_specialization_marker]
1681 pub(crate) trait MarkerEq: PartialEq<Self> {}
1683 impl<T: Eq> MarkerEq for T {}
1685 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1686 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1687 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1688 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1689 /// the same value, than two `&T`s.
1691 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1695 fn eq(&self, other: &Rc<T>) -> bool {
1696 Rc::ptr_eq(self, other) || **self == **other
1700 fn ne(&self, other: &Rc<T>) -> bool {
1701 !Rc::ptr_eq(self, other) && **self != **other
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1707 /// Equality for two `Rc`s.
1709 /// Two `Rc`s are equal if their inner values are equal, even if they are
1710 /// stored in different allocation.
1712 /// If `T` also implements `Eq` (implying reflexivity of equality),
1713 /// two `Rc`s that point to the same allocation are
1719 /// use std::rc::Rc;
1721 /// let five = Rc::new(5);
1723 /// assert!(five == Rc::new(5));
1726 fn eq(&self, other: &Rc<T>) -> bool {
1727 RcEqIdent::eq(self, other)
1730 /// Inequality for two `Rc`s.
1732 /// Two `Rc`s are unequal if their inner values are unequal.
1734 /// If `T` also implements `Eq` (implying reflexivity of equality),
1735 /// two `Rc`s that point to the same allocation are
1741 /// use std::rc::Rc;
1743 /// let five = Rc::new(5);
1745 /// assert!(five != Rc::new(6));
1748 fn ne(&self, other: &Rc<T>) -> bool {
1749 RcEqIdent::ne(self, other)
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1758 /// Partial comparison for two `Rc`s.
1760 /// The two are compared by calling `partial_cmp()` on their inner values.
1765 /// use std::rc::Rc;
1766 /// use std::cmp::Ordering;
1768 /// let five = Rc::new(5);
1770 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1773 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1774 (**self).partial_cmp(&**other)
1777 /// Less-than comparison for two `Rc`s.
1779 /// The two are compared by calling `<` on their inner values.
1784 /// use std::rc::Rc;
1786 /// let five = Rc::new(5);
1788 /// assert!(five < Rc::new(6));
1791 fn lt(&self, other: &Rc<T>) -> bool {
1795 /// 'Less than or equal to' comparison for two `Rc`s.
1797 /// The two are compared by calling `<=` on their inner values.
1802 /// use std::rc::Rc;
1804 /// let five = Rc::new(5);
1806 /// assert!(five <= Rc::new(5));
1809 fn le(&self, other: &Rc<T>) -> bool {
1813 /// Greater-than comparison for two `Rc`s.
1815 /// The two are compared by calling `>` on their inner values.
1820 /// use std::rc::Rc;
1822 /// let five = Rc::new(5);
1824 /// assert!(five > Rc::new(4));
1827 fn gt(&self, other: &Rc<T>) -> bool {
1831 /// 'Greater than or equal to' comparison for two `Rc`s.
1833 /// The two are compared by calling `>=` on their inner values.
1838 /// use std::rc::Rc;
1840 /// let five = Rc::new(5);
1842 /// assert!(five >= Rc::new(5));
1845 fn ge(&self, other: &Rc<T>) -> bool {
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 impl<T: ?Sized + Ord> Ord for Rc<T> {
1852 /// Comparison for two `Rc`s.
1854 /// The two are compared by calling `cmp()` on their inner values.
1859 /// use std::rc::Rc;
1860 /// use std::cmp::Ordering;
1862 /// let five = Rc::new(5);
1864 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1867 fn cmp(&self, other: &Rc<T>) -> Ordering {
1868 (**self).cmp(&**other)
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 impl<T: ?Sized + Hash> Hash for Rc<T> {
1874 fn hash<H: Hasher>(&self, state: &mut H) {
1875 (**self).hash(state);
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882 fmt::Display::fmt(&**self, f)
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1889 fmt::Debug::fmt(&**self, f)
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1895 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1896 fmt::Pointer::fmt(&(&**self as *const T), f)
1900 #[cfg(not(no_global_oom_handling))]
1901 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1902 impl<T> From<T> for Rc<T> {
1903 /// Converts a generic type `T` into an `Rc<T>`
1905 /// The conversion allocates on the heap and moves `t`
1906 /// from the stack into it.
1910 /// # use std::rc::Rc;
1912 /// let rc = Rc::new(5);
1914 /// assert_eq!(Rc::from(x), rc);
1916 fn from(t: T) -> Self {
1921 #[cfg(not(no_global_oom_handling))]
1922 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1923 impl<T: Clone> From<&[T]> for Rc<[T]> {
1924 /// Allocate a reference-counted slice and fill it by cloning `v`'s items.
1929 /// # use std::rc::Rc;
1930 /// let original: &[i32] = &[1, 2, 3];
1931 /// let shared: Rc<[i32]> = Rc::from(original);
1932 /// assert_eq!(&[1, 2, 3], &shared[..]);
1935 fn from(v: &[T]) -> Rc<[T]> {
1936 <Self as RcFromSlice<T>>::from_slice(v)
1940 #[cfg(not(no_global_oom_handling))]
1941 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1942 impl From<&str> for Rc<str> {
1943 /// Allocate a reference-counted string slice and copy `v` into it.
1948 /// # use std::rc::Rc;
1949 /// let shared: Rc<str> = Rc::from("statue");
1950 /// assert_eq!("statue", &shared[..]);
1953 fn from(v: &str) -> Rc<str> {
1954 let rc = Rc::<[u8]>::from(v.as_bytes());
1955 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1959 #[cfg(not(no_global_oom_handling))]
1960 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1961 impl From<String> for Rc<str> {
1962 /// Allocate a reference-counted string slice and copy `v` into it.
1967 /// # use std::rc::Rc;
1968 /// let original: String = "statue".to_owned();
1969 /// let shared: Rc<str> = Rc::from(original);
1970 /// assert_eq!("statue", &shared[..]);
1973 fn from(v: String) -> Rc<str> {
1978 #[cfg(not(no_global_oom_handling))]
1979 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1980 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1981 /// Move a boxed object to a new, reference counted, allocation.
1986 /// # use std::rc::Rc;
1987 /// let original: Box<i32> = Box::new(1);
1988 /// let shared: Rc<i32> = Rc::from(original);
1989 /// assert_eq!(1, *shared);
1992 fn from(v: Box<T>) -> Rc<T> {
1997 #[cfg(not(no_global_oom_handling))]
1998 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1999 impl<T> From<Vec<T>> for Rc<[T]> {
2000 /// Allocate a reference-counted slice and move `v`'s items into it.
2005 /// # use std::rc::Rc;
2006 /// let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
2007 /// let shared: Rc<Vec<i32>> = Rc::from(original);
2008 /// assert_eq!(vec![1, 2, 3], *shared);
2011 fn from(v: Vec<T>) -> Rc<[T]> {
2012 match Rc::try_from_vec_in_place(v) {
2016 let rc = Rc::copy_from_slice(&v);
2017 // Allow the Vec to free its memory, but not destroy its contents
2026 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2027 impl<'a, B> From<Cow<'a, B>> for Rc<B>
2029 B: ToOwned + ?Sized,
2030 Rc<B>: From<&'a B> + From<B::Owned>,
2032 /// Create a reference-counted pointer from
2033 /// a clone-on-write pointer by copying its content.
2038 /// # use std::rc::Rc;
2039 /// # use std::borrow::Cow;
2040 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
2041 /// let shared: Rc<str> = Rc::from(cow);
2042 /// assert_eq!("eggplant", &shared[..]);
2045 fn from(cow: Cow<'a, B>) -> Rc<B> {
2047 Cow::Borrowed(s) => Rc::from(s),
2048 Cow::Owned(s) => Rc::from(s),
2053 #[stable(feature = "shared_from_str", since = "1.62.0")]
2054 impl From<Rc<str>> for Rc<[u8]> {
2055 /// Converts a reference-counted string slice into a byte slice.
2060 /// # use std::rc::Rc;
2061 /// let string: Rc<str> = Rc::from("eggplant");
2062 /// let bytes: Rc<[u8]> = Rc::from(string);
2063 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
2066 fn from(rc: Rc<str>) -> Self {
2067 // SAFETY: `str` has the same layout as `[u8]`.
2068 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
2072 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2073 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
2074 type Error = Rc<[T]>;
2076 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
2077 if boxed_slice.len() == N {
2078 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
2085 #[cfg(not(no_global_oom_handling))]
2086 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2087 impl<T> iter::FromIterator<T> for Rc<[T]> {
2088 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
2090 /// # Performance characteristics
2092 /// ## The general case
2094 /// In the general case, collecting into `Rc<[T]>` is done by first
2095 /// collecting into a `Vec<T>`. That is, when writing the following:
2098 /// # use std::rc::Rc;
2099 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2100 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2103 /// this behaves as if we wrote:
2106 /// # use std::rc::Rc;
2107 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2108 /// .collect::<Vec<_>>() // The first set of allocations happens here.
2109 /// .into(); // A second allocation for `Rc<[T]>` happens here.
2110 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2113 /// This will allocate as many times as needed for constructing the `Vec<T>`
2114 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
2116 /// ## Iterators of known length
2118 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2119 /// a single allocation will be made for the `Rc<[T]>`. For example:
2122 /// # use std::rc::Rc;
2123 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2124 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2126 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
2127 ToRcSlice::to_rc_slice(iter.into_iter())
2131 /// Specialization trait used for collecting into `Rc<[T]>`.
2132 #[cfg(not(no_global_oom_handling))]
2133 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
2134 fn to_rc_slice(self) -> Rc<[T]>;
2137 #[cfg(not(no_global_oom_handling))]
2138 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
2139 default fn to_rc_slice(self) -> Rc<[T]> {
2140 self.collect::<Vec<T>>().into()
2144 #[cfg(not(no_global_oom_handling))]
2145 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
2146 fn to_rc_slice(self) -> Rc<[T]> {
2147 // This is the case for a `TrustedLen` iterator.
2148 let (low, high) = self.size_hint();
2149 if let Some(high) = high {
2153 "TrustedLen iterator's size hint is not exact: {:?}",
2158 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2159 Rc::from_iter_exact(self, low)
2162 // TrustedLen contract guarantees that `upper_bound == `None` implies an iterator
2163 // length exceeding `usize::MAX`.
2164 // The default implementation would collect into a vec which would panic.
2165 // Thus we panic here immediately without invoking `Vec` code.
2166 panic!("capacity overflow");
2171 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
2172 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
2173 /// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
2175 /// Since a `Weak` reference does not count towards ownership, it will not
2176 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
2177 /// guarantees about the value still being present. Thus it may return [`None`]
2178 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
2179 /// itself (the backing store) from being deallocated.
2181 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
2182 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2183 /// prevent circular references between [`Rc`] pointers, since mutual owning references
2184 /// would never allow either [`Rc`] to be dropped. For example, a tree could
2185 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2186 /// pointers from children back to their parents.
2188 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2190 /// [`upgrade`]: Weak::upgrade
2191 #[stable(feature = "rc_weak", since = "1.4.0")]
2192 pub struct Weak<T: ?Sized> {
2193 // This is a `NonNull` to allow optimizing the size of this type in enums,
2194 // but it is not necessarily a valid pointer.
2195 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
2196 // to allocate space on the heap. That's not a value a real pointer
2197 // will ever have because RcBox has alignment at least 2.
2198 // This is only possible when `T: Sized`; unsized `T` never dangle.
2199 ptr: NonNull<RcBox<T>>,
2202 #[stable(feature = "rc_weak", since = "1.4.0")]
2203 impl<T: ?Sized> !marker::Send for Weak<T> {}
2204 #[stable(feature = "rc_weak", since = "1.4.0")]
2205 impl<T: ?Sized> !marker::Sync for Weak<T> {}
2207 #[unstable(feature = "coerce_unsized", issue = "27732")]
2208 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
2210 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2211 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
2214 /// Constructs a new `Weak<T>`, without allocating any memory.
2215 /// Calling [`upgrade`] on the return value always gives [`None`].
2217 /// [`upgrade`]: Weak::upgrade
2222 /// use std::rc::Weak;
2224 /// let empty: Weak<i64> = Weak::new();
2225 /// assert!(empty.upgrade().is_none());
2227 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2228 #[rustc_const_unstable(feature = "const_weak_new", issue = "95091", reason = "recently added")]
2230 pub const fn new() -> Weak<T> {
2231 Weak { ptr: unsafe { NonNull::new_unchecked(ptr::invalid_mut::<RcBox<T>>(usize::MAX)) } }
2235 pub(crate) fn is_dangling<T: ?Sized>(ptr: *mut T) -> bool {
2236 (ptr as *mut ()).addr() == usize::MAX
2239 /// Helper type to allow accessing the reference counts without
2240 /// making any assertions about the data field.
2241 struct WeakInner<'a> {
2242 weak: &'a Cell<usize>,
2243 strong: &'a Cell<usize>,
2246 impl<T: ?Sized> Weak<T> {
2247 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
2249 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
2250 /// unaligned or even [`null`] otherwise.
2255 /// use std::rc::Rc;
2258 /// let strong = Rc::new("hello".to_owned());
2259 /// let weak = Rc::downgrade(&strong);
2260 /// // Both point to the same object
2261 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
2262 /// // The strong here keeps it alive, so we can still access the object.
2263 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
2266 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
2267 /// // undefined behaviour.
2268 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
2271 /// [`null`]: ptr::null
2273 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
2274 pub fn as_ptr(&self) -> *const T {
2275 let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
2277 if is_dangling(ptr) {
2278 // If the pointer is dangling, we return the sentinel directly. This cannot be
2279 // a valid payload address, as the payload is at least as aligned as RcBox (usize).
2282 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
2283 // The payload may be dropped at this point, and we have to maintain provenance,
2284 // so use raw pointer manipulation.
2285 unsafe { ptr::addr_of_mut!((*ptr).value) }
2289 /// Consumes the `Weak<T>` and turns it into a raw pointer.
2291 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
2292 /// one weak reference (the weak count is not modified by this operation). It can be turned
2293 /// back into the `Weak<T>` with [`from_raw`].
2295 /// The same restrictions of accessing the target of the pointer as with
2296 /// [`as_ptr`] apply.
2301 /// use std::rc::{Rc, Weak};
2303 /// let strong = Rc::new("hello".to_owned());
2304 /// let weak = Rc::downgrade(&strong);
2305 /// let raw = weak.into_raw();
2307 /// assert_eq!(1, Rc::weak_count(&strong));
2308 /// assert_eq!("hello", unsafe { &*raw });
2310 /// drop(unsafe { Weak::from_raw(raw) });
2311 /// assert_eq!(0, Rc::weak_count(&strong));
2314 /// [`from_raw`]: Weak::from_raw
2315 /// [`as_ptr`]: Weak::as_ptr
2316 #[must_use = "`self` will be dropped if the result is not used"]
2317 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2318 pub fn into_raw(self) -> *const T {
2319 let result = self.as_ptr();
2324 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
2326 /// This can be used to safely get a strong reference (by calling [`upgrade`]
2327 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
2329 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
2330 /// as these don't own anything; the method still works on them).
2334 /// The pointer must have originated from the [`into_raw`] and must still own its potential
2337 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
2338 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
2339 /// count is not modified by this operation) and therefore it must be paired with a previous
2340 /// call to [`into_raw`].
2345 /// use std::rc::{Rc, Weak};
2347 /// let strong = Rc::new("hello".to_owned());
2349 /// let raw_1 = Rc::downgrade(&strong).into_raw();
2350 /// let raw_2 = Rc::downgrade(&strong).into_raw();
2352 /// assert_eq!(2, Rc::weak_count(&strong));
2354 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
2355 /// assert_eq!(1, Rc::weak_count(&strong));
2359 /// // Decrement the last weak count.
2360 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
2363 /// [`into_raw`]: Weak::into_raw
2364 /// [`upgrade`]: Weak::upgrade
2365 /// [`new`]: Weak::new
2366 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2367 pub unsafe fn from_raw(ptr: *const T) -> Self {
2368 // See Weak::as_ptr for context on how the input pointer is derived.
2370 let ptr = if is_dangling(ptr as *mut T) {
2371 // This is a dangling Weak.
2372 ptr as *mut RcBox<T>
2374 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
2375 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
2376 let offset = unsafe { data_offset(ptr) };
2377 // Thus, we reverse the offset to get the whole RcBox.
2378 // SAFETY: the pointer originated from a Weak, so this offset is safe.
2379 unsafe { ptr.byte_sub(offset) as *mut RcBox<T> }
2382 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
2383 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } }
2386 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
2387 /// dropping of the inner value if successful.
2389 /// Returns [`None`] if the inner value has since been dropped.
2394 /// use std::rc::Rc;
2396 /// let five = Rc::new(5);
2398 /// let weak_five = Rc::downgrade(&five);
2400 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
2401 /// assert!(strong_five.is_some());
2403 /// // Destroy all strong pointers.
2404 /// drop(strong_five);
2407 /// assert!(weak_five.upgrade().is_none());
2409 #[must_use = "this returns a new `Rc`, \
2410 without modifying the original weak pointer"]
2411 #[stable(feature = "rc_weak", since = "1.4.0")]
2412 pub fn upgrade(&self) -> Option<Rc<T>> {
2413 let inner = self.inner()?;
2415 if inner.strong() == 0 {
2420 Some(Rc::from_inner(self.ptr))
2425 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
2427 /// If `self` was created using [`Weak::new`], this will return 0.
2429 #[stable(feature = "weak_counts", since = "1.41.0")]
2430 pub fn strong_count(&self) -> usize {
2431 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
2434 /// Gets the number of `Weak` pointers pointing to this allocation.
2436 /// If no strong pointers remain, this will return zero.
2438 #[stable(feature = "weak_counts", since = "1.41.0")]
2439 pub fn weak_count(&self) -> usize {
2442 if inner.strong() > 0 {
2443 inner.weak() - 1 // subtract the implicit weak ptr
2451 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`,
2452 /// (i.e., when this `Weak` was created by `Weak::new`).
2454 fn inner(&self) -> Option<WeakInner<'_>> {
2455 if is_dangling(self.ptr.as_ptr()) {
2458 // We are careful to *not* create a reference covering the "data" field, as
2459 // the field may be mutated concurrently (for example, if the last `Rc`
2460 // is dropped, the data field will be dropped in-place).
2462 let ptr = self.ptr.as_ptr();
2463 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
2468 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
2469 /// both don't point to any allocation (because they were created with `Weak::new()`). See [that
2470 /// function][`ptr::eq`] for caveats when comparing `dyn Trait` pointers.
2474 /// Since this compares pointers it means that `Weak::new()` will equal each
2475 /// other, even though they don't point to any allocation.
2480 /// use std::rc::Rc;
2482 /// let first_rc = Rc::new(5);
2483 /// let first = Rc::downgrade(&first_rc);
2484 /// let second = Rc::downgrade(&first_rc);
2486 /// assert!(first.ptr_eq(&second));
2488 /// let third_rc = Rc::new(5);
2489 /// let third = Rc::downgrade(&third_rc);
2491 /// assert!(!first.ptr_eq(&third));
2494 /// Comparing `Weak::new`.
2497 /// use std::rc::{Rc, Weak};
2499 /// let first = Weak::new();
2500 /// let second = Weak::new();
2501 /// assert!(first.ptr_eq(&second));
2503 /// let third_rc = Rc::new(());
2504 /// let third = Rc::downgrade(&third_rc);
2505 /// assert!(!first.ptr_eq(&third));
2509 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
2510 pub fn ptr_eq(&self, other: &Self) -> bool {
2511 self.ptr.as_ptr() == other.ptr.as_ptr()
2515 #[stable(feature = "rc_weak", since = "1.4.0")]
2516 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
2517 /// Drops the `Weak` pointer.
2522 /// use std::rc::{Rc, Weak};
2526 /// impl Drop for Foo {
2527 /// fn drop(&mut self) {
2528 /// println!("dropped!");
2532 /// let foo = Rc::new(Foo);
2533 /// let weak_foo = Rc::downgrade(&foo);
2534 /// let other_weak_foo = Weak::clone(&weak_foo);
2536 /// drop(weak_foo); // Doesn't print anything
2537 /// drop(foo); // Prints "dropped!"
2539 /// assert!(other_weak_foo.upgrade().is_none());
2541 fn drop(&mut self) {
2542 let inner = if let Some(inner) = self.inner() { inner } else { return };
2545 // the weak count starts at 1, and will only go to zero if all
2546 // the strong pointers have disappeared.
2547 if inner.weak() == 0 {
2549 Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
2555 #[stable(feature = "rc_weak", since = "1.4.0")]
2556 impl<T: ?Sized> Clone for Weak<T> {
2557 /// Makes a clone of the `Weak` pointer that points to the same allocation.
2562 /// use std::rc::{Rc, Weak};
2564 /// let weak_five = Rc::downgrade(&Rc::new(5));
2566 /// let _ = Weak::clone(&weak_five);
2569 fn clone(&self) -> Weak<T> {
2570 if let Some(inner) = self.inner() {
2573 Weak { ptr: self.ptr }
2577 #[stable(feature = "rc_weak", since = "1.4.0")]
2578 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
2579 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2584 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2585 impl<T> Default for Weak<T> {
2586 /// Constructs a new `Weak<T>`, without allocating any memory.
2587 /// Calling [`upgrade`] on the return value always gives [`None`].
2589 /// [`upgrade`]: Weak::upgrade
2594 /// use std::rc::Weak;
2596 /// let empty: Weak<i64> = Default::default();
2597 /// assert!(empty.upgrade().is_none());
2599 fn default() -> Weak<T> {
2604 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2605 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2606 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2607 // We abort because this is such a degenerate scenario that we don't care about
2608 // what happens -- no real program should ever experience this.
2610 // This should have negligible overhead since you don't actually need to
2611 // clone these much in Rust thanks to ownership and move-semantics.
2615 fn weak_ref(&self) -> &Cell<usize>;
2616 fn strong_ref(&self) -> &Cell<usize>;
2619 fn strong(&self) -> usize {
2620 self.strong_ref().get()
2624 fn inc_strong(&self) {
2625 let strong = self.strong();
2627 // We insert an `assume` here to hint LLVM at an otherwise
2628 // missed optimization.
2629 // SAFETY: The reference count will never be zero when this is
2632 core::intrinsics::assume(strong != 0);
2635 let strong = strong.wrapping_add(1);
2636 self.strong_ref().set(strong);
2638 // We want to abort on overflow instead of dropping the value.
2639 // Checking for overflow after the store instead of before
2640 // allows for slightly better code generation.
2641 if core::intrinsics::unlikely(strong == 0) {
2647 fn dec_strong(&self) {
2648 self.strong_ref().set(self.strong() - 1);
2652 fn weak(&self) -> usize {
2653 self.weak_ref().get()
2657 fn inc_weak(&self) {
2658 let weak = self.weak();
2660 // We insert an `assume` here to hint LLVM at an otherwise
2661 // missed optimization.
2662 // SAFETY: The reference count will never be zero when this is
2665 core::intrinsics::assume(weak != 0);
2668 let weak = weak.wrapping_add(1);
2669 self.weak_ref().set(weak);
2671 // We want to abort on overflow instead of dropping the value.
2672 // Checking for overflow after the store instead of before
2673 // allows for slightly better code generation.
2674 if core::intrinsics::unlikely(weak == 0) {
2680 fn dec_weak(&self) {
2681 self.weak_ref().set(self.weak() - 1);
2685 impl<T: ?Sized> RcInnerPtr for RcBox<T> {
2687 fn weak_ref(&self) -> &Cell<usize> {
2692 fn strong_ref(&self) -> &Cell<usize> {
2697 impl<'a> RcInnerPtr for WeakInner<'a> {
2699 fn weak_ref(&self) -> &Cell<usize> {
2704 fn strong_ref(&self) -> &Cell<usize> {
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2711 fn borrow(&self) -> &T {
2716 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2717 impl<T: ?Sized> AsRef<T> for Rc<T> {
2718 fn as_ref(&self) -> &T {
2723 #[stable(feature = "pin", since = "1.33.0")]
2724 impl<T: ?Sized> Unpin for Rc<T> {}
2726 /// Get the offset within an `RcBox` for the payload behind a pointer.
2730 /// The pointer must point to (and have valid metadata for) a previously
2731 /// valid instance of T, but the T is allowed to be dropped.
2732 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
2733 // Align the unsized value to the end of the RcBox.
2734 // Because RcBox is repr(C), it will always be the last field in memory.
2735 // SAFETY: since the only unsized types possible are slices, trait objects,
2736 // and extern types, the input safety requirement is currently enough to
2737 // satisfy the requirements of align_of_val_raw; this is an implementation
2738 // detail of the language that must not be relied upon outside of std.
2739 unsafe { data_offset_align(align_of_val_raw(ptr)) }
2743 fn data_offset_align(align: usize) -> usize {
2744 let layout = Layout::new::<RcBox<()>>();
2745 layout.size() + layout.padding_needed_for(align)