Skip to main content

alloc/
rc.rs

1//! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
2//! Counted'.
3//!
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.
9//!
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].
15//!
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`]. 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].
22//!
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.
29//!
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.
34//!
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]:
39//!
40//! ```
41//! use std::rc::Rc;
42//!
43//! let my_rc = Rc::new(());
44//! let my_weak = Rc::downgrade(&my_rc);
45//! ```
46//!
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.
50//!
51//! ```
52//! use std::rc::Rc;
53//!
54//! let rc = Rc::new(());
55//! // Method-call syntax
56//! let rc2 = rc.clone();
57//! // Fully qualified syntax
58//! let rc3 = Rc::clone(&rc);
59//! ```
60//!
61//! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
62//! already been dropped.
63//!
64//! # Cloning references
65//!
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`].
68//!
69//! ```
70//! use std::rc::Rc;
71//!
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.
77//! ```
78//!
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.
82//!
83//! # Examples
84//!
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.
90//!
91//! ```
92//! use std::rc::Rc;
93//!
94//! struct Owner {
95//!     name: String,
96//!     // ...other fields
97//! }
98//!
99//! struct Gadget {
100//!     id: i32,
101//!     owner: Rc<Owner>,
102//!     // ...other fields
103//! }
104//!
105//! fn main() {
106//!     // Create a reference-counted `Owner`.
107//!     let gadget_owner: Rc<Owner> = Rc::new(
108//!         Owner {
109//!             name: "Gadget Man".to_string(),
110//!         }
111//!     );
112//!
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 {
117//!         id: 1,
118//!         owner: Rc::clone(&gadget_owner),
119//!     };
120//!     let gadget2 = Gadget {
121//!         id: 2,
122//!         owner: Rc::clone(&gadget_owner),
123//!     };
124//!
125//!     // Dispose of our local variable `gadget_owner`.
126//!     drop(gadget_owner);
127//!
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);
136//!
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.
140//! }
141//! ```
142//!
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`]
148//! pointers.
149//!
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.
158//!
159//! ```
160//! use std::rc::Rc;
161//! use std::rc::Weak;
162//! use std::cell::RefCell;
163//!
164//! struct Owner {
165//!     name: String,
166//!     gadgets: RefCell<Vec<Weak<Gadget>>>,
167//!     // ...other fields
168//! }
169//!
170//! struct Gadget {
171//!     id: i32,
172//!     owner: Rc<Owner>,
173//!     // ...other fields
174//! }
175//!
176//! fn main() {
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(
181//!         Owner {
182//!             name: "Gadget Man".to_string(),
183//!             gadgets: RefCell::new(vec![]),
184//!         }
185//!     );
186//!
187//!     // Create `Gadget`s belonging to `gadget_owner`, as before.
188//!     let gadget1 = Rc::new(
189//!         Gadget {
190//!             id: 1,
191//!             owner: Rc::clone(&gadget_owner),
192//!         }
193//!     );
194//!     let gadget2 = Rc::new(
195//!         Gadget {
196//!             id: 2,
197//!             owner: Rc::clone(&gadget_owner),
198//!         }
199//!     );
200//!
201//!     // Add the `Gadget`s to their `Owner`.
202//!     {
203//!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
204//!         gadgets.push(Rc::downgrade(&gadget1));
205//!         gadgets.push(Rc::downgrade(&gadget2));
206//!
207//!         // `RefCell` dynamic borrow ends here.
208//!     }
209//!
210//!     // Iterate over our `Gadget`s, printing their details out.
211//!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
212//!
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>>`.
216//!         //
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.
220//!
221//!         let gadget = gadget_weak.upgrade().unwrap();
222//!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
223//!     }
224//!
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.
229//! }
230//! ```
231//!
232//! [clone]: Clone::clone
233//! [`Cell`]: core::cell::Cell
234//! [`RefCell`]: core::cell::RefCell
235//! [arc]: crate::sync::Arc
236//! [`Deref`]: core::ops::Deref
237//! [downgrade]: Rc::downgrade
238//! [upgrade]: Weak::upgrade
239//! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
240//! [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
241
242#![stable(feature = "rust1", since = "1.0.0")]
243
244use core::any::Any;
245use core::cell::{Cell, CloneFromCell};
246#[cfg(not(no_global_oom_handling))]
247use core::clone::TrivialClone;
248use core::clone::{CloneToUninit, Share, UseCloned};
249use core::cmp::Ordering;
250use core::hash::{Hash, Hasher};
251use core::intrinsics::abort;
252#[cfg(not(no_global_oom_handling))]
253use core::iter;
254use core::marker::{PhantomData, Unsize};
255use core::mem::{self, Alignment, ManuallyDrop};
256use core::num::NonZeroUsize;
257use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver};
258#[cfg(not(no_global_oom_handling))]
259use core::ops::{Residual, Try};
260use core::panic::{RefUnwindSafe, UnwindSafe};
261#[cfg(not(no_global_oom_handling))]
262use core::pin::Pin;
263use core::pin::PinSafePointer;
264use core::ptr::{self, NonNull, drop_in_place};
265#[cfg(not(no_global_oom_handling))]
266use core::slice::from_raw_parts_mut;
267use core::{borrow, fmt, hint};
268
269#[cfg(not(no_global_oom_handling))]
270use crate::alloc::handle_alloc_error;
271use crate::alloc::{AllocError, Allocator, AllocatorClone, Global, Layout};
272use crate::borrow::{Cow, ToOwned};
273use crate::boxed::Box;
274#[cfg(not(no_global_oom_handling))]
275use crate::string::String;
276#[cfg(not(no_global_oom_handling))]
277use crate::vec::Vec;
278
279// This is repr(C) to future-proof against possible field-reordering, which
280// would interfere with otherwise safe [into|from]_raw() of transmutable
281// inner types.
282// repr(align(2)) (forcing alignment to at least 2) is required because usize
283// has 1-byte alignment on AVR.
284#[repr(C, align(2))]
285struct RcInner<T: ?Sized> {
286    strong: Cell<usize>,
287    weak: Cell<usize>,
288    value: T,
289}
290
291/// Calculate layout for `RcInner<T>` using the inner value's layout
292fn rc_inner_layout_for_value_layout(layout: Layout) -> Layout {
293    // Calculate layout using the given value layout.
294    // Previously, layout was calculated on the expression
295    // `&*(ptr as *const RcInner<T>)`, but this created a misaligned
296    // reference (see #54908).
297    Layout::new::<RcInner<()>>()
298        .extend(layout)
299        .unwrap_or_else(|_| panic!("capacity overflow"))
300        .0
301        .pad_to_align()
302}
303
304/// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
305/// Counted'.
306///
307/// See the [module-level documentation](./index.html) for more details.
308///
309/// The inherent methods of `Rc` are all associated functions, which means
310/// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
311/// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
312///
313/// [get_mut]: Rc::get_mut
314#[doc(search_unbox)]
315#[rustc_diagnostic_item = "Rc"]
316#[stable(feature = "rust1", since = "1.0.0")]
317#[rustc_insignificant_dtor]
318#[diagnostic::on_move(
319    message = "the type `{Self}` does not implement `Copy`",
320    label = "this move could be avoided by cloning the original `{Self}`, which is inexpensive",
321    note = "consider using `Rc::clone`"
322)]
323
324pub struct Rc<
325    T: ?Sized,
326    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
327> {
328    ptr: NonNull<RcInner<T>>,
329    phantom: PhantomData<RcInner<T>>,
330    alloc: A,
331}
332
333#[stable(feature = "rust1", since = "1.0.0")]
334impl<T: ?Sized, A: Allocator> !Send for Rc<T, A> {}
335
336// Note that this negative impl isn't strictly necessary for correctness,
337// as `Rc` transitively contains a `Cell`, which is itself `!Sync`.
338// However, given how important `Rc`'s `!Sync`-ness is,
339// having an explicit negative impl is nice for documentation purposes
340// and results in nicer error messages.
341#[stable(feature = "rust1", since = "1.0.0")]
342impl<T: ?Sized, A: Allocator> !Sync for Rc<T, A> {}
343
344#[stable(feature = "catch_unwind", since = "1.9.0")]
345impl<T: RefUnwindSafe + ?Sized, A: Allocator + UnwindSafe + RefUnwindSafe> UnwindSafe for Rc<T, A> {}
346#[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")]
347impl<T: RefUnwindSafe + ?Sized, A: Allocator + UnwindSafe + RefUnwindSafe> RefUnwindSafe
348    for Rc<T, A>
349{
350}
351
352#[unstable(feature = "coerce_unsized", issue = "18598")]
353impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Rc<U, A>> for Rc<T, A> {}
354
355#[unstable(feature = "dispatch_from_dyn", issue = "none")]
356impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
357
358// SAFETY: `Rc::clone` doesn't access any `Cell`s which could contain the `Rc` being cloned.
359#[unstable(feature = "cell_get_cloned", issue = "145329")]
360unsafe impl<T: ?Sized> CloneFromCell for Rc<T> {}
361
362impl<T: ?Sized> Rc<T> {
363    #[inline]
364    unsafe fn from_inner(ptr: NonNull<RcInner<T>>) -> Self {
365        unsafe { Self::from_inner_in(ptr, Global) }
366    }
367
368    #[inline]
369    unsafe fn from_ptr(ptr: *mut RcInner<T>) -> Self {
370        unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
371    }
372}
373
374impl<T: ?Sized, A: Allocator> Rc<T, A> {
375    #[inline(always)]
376    fn inner(&self) -> &RcInner<T> {
377        // This unsafety is ok because while this Rc is alive we're guaranteed
378        // that the inner pointer is valid.
379        unsafe { self.ptr.as_ref() }
380    }
381
382    #[inline]
383    fn into_inner_with_allocator(this: Self) -> (NonNull<RcInner<T>>, A) {
384        let this = mem::ManuallyDrop::new(this);
385        (this.ptr, unsafe { ptr::read(&this.alloc) })
386    }
387
388    #[inline]
389    unsafe fn from_inner_in(ptr: NonNull<RcInner<T>>, alloc: A) -> Self {
390        Self { ptr, phantom: PhantomData, alloc }
391    }
392
393    #[inline]
394    unsafe fn from_ptr_in(ptr: *mut RcInner<T>, alloc: A) -> Self {
395        unsafe { Self::from_inner_in(NonNull::new_unchecked(ptr), alloc) }
396    }
397
398    // Non-inlined part of `drop`.
399    #[inline(never)]
400    unsafe fn drop_slow(&mut self) {
401        // Reconstruct the "strong weak" pointer and drop it when this
402        // variable goes out of scope. This ensures that the memory is
403        // deallocated even if the destructor of `T` panics.
404        let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };
405
406        // Destroy the contained object.
407        // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed.
408        unsafe {
409            ptr::drop_in_place(&mut (*self.ptr.as_ptr()).value);
410        }
411    }
412}
413
414impl<T> Rc<T> {
415    /// Constructs a new `Rc<T>`.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// use std::rc::Rc;
421    ///
422    /// let five = Rc::new(5);
423    /// ```
424    #[cfg(not(no_global_oom_handling))]
425    #[stable(feature = "rust1", since = "1.0.0")]
426    pub fn new(value: T) -> Rc<T> {
427        // There is an implicit weak pointer owned by all the strong
428        // pointers, which ensures that the weak destructor never frees
429        // the allocation while the strong destructor is running, even
430        // if the weak pointer is stored inside the strong one.
431        unsafe {
432            Self::from_inner(
433                Box::leak(Box::new(RcInner { strong: Cell::new(1), weak: Cell::new(1), value }))
434                    .into(),
435            )
436        }
437    }
438
439    /// Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation,
440    /// to allow you to construct a `T` which holds a weak pointer to itself.
441    ///
442    /// Generally, a structure circularly referencing itself, either directly or
443    /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
444    /// Using this function, you get access to the weak pointer during the
445    /// initialization of `T`, before the `Rc<T>` is created, such that you can
446    /// clone and store it inside the `T`.
447    ///
448    /// `new_cyclic` first allocates the managed allocation for the `Rc<T>`,
449    /// then calls your closure, giving it a `Weak<T>` to this allocation,
450    /// and only afterwards completes the construction of the `Rc<T>` by placing
451    /// the `T` returned from your closure into the allocation.
452    ///
453    /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
454    /// returns, calling [`upgrade`] on the weak reference inside your closure will
455    /// fail and result in a `None` value.
456    ///
457    /// # Panics
458    ///
459    /// If `data_fn` panics, the panic is propagated to the caller, and the
460    /// temporary [`Weak<T>`] is dropped normally.
461    ///
462    /// # Examples
463    ///
464    /// ```
465    /// # #![allow(dead_code)]
466    /// use std::rc::{Rc, Weak};
467    ///
468    /// struct Gadget {
469    ///     me: Weak<Gadget>,
470    /// }
471    ///
472    /// impl Gadget {
473    ///     /// Constructs a reference counted Gadget.
474    ///     fn new() -> Rc<Self> {
475    ///         // `me` is a `Weak<Gadget>` pointing at the new allocation of the
476    ///         // `Rc` we're constructing.
477    ///         Rc::new_cyclic(|me| {
478    ///             // Create the actual struct here.
479    ///             Gadget { me: me.clone() }
480    ///         })
481    ///     }
482    ///
483    ///     /// Returns a reference counted pointer to Self.
484    ///     fn me(&self) -> Rc<Self> {
485    ///         self.me.upgrade().unwrap()
486    ///     }
487    /// }
488    /// ```
489    /// [`upgrade`]: Weak::upgrade
490    #[cfg(not(no_global_oom_handling))]
491    #[stable(feature = "arc_new_cyclic", since = "1.60.0")]
492    pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
493    where
494        F: FnOnce(&Weak<T>) -> T,
495    {
496        Self::new_cyclic_in(data_fn, Global)
497    }
498
499    /// Constructs a new `Rc` with uninitialized contents.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use std::rc::Rc;
505    ///
506    /// let mut five = Rc::<u32>::new_uninit();
507    ///
508    /// // Deferred initialization:
509    /// Rc::get_mut(&mut five).unwrap().write(5);
510    ///
511    /// let five = unsafe { five.assume_init() };
512    ///
513    /// assert_eq!(*five, 5)
514    /// ```
515    #[cfg(not(no_global_oom_handling))]
516    #[stable(feature = "new_uninit", since = "1.82.0")]
517    #[must_use]
518    pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
519        unsafe {
520            Rc::from_ptr(Rc::allocate_for_layout(
521                Layout::new::<T>(),
522                |layout| Global.allocate(layout),
523                <*mut u8>::cast,
524            ))
525        }
526    }
527
528    /// Constructs a new `Rc` with uninitialized contents, with the memory
529    /// being filled with `0` bytes.
530    ///
531    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
532    /// incorrect usage of this method.
533    ///
534    /// # Examples
535    ///
536    /// ```
537    /// use std::rc::Rc;
538    ///
539    /// let zero = Rc::<u32>::new_zeroed();
540    /// let zero = unsafe { zero.assume_init() };
541    ///
542    /// assert_eq!(*zero, 0)
543    /// ```
544    ///
545    /// [zeroed]: mem::MaybeUninit::zeroed
546    #[cfg(not(no_global_oom_handling))]
547    #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
548    #[must_use]
549    pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
550        unsafe {
551            Rc::from_ptr(Rc::allocate_for_layout(
552                Layout::new::<T>(),
553                |layout| Global.allocate_zeroed(layout),
554                <*mut u8>::cast,
555            ))
556        }
557    }
558
559    /// Constructs a new `Rc<T>`, returning an error if the allocation fails
560    ///
561    /// # Examples
562    ///
563    /// ```
564    /// #![feature(allocator_api)]
565    /// use std::rc::Rc;
566    ///
567    /// let five = Rc::try_new(5);
568    /// # Ok::<(), std::alloc::AllocError>(())
569    /// ```
570    #[unstable(feature = "allocator_api", issue = "32838")]
571    pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
572        // There is an implicit weak pointer owned by all the strong
573        // pointers, which ensures that the weak destructor never frees
574        // the allocation while the strong destructor is running, even
575        // if the weak pointer is stored inside the strong one.
576        unsafe {
577            Ok(Self::from_inner(
578                Box::leak(Box::try_new(RcInner {
579                    strong: Cell::new(1),
580                    weak: Cell::new(1),
581                    value,
582                })?)
583                .into(),
584            ))
585        }
586    }
587
588    /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
589    ///
590    /// # Examples
591    ///
592    /// ```
593    /// #![feature(allocator_api)]
594    ///
595    /// use std::rc::Rc;
596    ///
597    /// let mut five = Rc::<u32>::try_new_uninit()?;
598    ///
599    /// // Deferred initialization:
600    /// Rc::get_mut(&mut five).unwrap().write(5);
601    ///
602    /// let five = unsafe { five.assume_init() };
603    ///
604    /// assert_eq!(*five, 5);
605    /// # Ok::<(), std::alloc::AllocError>(())
606    /// ```
607    #[unstable(feature = "allocator_api", issue = "32838")]
608    pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
609        unsafe {
610            Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
611                Layout::new::<T>(),
612                |layout| Global.allocate(layout),
613                <*mut u8>::cast,
614            )?))
615        }
616    }
617
618    /// Constructs a new `Rc` with uninitialized contents, with the memory
619    /// being filled with `0` bytes, returning an error if the allocation fails
620    ///
621    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
622    /// incorrect usage of this method.
623    ///
624    /// # Examples
625    ///
626    /// ```
627    /// #![feature(allocator_api)]
628    ///
629    /// use std::rc::Rc;
630    ///
631    /// let zero = Rc::<u32>::try_new_zeroed()?;
632    /// let zero = unsafe { zero.assume_init() };
633    ///
634    /// assert_eq!(*zero, 0);
635    /// # Ok::<(), std::alloc::AllocError>(())
636    /// ```
637    ///
638    /// [zeroed]: mem::MaybeUninit::zeroed
639    #[unstable(feature = "allocator_api", issue = "32838")]
640    pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
641        unsafe {
642            Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
643                Layout::new::<T>(),
644                |layout| Global.allocate_zeroed(layout),
645                <*mut u8>::cast,
646            )?))
647        }
648    }
649    /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
650    /// `value` will be pinned in memory and unable to be moved.
651    #[cfg(not(no_global_oom_handling))]
652    #[stable(feature = "pin", since = "1.33.0")]
653    #[must_use]
654    pub fn pin(value: T) -> Pin<Rc<T>> {
655        unsafe { Pin::new_unchecked(Rc::new(value)) }
656    }
657
658    /// Maps the value in an `Rc`, reusing the allocation if possible.
659    ///
660    /// `f` is called on a reference to the value in the `Rc`, and the result is returned, also in
661    /// an `Rc`.
662    ///
663    /// Note: this is an associated function, which means that you have
664    /// to call it as `Rc::map(r, f)` instead of `r.map(f)`. This
665    /// is so that there is no conflict with a method on the inner type.
666    ///
667    /// # Examples
668    ///
669    /// ```
670    /// #![feature(smart_pointer_try_map)]
671    ///
672    /// use std::rc::Rc;
673    ///
674    /// let r = Rc::new(7);
675    /// let new = Rc::map(r, |i| i + 7);
676    /// assert_eq!(*new, 14);
677    /// ```
678    #[cfg(not(no_global_oom_handling))]
679    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
680    pub fn map<U>(this: Self, f: impl FnOnce(&T) -> U) -> Rc<U> {
681        if size_of::<T>() == size_of::<U>()
682            && align_of::<T>() == align_of::<U>()
683            && Rc::is_unique(&this)
684        {
685            unsafe {
686                let ptr = Rc::into_raw(this);
687                let value = ptr.read();
688                let mut allocation = Rc::from_raw(ptr.cast::<mem::MaybeUninit<U>>());
689
690                Rc::get_mut_unchecked(&mut allocation).write(f(&value));
691                allocation.assume_init()
692            }
693        } else {
694            Rc::new(f(&*this))
695        }
696    }
697
698    /// Attempts to map the value in an `Rc`, reusing the allocation if possible.
699    ///
700    /// `f` is called on a reference to the value in the `Rc`, and if the operation succeeds, the
701    /// result is returned, also in an `Rc`.
702    ///
703    /// Note: this is an associated function, which means that you have
704    /// to call it as `Rc::try_map(r, f)` instead of `r.try_map(f)`. This
705    /// is so that there is no conflict with a method on the inner type.
706    ///
707    /// # Examples
708    ///
709    /// ```
710    /// #![feature(smart_pointer_try_map)]
711    ///
712    /// use std::rc::Rc;
713    ///
714    /// let b = Rc::new(7);
715    /// let new = Rc::try_map(b, |&i| u32::try_from(i)).unwrap();
716    /// assert_eq!(*new, 7);
717    /// ```
718    #[cfg(not(no_global_oom_handling))]
719    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
720    pub fn try_map<R>(
721        this: Self,
722        f: impl FnOnce(&T) -> R,
723    ) -> <R::Residual as Residual<Rc<R::Output>>>::TryType
724    where
725        R: Try,
726        R::Residual: Residual<Rc<R::Output>>,
727    {
728        if size_of::<T>() == size_of::<R::Output>()
729            && align_of::<T>() == align_of::<R::Output>()
730            && Rc::is_unique(&this)
731        {
732            unsafe {
733                let ptr = Rc::into_raw(this);
734                let value = ptr.read();
735                let mut allocation = Rc::from_raw(ptr.cast::<mem::MaybeUninit<R::Output>>());
736
737                Rc::get_mut_unchecked(&mut allocation).write(f(&value)?);
738                try { allocation.assume_init() }
739            }
740        } else {
741            try { Rc::new(f(&*this)?) }
742        }
743    }
744}
745
746impl<T, A: Allocator> Rc<T, A> {
747    /// Constructs a new `Rc` in the provided allocator.
748    ///
749    /// # Examples
750    ///
751    /// ```
752    /// #![feature(allocator_api)]
753    ///
754    /// use std::rc::Rc;
755    /// use std::alloc::System;
756    ///
757    /// let five = Rc::new_in(5, System);
758    /// ```
759    #[cfg(not(no_global_oom_handling))]
760    #[unstable(feature = "allocator_api", issue = "32838")]
761    #[inline]
762    pub fn new_in(value: T, alloc: A) -> Rc<T, A> {
763        // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
764        // That would make code size bigger.
765        match Self::try_new_in(value, alloc) {
766            Ok(m) => m,
767            Err(_) => handle_alloc_error(Layout::new::<RcInner<T>>()),
768        }
769    }
770
771    /// Constructs a new `Rc` with uninitialized contents in the provided allocator.
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// #![feature(get_mut_unchecked)]
777    /// #![feature(allocator_api)]
778    ///
779    /// use std::rc::Rc;
780    /// use std::alloc::System;
781    ///
782    /// let mut five = Rc::<u32, _>::new_uninit_in(System);
783    ///
784    /// let five = unsafe {
785    ///     // Deferred initialization:
786    ///     Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
787    ///
788    ///     five.assume_init()
789    /// };
790    ///
791    /// assert_eq!(*five, 5)
792    /// ```
793    #[cfg(not(no_global_oom_handling))]
794    #[unstable(feature = "allocator_api", issue = "32838")]
795    #[inline]
796    pub fn new_uninit_in(alloc: A) -> Rc<mem::MaybeUninit<T>, A> {
797        unsafe {
798            Rc::from_ptr_in(
799                Rc::allocate_for_layout(
800                    Layout::new::<T>(),
801                    |layout| alloc.allocate(layout),
802                    <*mut u8>::cast,
803                ),
804                alloc,
805            )
806        }
807    }
808
809    /// Constructs a new `Rc` with uninitialized contents, with the memory
810    /// being filled with `0` bytes, in the provided allocator.
811    ///
812    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
813    /// incorrect usage of this method.
814    ///
815    /// # Examples
816    ///
817    /// ```
818    /// #![feature(allocator_api)]
819    ///
820    /// use std::rc::Rc;
821    /// use std::alloc::System;
822    ///
823    /// let zero = Rc::<u32, _>::new_zeroed_in(System);
824    /// let zero = unsafe { zero.assume_init() };
825    ///
826    /// assert_eq!(*zero, 0)
827    /// ```
828    ///
829    /// [zeroed]: mem::MaybeUninit::zeroed
830    #[cfg(not(no_global_oom_handling))]
831    #[unstable(feature = "allocator_api", issue = "32838")]
832    #[inline]
833    pub fn new_zeroed_in(alloc: A) -> Rc<mem::MaybeUninit<T>, A> {
834        unsafe {
835            Rc::from_ptr_in(
836                Rc::allocate_for_layout(
837                    Layout::new::<T>(),
838                    |layout| alloc.allocate_zeroed(layout),
839                    <*mut u8>::cast,
840                ),
841                alloc,
842            )
843        }
844    }
845
846    /// Constructs a new `Rc<T, A>` in the given allocator while giving you a `Weak<T, A>` to the allocation,
847    /// to allow you to construct a `T` which holds a weak pointer to itself.
848    ///
849    /// Generally, a structure circularly referencing itself, either directly or
850    /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
851    /// Using this function, you get access to the weak pointer during the
852    /// initialization of `T`, before the `Rc<T, A>` is created, such that you can
853    /// clone and store it inside the `T`.
854    ///
855    /// `new_cyclic_in` first allocates the managed allocation for the `Rc<T, A>`,
856    /// then calls your closure, giving it a `Weak<T, A>` to this allocation,
857    /// and only afterwards completes the construction of the `Rc<T, A>` by placing
858    /// the `T` returned from your closure into the allocation.
859    ///
860    /// Since the new `Rc<T, A>` is not fully-constructed until `Rc<T, A>::new_cyclic_in`
861    /// returns, calling [`upgrade`] on the weak reference inside your closure will
862    /// fail and result in a `None` value.
863    ///
864    /// # Panics
865    ///
866    /// If `data_fn` panics, the panic is propagated to the caller, and the
867    /// temporary [`Weak<T, A>`] is dropped normally.
868    ///
869    /// # Examples
870    ///
871    /// See [`new_cyclic`].
872    ///
873    /// [`new_cyclic`]: Rc::new_cyclic
874    /// [`upgrade`]: Weak::upgrade
875    #[cfg(not(no_global_oom_handling))]
876    #[unstable(feature = "allocator_api", issue = "32838")]
877    pub fn new_cyclic_in<F>(data_fn: F, alloc: A) -> Rc<T, A>
878    where
879        F: FnOnce(&Weak<T, A>) -> T,
880    {
881        // Construct the inner in the "uninitialized" state with a single
882        // weak reference.
883        let (uninit_raw_ptr, alloc) = Box::into_raw_with_allocator(Box::new_in(
884            RcInner {
885                strong: Cell::new(0),
886                weak: Cell::new(1),
887                value: mem::MaybeUninit::<T>::uninit(),
888            },
889            alloc,
890        ));
891        let uninit_ptr: NonNull<_> = (unsafe { &mut *uninit_raw_ptr }).into();
892        let init_ptr: NonNull<RcInner<T>> = uninit_ptr.cast();
893
894        let weak = Weak { ptr: init_ptr, alloc };
895
896        // It's important we don't give up ownership of the weak pointer, or
897        // else the memory might be freed by the time `data_fn` returns. If
898        // we really wanted to pass ownership, we could create an additional
899        // weak pointer for ourselves, but this would result in additional
900        // updates to the weak reference count which might not be necessary
901        // otherwise.
902        let data = data_fn(&weak);
903
904        unsafe {
905            let inner = init_ptr.as_ptr();
906            ptr::write(&raw mut (*inner).value, data);
907
908            let prev_value = (*inner).strong.get();
909            debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
910            (*inner).strong.set(1);
911
912            // Strong references should collectively own a shared weak reference,
913            // so don't run the destructor for our old weak reference.
914            // Calling into_raw_with_allocator has the double effect of giving us back the allocator,
915            // and forgetting the weak reference.
916            let alloc = weak.into_raw_with_allocator().1;
917
918            Rc::from_inner_in(init_ptr, alloc)
919        }
920    }
921
922    /// Constructs a new `Rc<T>` in the provided allocator, returning an error if the allocation
923    /// fails
924    ///
925    /// # Examples
926    ///
927    /// ```
928    /// #![feature(allocator_api)]
929    /// use std::rc::Rc;
930    /// use std::alloc::System;
931    ///
932    /// let five = Rc::try_new_in(5, System);
933    /// # Ok::<(), std::alloc::AllocError>(())
934    /// ```
935    #[unstable(feature = "allocator_api", issue = "32838")]
936    #[inline]
937    pub fn try_new_in(value: T, alloc: A) -> Result<Self, AllocError> {
938        // There is an implicit weak pointer owned by all the strong
939        // pointers, which ensures that the weak destructor never frees
940        // the allocation while the strong destructor is running, even
941        // if the weak pointer is stored inside the strong one.
942        let (ptr, alloc) = Box::into_unique(Box::try_new_in(
943            RcInner { strong: Cell::new(1), weak: Cell::new(1), value },
944            alloc,
945        )?);
946        Ok(unsafe { Self::from_inner_in(ptr.into(), alloc) })
947    }
948
949    /// Constructs a new `Rc` with uninitialized contents, in the provided allocator, returning an
950    /// error if the allocation fails
951    ///
952    /// # Examples
953    ///
954    /// ```
955    /// #![feature(allocator_api)]
956    /// #![feature(get_mut_unchecked)]
957    ///
958    /// use std::rc::Rc;
959    /// use std::alloc::System;
960    ///
961    /// let mut five = Rc::<u32, _>::try_new_uninit_in(System)?;
962    ///
963    /// let five = unsafe {
964    ///     // Deferred initialization:
965    ///     Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
966    ///
967    ///     five.assume_init()
968    /// };
969    ///
970    /// assert_eq!(*five, 5);
971    /// # Ok::<(), std::alloc::AllocError>(())
972    /// ```
973    #[unstable(feature = "allocator_api", issue = "32838")]
974    #[inline]
975    pub fn try_new_uninit_in(alloc: A) -> Result<Rc<mem::MaybeUninit<T>, A>, AllocError> {
976        unsafe {
977            Ok(Rc::from_ptr_in(
978                Rc::try_allocate_for_layout(
979                    Layout::new::<T>(),
980                    |layout| alloc.allocate(layout),
981                    <*mut u8>::cast,
982                )?,
983                alloc,
984            ))
985        }
986    }
987
988    /// Constructs a new `Rc` with uninitialized contents, with the memory
989    /// being filled with `0` bytes, in the provided allocator, returning an error if the allocation
990    /// fails
991    ///
992    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
993    /// incorrect usage of this method.
994    ///
995    /// # Examples
996    ///
997    /// ```
998    /// #![feature(allocator_api)]
999    ///
1000    /// use std::rc::Rc;
1001    /// use std::alloc::System;
1002    ///
1003    /// let zero = Rc::<u32, _>::try_new_zeroed_in(System)?;
1004    /// let zero = unsafe { zero.assume_init() };
1005    ///
1006    /// assert_eq!(*zero, 0);
1007    /// # Ok::<(), std::alloc::AllocError>(())
1008    /// ```
1009    ///
1010    /// [zeroed]: mem::MaybeUninit::zeroed
1011    #[unstable(feature = "allocator_api", issue = "32838")]
1012    #[inline]
1013    pub fn try_new_zeroed_in(alloc: A) -> Result<Rc<mem::MaybeUninit<T>, A>, AllocError> {
1014        unsafe {
1015            Ok(Rc::from_ptr_in(
1016                Rc::try_allocate_for_layout(
1017                    Layout::new::<T>(),
1018                    |layout| alloc.allocate_zeroed(layout),
1019                    <*mut u8>::cast,
1020                )?,
1021                alloc,
1022            ))
1023        }
1024    }
1025
1026    /// Constructs a new `Pin<Rc<T>>` in the provided allocator. If `T` does not implement `Unpin`, then
1027    /// `value` will be pinned in memory and unable to be moved.
1028    #[cfg(not(no_global_oom_handling))]
1029    #[unstable(feature = "allocator_api", issue = "32838")]
1030    #[inline]
1031    pub fn pin_in(value: T, alloc: A) -> Pin<Self>
1032    where
1033        A: 'static,
1034    {
1035        unsafe { Pin::new_unchecked(Rc::new_in(value, alloc)) }
1036    }
1037
1038    /// Returns the inner value, if the `Rc` has exactly one strong reference.
1039    ///
1040    /// Otherwise, an [`Err`] is returned with the same `Rc` that was
1041    /// passed in.
1042    ///
1043    /// This will succeed even if there are outstanding weak references.
1044    ///
1045    /// # Examples
1046    ///
1047    /// ```
1048    /// use std::rc::Rc;
1049    ///
1050    /// let x = Rc::new(3);
1051    /// assert_eq!(Rc::try_unwrap(x), Ok(3));
1052    ///
1053    /// let x = Rc::new(4);
1054    /// let _y = Rc::clone(&x);
1055    /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
1056    /// ```
1057    #[inline]
1058    #[stable(feature = "rc_unique", since = "1.4.0")]
1059    pub fn try_unwrap(this: Self) -> Result<T, Self> {
1060        if Rc::strong_count(&this) == 1 {
1061            let this = ManuallyDrop::new(this);
1062
1063            let val: T = unsafe { ptr::read(&**this) }; // copy the contained object
1064            let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
1065
1066            // Indicate to Weaks that they can't be promoted by decrementing
1067            // the strong count, and then remove the implicit "strong weak"
1068            // pointer while also handling drop logic by just crafting a
1069            // fake Weak.
1070            this.inner().dec_strong();
1071            let _weak = Weak { ptr: this.ptr, alloc };
1072            Ok(val)
1073        } else {
1074            Err(this)
1075        }
1076    }
1077
1078    /// Returns the inner value, if the `Rc` has exactly one strong reference.
1079    ///
1080    /// Otherwise, [`None`] is returned and the `Rc` is dropped.
1081    ///
1082    /// This will succeed even if there are outstanding weak references.
1083    ///
1084    /// If `Rc::into_inner` is called on every clone of this `Rc`,
1085    /// it is guaranteed that exactly one of the calls returns the inner value.
1086    /// This means in particular that the inner value is not dropped.
1087    ///
1088    /// [`Rc::try_unwrap`] is conceptually similar to `Rc::into_inner`.
1089    /// And while they are meant for different use-cases, `Rc::into_inner(this)`
1090    /// is in fact equivalent to <code>[Rc::try_unwrap]\(this).[ok][Result::ok]()</code>.
1091    /// (Note that the same kind of equivalence does **not** hold true for
1092    /// [`Arc`](crate::sync::Arc), due to race conditions that do not apply to `Rc`!)
1093    ///
1094    /// # Examples
1095    ///
1096    /// ```
1097    /// use std::rc::Rc;
1098    ///
1099    /// let x = Rc::new(3);
1100    /// assert_eq!(Rc::into_inner(x), Some(3));
1101    ///
1102    /// let x = Rc::new(4);
1103    /// let y = Rc::clone(&x);
1104    ///
1105    /// assert_eq!(Rc::into_inner(y), None);
1106    /// assert_eq!(Rc::into_inner(x), Some(4));
1107    /// ```
1108    #[inline]
1109    #[stable(feature = "rc_into_inner", since = "1.70.0")]
1110    pub fn into_inner(this: Self) -> Option<T> {
1111        Rc::try_unwrap(this).ok()
1112    }
1113}
1114
1115impl<T> Rc<[T]> {
1116    /// Constructs a new reference-counted slice with uninitialized contents.
1117    ///
1118    /// # Examples
1119    ///
1120    /// ```
1121    /// use std::rc::Rc;
1122    ///
1123    /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
1124    ///
1125    /// // Deferred initialization:
1126    /// let data = Rc::get_mut(&mut values).unwrap();
1127    /// data[0].write(1);
1128    /// data[1].write(2);
1129    /// data[2].write(3);
1130    ///
1131    /// let values = unsafe { values.assume_init() };
1132    ///
1133    /// assert_eq!(*values, [1, 2, 3])
1134    /// ```
1135    #[cfg(not(no_global_oom_handling))]
1136    #[stable(feature = "new_uninit", since = "1.82.0")]
1137    #[must_use]
1138    pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
1139        unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
1140    }
1141
1142    /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
1143    /// filled with `0` bytes.
1144    ///
1145    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
1146    /// incorrect usage of this method.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```
1151    /// use std::rc::Rc;
1152    ///
1153    /// let values = Rc::<[u32]>::new_zeroed_slice(3);
1154    /// let values = unsafe { values.assume_init() };
1155    ///
1156    /// assert_eq!(*values, [0, 0, 0])
1157    /// ```
1158    ///
1159    /// [zeroed]: mem::MaybeUninit::zeroed
1160    #[cfg(not(no_global_oom_handling))]
1161    #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
1162    #[must_use]
1163    pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
1164        unsafe {
1165            Rc::from_ptr(Rc::allocate_for_layout(
1166                Layout::array::<T>(len).unwrap(),
1167                |layout| Global.allocate_zeroed(layout),
1168                |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[mem::MaybeUninit<T>]>,
1169            ))
1170        }
1171    }
1172}
1173
1174impl<T, A: Allocator> Rc<[T], A> {
1175    /// Constructs a new reference-counted slice with uninitialized contents.
1176    ///
1177    /// # Examples
1178    ///
1179    /// ```
1180    /// #![feature(get_mut_unchecked)]
1181    /// #![feature(allocator_api)]
1182    ///
1183    /// use std::rc::Rc;
1184    /// use std::alloc::System;
1185    ///
1186    /// let mut values = Rc::<[u32], _>::new_uninit_slice_in(3, System);
1187    ///
1188    /// let values = unsafe {
1189    ///     // Deferred initialization:
1190    ///     Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
1191    ///     Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
1192    ///     Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
1193    ///
1194    ///     values.assume_init()
1195    /// };
1196    ///
1197    /// assert_eq!(*values, [1, 2, 3])
1198    /// ```
1199    #[cfg(not(no_global_oom_handling))]
1200    #[unstable(feature = "allocator_api", issue = "32838")]
1201    #[inline]
1202    pub fn new_uninit_slice_in(len: usize, alloc: A) -> Rc<[mem::MaybeUninit<T>], A> {
1203        unsafe { Rc::from_ptr_in(Rc::allocate_for_slice_in(len, &alloc), alloc) }
1204    }
1205
1206    /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
1207    /// filled with `0` bytes.
1208    ///
1209    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
1210    /// incorrect usage of this method.
1211    ///
1212    /// # Examples
1213    ///
1214    /// ```
1215    /// #![feature(allocator_api)]
1216    ///
1217    /// use std::rc::Rc;
1218    /// use std::alloc::System;
1219    ///
1220    /// let values = Rc::<[u32], _>::new_zeroed_slice_in(3, System);
1221    /// let values = unsafe { values.assume_init() };
1222    ///
1223    /// assert_eq!(*values, [0, 0, 0])
1224    /// ```
1225    ///
1226    /// [zeroed]: mem::MaybeUninit::zeroed
1227    #[cfg(not(no_global_oom_handling))]
1228    #[unstable(feature = "allocator_api", issue = "32838")]
1229    #[inline]
1230    pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Rc<[mem::MaybeUninit<T>], A> {
1231        unsafe {
1232            Rc::from_ptr_in(
1233                Rc::allocate_for_layout(
1234                    Layout::array::<T>(len).unwrap(),
1235                    |layout| alloc.allocate_zeroed(layout),
1236                    |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[mem::MaybeUninit<T>]>,
1237                ),
1238                alloc,
1239            )
1240        }
1241    }
1242
1243    /// Converts the reference-counted slice into a reference-counted array.
1244    ///
1245    /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
1246    ///
1247    /// # Errors
1248    ///
1249    /// Returns the original `Rc<[T]>` in the `Err` variant if `self.len()` does not equal `N`.
1250    ///
1251    /// # Examples
1252    ///
1253    /// ```
1254    /// #![feature(alloc_slice_into_array)]
1255    /// use std::rc::Rc;
1256    ///
1257    /// let rc_slice: Rc<[i32]> = Rc::new([1, 2, 3]);
1258    ///
1259    /// let rc_array: Rc<[i32; 3]> = rc_slice.into_array().unwrap();
1260    /// ```
1261    #[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1262    #[inline]
1263    #[must_use]
1264    pub fn into_array<const N: usize>(self) -> Result<Rc<[T; N], A>, Self> {
1265        if self.len() == N {
1266            let (ptr, alloc) = Self::into_raw_with_allocator(self);
1267            let ptr = ptr as *const [T; N];
1268
1269            // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length.
1270            let me = unsafe { Rc::from_raw_in(ptr, alloc) };
1271            Ok(me)
1272        } else {
1273            Err(self)
1274        }
1275    }
1276}
1277
1278impl<T, A: Allocator> Rc<mem::MaybeUninit<T>, A> {
1279    /// Converts to `Rc<T>`.
1280    ///
1281    /// # Safety
1282    ///
1283    /// As with [`MaybeUninit::assume_init`],
1284    /// it is up to the caller to guarantee that the inner value
1285    /// really is in an initialized state.
1286    /// Calling this when the content is not yet fully initialized
1287    /// causes immediate undefined behavior.
1288    ///
1289    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1290    ///
1291    /// # Examples
1292    ///
1293    /// ```
1294    /// use std::rc::Rc;
1295    ///
1296    /// let mut five = Rc::<u32>::new_uninit();
1297    ///
1298    /// // Deferred initialization:
1299    /// Rc::get_mut(&mut five).unwrap().write(5);
1300    ///
1301    /// let five = unsafe { five.assume_init() };
1302    ///
1303    /// assert_eq!(*five, 5)
1304    /// ```
1305    #[stable(feature = "new_uninit", since = "1.82.0")]
1306    #[inline]
1307    pub unsafe fn assume_init(self) -> Rc<T, A> {
1308        let (ptr, alloc) = Rc::into_inner_with_allocator(self);
1309        unsafe { Rc::from_inner_in(ptr.cast(), alloc) }
1310    }
1311}
1312
1313impl<T: ?Sized + CloneToUninit> Rc<T> {
1314    /// Constructs a new `Rc<T>` with a clone of `value`.
1315    ///
1316    /// # Examples
1317    ///
1318    /// ```
1319    /// #![feature(clone_from_ref)]
1320    /// use std::rc::Rc;
1321    ///
1322    /// let hello: Rc<str> = Rc::clone_from_ref("hello");
1323    /// ```
1324    #[cfg(not(no_global_oom_handling))]
1325    #[unstable(feature = "clone_from_ref", issue = "149075")]
1326    pub fn clone_from_ref(value: &T) -> Rc<T> {
1327        Rc::clone_from_ref_in(value, Global)
1328    }
1329
1330    /// Constructs a new `Rc<T>` with a clone of `value`, returning an error if allocation fails
1331    ///
1332    /// # Examples
1333    ///
1334    /// ```
1335    /// #![feature(clone_from_ref)]
1336    /// #![feature(allocator_api)]
1337    /// use std::rc::Rc;
1338    ///
1339    /// let hello: Rc<str> = Rc::try_clone_from_ref("hello")?;
1340    /// # Ok::<(), std::alloc::AllocError>(())
1341    /// ```
1342    #[unstable(feature = "clone_from_ref", issue = "149075")]
1343    //#[unstable(feature = "allocator_api", issue = "32838")]
1344    pub fn try_clone_from_ref(value: &T) -> Result<Rc<T>, AllocError> {
1345        Rc::try_clone_from_ref_in(value, Global)
1346    }
1347}
1348
1349impl<T: ?Sized + CloneToUninit, A: Allocator> Rc<T, A> {
1350    /// Constructs a new `Rc<T>` with a clone of `value` in the provided allocator.
1351    ///
1352    /// # Examples
1353    ///
1354    /// ```
1355    /// #![feature(clone_from_ref)]
1356    /// #![feature(allocator_api)]
1357    /// use std::rc::Rc;
1358    /// use std::alloc::System;
1359    ///
1360    /// let hello: Rc<str, System> = Rc::clone_from_ref_in("hello", System);
1361    /// ```
1362    #[cfg(not(no_global_oom_handling))]
1363    #[unstable(feature = "clone_from_ref", issue = "149075")]
1364    //#[unstable(feature = "allocator_api", issue = "32838")]
1365    pub fn clone_from_ref_in(value: &T, alloc: A) -> Rc<T, A> {
1366        // `in_progress` drops the allocation if we panic before finishing initializing it.
1367        let mut in_progress: UniqueRcUninit<T, A> = UniqueRcUninit::new(value, alloc);
1368
1369        // Initialize with clone of value.
1370        unsafe {
1371            // Clone. If the clone panics, `in_progress` will be dropped and clean up.
1372            value.clone_to_uninit(in_progress.data_ptr().cast());
1373            // Cast type of pointer, now that it is initialized.
1374            in_progress.into_rc()
1375        }
1376    }
1377
1378    /// Constructs a new `Rc<T>` with a clone of `value` in the provided allocator, returning an error if allocation fails
1379    ///
1380    /// # Examples
1381    ///
1382    /// ```
1383    /// #![feature(clone_from_ref)]
1384    /// #![feature(allocator_api)]
1385    /// use std::rc::Rc;
1386    /// use std::alloc::System;
1387    ///
1388    /// let hello: Rc<str, System> = Rc::try_clone_from_ref_in("hello", System)?;
1389    /// # Ok::<(), std::alloc::AllocError>(())
1390    /// ```
1391    #[unstable(feature = "clone_from_ref", issue = "149075")]
1392    //#[unstable(feature = "allocator_api", issue = "32838")]
1393    pub fn try_clone_from_ref_in(value: &T, alloc: A) -> Result<Rc<T, A>, AllocError> {
1394        // `in_progress` drops the allocation if we panic before finishing initializing it.
1395        let mut in_progress: UniqueRcUninit<T, A> = UniqueRcUninit::try_new(value, alloc)?;
1396
1397        // Initialize with clone of value.
1398        let initialized_clone = unsafe {
1399            // Clone. If the clone panics, `in_progress` will be dropped and clean up.
1400            value.clone_to_uninit(in_progress.data_ptr().cast());
1401            // Cast type of pointer, now that it is initialized.
1402            in_progress.into_rc()
1403        };
1404
1405        Ok(initialized_clone)
1406    }
1407}
1408
1409impl<T, A: Allocator> Rc<[mem::MaybeUninit<T>], A> {
1410    /// Converts to `Rc<[T]>`.
1411    ///
1412    /// # Safety
1413    ///
1414    /// As with [`MaybeUninit::assume_init`],
1415    /// it is up to the caller to guarantee that the inner value
1416    /// really is in an initialized state.
1417    /// Calling this when the content is not yet fully initialized
1418    /// causes immediate undefined behavior.
1419    ///
1420    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1421    ///
1422    /// # Examples
1423    ///
1424    /// ```
1425    /// use std::rc::Rc;
1426    ///
1427    /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
1428    ///
1429    /// // Deferred initialization:
1430    /// let data = Rc::get_mut(&mut values).unwrap();
1431    /// data[0].write(1);
1432    /// data[1].write(2);
1433    /// data[2].write(3);
1434    ///
1435    /// let values = unsafe { values.assume_init() };
1436    ///
1437    /// assert_eq!(*values, [1, 2, 3])
1438    /// ```
1439    #[stable(feature = "new_uninit", since = "1.82.0")]
1440    #[inline]
1441    pub unsafe fn assume_init(self) -> Rc<[T], A> {
1442        let (ptr, alloc) = Rc::into_inner_with_allocator(self);
1443        unsafe { Rc::from_ptr_in(ptr.as_ptr() as _, alloc) }
1444    }
1445}
1446
1447impl<T: ?Sized> Rc<T> {
1448    /// Constructs an `Rc<T>` from a raw pointer.
1449    ///
1450    /// The raw pointer must have been previously returned by a call to
1451    /// [`Rc<U>::into_raw`][into_raw] or [`Rc<U>::into_raw_with_allocator`][into_raw_with_allocator].
1452    ///
1453    /// # Safety
1454    ///
1455    /// * Creating a `Rc<T>` from a pointer other than one returned from
1456    ///   [`Rc<U>::into_raw`][into_raw] or [`Rc<U>::into_raw_with_allocator`][into_raw_with_allocator]
1457    ///   is undefined behavior.
1458    /// * If `U` is sized, it must have the same size and alignment as `T`. This
1459    ///   is trivially true if `U` is `T`.
1460    /// * If `U` is unsized, its data pointer must have the same size and
1461    ///   alignment as `T`. This is trivially true if `Rc<U>` was constructed
1462    ///   through `Rc<T>` and then converted to `Rc<U>` through an [unsized
1463    ///   coercion].
1464    /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size
1465    ///   and alignment, this is basically like transmuting references of
1466    ///   different types. See [`mem::transmute`][transmute] for more information
1467    ///   on what restrictions apply in this case.
1468    /// * The raw pointer must point to a block of memory allocated by the global allocator
1469    /// * The user of `from_raw` has to make sure a specific value of `T` is only
1470    ///   dropped once.
1471    ///
1472    /// This function is unsafe because improper use may lead to memory unsafety,
1473    /// even if the returned `Rc<T>` is never accessed.
1474    ///
1475    /// [into_raw]: Rc::into_raw
1476    /// [into_raw_with_allocator]: Rc::into_raw_with_allocator
1477    /// [transmute]: core::mem::transmute
1478    /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions
1479    ///
1480    /// # Examples
1481    ///
1482    /// ```
1483    /// use std::rc::Rc;
1484    ///
1485    /// let x = Rc::new("hello".to_owned());
1486    /// let x_ptr = Rc::into_raw(x);
1487    ///
1488    /// unsafe {
1489    ///     // Convert back to an `Rc` to prevent leak.
1490    ///     let x = Rc::from_raw(x_ptr);
1491    ///     assert_eq!(&*x, "hello");
1492    ///
1493    ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
1494    /// }
1495    ///
1496    /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
1497    /// ```
1498    ///
1499    /// Convert a slice back into its original array:
1500    ///
1501    /// ```
1502    /// use std::rc::Rc;
1503    ///
1504    /// let x: Rc<[u32]> = Rc::new([1, 2, 3]);
1505    /// let x_ptr: *const [u32] = Rc::into_raw(x);
1506    ///
1507    /// unsafe {
1508    ///     let x: Rc<[u32; 3]> = Rc::from_raw(x_ptr.cast::<[u32; 3]>());
1509    ///     assert_eq!(&*x, &[1, 2, 3]);
1510    /// }
1511    /// ```
1512    #[inline]
1513    #[stable(feature = "rc_raw", since = "1.17.0")]
1514    pub unsafe fn from_raw(ptr: *const T) -> Self {
1515        unsafe { Self::from_raw_in(ptr, Global) }
1516    }
1517
1518    /// Consumes the `Rc`, returning the wrapped pointer.
1519    ///
1520    /// To avoid a memory leak the pointer must be converted back to an `Rc` using
1521    /// [`Rc::from_raw`].
1522    ///
1523    /// # Examples
1524    ///
1525    /// ```
1526    /// use std::rc::Rc;
1527    ///
1528    /// let x = Rc::new("hello".to_owned());
1529    /// let x_ptr = Rc::into_raw(x);
1530    /// assert_eq!(unsafe { &*x_ptr }, "hello");
1531    /// # // Prevent leaks for Miri.
1532    /// # drop(unsafe { Rc::from_raw(x_ptr) });
1533    /// ```
1534    #[must_use = "losing the pointer will leak memory"]
1535    #[stable(feature = "rc_raw", since = "1.17.0")]
1536    #[rustc_never_returns_null_ptr]
1537    pub fn into_raw(this: Self) -> *const T {
1538        let this = ManuallyDrop::new(this);
1539        Self::as_ptr(&*this)
1540    }
1541
1542    /// Increments the strong reference count on the `Rc<T>` associated with the
1543    /// provided pointer by one.
1544    ///
1545    /// # Safety
1546    ///
1547    /// The pointer must have been obtained through [`Rc::into_raw`] and must satisfy the
1548    /// same layout requirements specified in [`Rc::from_raw_in`].
1549    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1550    /// least 1) for the duration of this method, and `ptr` must point to a block of memory
1551    /// allocated by the global allocator.
1552    ///
1553    /// # Examples
1554    ///
1555    /// ```
1556    /// use std::rc::Rc;
1557    ///
1558    /// let five = Rc::new(5);
1559    ///
1560    /// unsafe {
1561    ///     let ptr = Rc::into_raw(five);
1562    ///     Rc::increment_strong_count(ptr);
1563    ///
1564    ///     let five = Rc::from_raw(ptr);
1565    ///     assert_eq!(2, Rc::strong_count(&five));
1566    /// #   // Prevent leaks for Miri.
1567    /// #   Rc::decrement_strong_count(ptr);
1568    /// }
1569    /// ```
1570    #[inline]
1571    #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1572    pub unsafe fn increment_strong_count(ptr: *const T) {
1573        unsafe { Self::increment_strong_count_in(ptr, Global) }
1574    }
1575
1576    /// Decrements the strong reference count on the `Rc<T>` associated with the
1577    /// provided pointer by one.
1578    ///
1579    /// # Safety
1580    ///
1581    /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1582    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1583    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1584    /// least 1) when invoking this method, and `ptr` must point to a block of memory
1585    /// allocated by the global allocator. This method can be used to release the final `Rc` and
1586    /// backing storage, but **should not** be called after the final `Rc` has been released.
1587    ///
1588    /// [from_raw_in]: Rc::from_raw_in
1589    ///
1590    /// # Examples
1591    ///
1592    /// ```
1593    /// use std::rc::Rc;
1594    ///
1595    /// let five = Rc::new(5);
1596    ///
1597    /// unsafe {
1598    ///     let ptr = Rc::into_raw(five);
1599    ///     Rc::increment_strong_count(ptr);
1600    ///
1601    ///     let five = Rc::from_raw(ptr);
1602    ///     assert_eq!(2, Rc::strong_count(&five));
1603    ///     Rc::decrement_strong_count(ptr);
1604    ///     assert_eq!(1, Rc::strong_count(&five));
1605    /// }
1606    /// ```
1607    #[inline]
1608    #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1609    pub unsafe fn decrement_strong_count(ptr: *const T) {
1610        unsafe { Self::decrement_strong_count_in(ptr, Global) }
1611    }
1612}
1613
1614impl<T: ?Sized, A: Allocator> Rc<T, A> {
1615    /// Returns a reference to the underlying allocator.
1616    ///
1617    /// Note: this is an associated function, which means that you have
1618    /// to call it as `Rc::allocator(&r)` instead of `r.allocator()`. This
1619    /// is so that there is no conflict with a method on the inner type.
1620    #[inline]
1621    #[unstable(feature = "allocator_api", issue = "32838")]
1622    pub fn allocator(this: &Self) -> &A {
1623        &this.alloc
1624    }
1625
1626    /// Consumes the `Rc`, returning the wrapped pointer and allocator.
1627    ///
1628    /// To avoid a memory leak the pointer must be converted back to an `Rc` using
1629    /// [`Rc::from_raw_in`].
1630    ///
1631    /// # Examples
1632    ///
1633    /// ```
1634    /// #![feature(allocator_api)]
1635    /// use std::rc::Rc;
1636    /// use std::alloc::System;
1637    ///
1638    /// let x = Rc::new_in("hello".to_owned(), System);
1639    /// let (ptr, alloc) = Rc::into_raw_with_allocator(x);
1640    /// assert_eq!(unsafe { &*ptr }, "hello");
1641    /// let x = unsafe { Rc::from_raw_in(ptr, alloc) };
1642    /// assert_eq!(&*x, "hello");
1643    /// ```
1644    #[must_use = "losing the pointer will leak memory"]
1645    #[unstable(feature = "allocator_api", issue = "32838")]
1646    pub fn into_raw_with_allocator(this: Self) -> (*const T, A) {
1647        let this = mem::ManuallyDrop::new(this);
1648        let ptr = Self::as_ptr(&this);
1649        // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
1650        let alloc = unsafe { ptr::read(&this.alloc) };
1651        (ptr, alloc)
1652    }
1653
1654    /// Provides a raw pointer to the data.
1655    ///
1656    /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
1657    /// for as long as there are strong counts in the `Rc`.
1658    ///
1659    /// # Examples
1660    ///
1661    /// ```
1662    /// use std::rc::Rc;
1663    ///
1664    /// let x = Rc::new(0);
1665    /// let y = Rc::clone(&x);
1666    /// let x_ptr = Rc::as_ptr(&x);
1667    /// assert_eq!(x_ptr, Rc::as_ptr(&y));
1668    /// assert_eq!(unsafe { *x_ptr }, 0);
1669    /// ```
1670    #[stable(feature = "weak_into_raw", since = "1.45.0")]
1671    #[rustc_never_returns_null_ptr]
1672    pub fn as_ptr(this: &Self) -> *const T {
1673        let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
1674
1675        // SAFETY: This cannot go through Deref::deref or Rc::inner because
1676        // this is required to retain raw/mut provenance such that e.g. `get_mut` can
1677        // write through the pointer after the Rc is recovered through `from_raw`.
1678        unsafe { &raw mut (*ptr).value }
1679    }
1680
1681    /// Constructs an `Rc<T, A>` from a raw pointer in the provided allocator.
1682    ///
1683    /// The raw pointer must have been previously returned by a call to [`Rc<U,
1684    /// A>::into_raw`][into_raw] or [`Rc<U, A>::into_raw_with_allocator`][into_raw_with_allocator].
1685    ///
1686    /// # Safety
1687    ///
1688    /// * Creating a `Rc<T, A>` from a pointer other than one returned from
1689    ///   [`Rc<U, A>::into_raw`][into_raw] or [`Rc<U, A>::into_raw_with_allocator`][into_raw_with_allocator]
1690    ///   is undefined behavior.
1691    /// * If `U` is sized, it must have the same size and alignment as `T`. This
1692    ///   is trivially true if `U` is `T`.
1693    /// * If `U` is unsized, its data pointer must have the same size and
1694    ///   alignment as `T`. This is trivially true if `Rc<U, A>` was constructed
1695    ///   through `Rc<T, A>` and then converted to `Rc<U, A>` through an [unsized
1696    ///   coercion].
1697    /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size
1698    ///   and alignment, this is basically like transmuting references of
1699    ///   different types. See [`mem::transmute`][transmute] for more information
1700    ///   on what restrictions apply in this case.
1701    /// * The raw pointer must point to a block of memory allocated by `alloc`
1702    /// * The user of `from_raw` has to make sure a specific value of `T` is only
1703    ///   dropped once.
1704    ///
1705    /// This function is unsafe because improper use may lead to memory unsafety,
1706    /// even if the returned `Rc<T, A>` is never accessed.
1707    ///
1708    /// [into_raw]: Rc::into_raw
1709    /// [into_raw_with_allocator]: Rc::into_raw_with_allocator
1710    /// [transmute]: core::mem::transmute
1711    /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions
1712    ///
1713    /// # Examples
1714    ///
1715    /// ```
1716    /// #![feature(allocator_api)]
1717    ///
1718    /// use std::rc::Rc;
1719    /// use std::alloc::System;
1720    ///
1721    /// let x = Rc::new_in("hello".to_owned(), System);
1722    /// let (x_ptr, _alloc) = Rc::into_raw_with_allocator(x);
1723    ///
1724    /// unsafe {
1725    ///     // Convert back to an `Rc` to prevent leak.
1726    ///     let x = Rc::from_raw_in(x_ptr, System);
1727    ///     assert_eq!(&*x, "hello");
1728    ///
1729    ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
1730    /// }
1731    ///
1732    /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
1733    /// ```
1734    ///
1735    /// Convert a slice back into its original array:
1736    ///
1737    /// ```
1738    /// #![feature(allocator_api)]
1739    ///
1740    /// use std::rc::Rc;
1741    /// use std::alloc::System;
1742    ///
1743    /// let x: Rc<[u32], _> = Rc::new_in([1, 2, 3], System);
1744    /// let x_ptr: *const [u32] = Rc::into_raw_with_allocator(x).0;
1745    ///
1746    /// unsafe {
1747    ///     let x: Rc<[u32; 3], _> = Rc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System);
1748    ///     assert_eq!(&*x, &[1, 2, 3]);
1749    /// }
1750    /// ```
1751    #[unstable(feature = "allocator_api", issue = "32838")]
1752    pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
1753        let offset = unsafe { data_offset(ptr) };
1754
1755        // Reverse the offset to find the original RcInner.
1756        let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
1757
1758        unsafe { Self::from_ptr_in(rc_ptr, alloc) }
1759    }
1760
1761    /// Creates a new [`Weak`] pointer to this allocation.
1762    ///
1763    /// # Examples
1764    ///
1765    /// ```
1766    /// use std::rc::Rc;
1767    ///
1768    /// let five = Rc::new(5);
1769    ///
1770    /// let weak_five = Rc::downgrade(&five);
1771    /// ```
1772    #[must_use = "this returns a new `Weak` pointer, \
1773                  without modifying the original `Rc`"]
1774    #[stable(feature = "rc_weak", since = "1.4.0")]
1775    pub fn downgrade(this: &Self) -> Weak<T, A>
1776    where
1777        A: AllocatorClone,
1778    {
1779        this.inner().inc_weak();
1780        // Make sure we do not create a dangling Weak
1781        debug_assert!(!is_dangling(this.ptr.as_ptr()));
1782        Weak { ptr: this.ptr, alloc: this.alloc.clone() }
1783    }
1784
1785    /// Gets the number of [`Weak`] pointers to this allocation.
1786    ///
1787    /// # Examples
1788    ///
1789    /// ```
1790    /// use std::rc::Rc;
1791    ///
1792    /// let five = Rc::new(5);
1793    /// let _weak_five = Rc::downgrade(&five);
1794    ///
1795    /// assert_eq!(1, Rc::weak_count(&five));
1796    /// ```
1797    #[inline]
1798    #[stable(feature = "rc_counts", since = "1.15.0")]
1799    pub fn weak_count(this: &Self) -> usize {
1800        this.inner().weak() - 1
1801    }
1802
1803    /// Gets the number of strong (`Rc`) pointers to this allocation.
1804    ///
1805    /// # Examples
1806    ///
1807    /// ```
1808    /// use std::rc::Rc;
1809    ///
1810    /// let five = Rc::new(5);
1811    /// let _also_five = Rc::clone(&five);
1812    ///
1813    /// assert_eq!(2, Rc::strong_count(&five));
1814    /// ```
1815    #[inline]
1816    #[stable(feature = "rc_counts", since = "1.15.0")]
1817    pub fn strong_count(this: &Self) -> usize {
1818        this.inner().strong()
1819    }
1820
1821    /// Increments the strong reference count on the `Rc<T>` associated with the
1822    /// provided pointer by one.
1823    ///
1824    /// # Safety
1825    ///
1826    /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1827    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1828    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1829    /// least 1) for the duration of this method, and `ptr` must point to a block of memory
1830    /// allocated by `alloc`.
1831    ///
1832    /// [from_raw_in]: Rc::from_raw_in
1833    ///
1834    /// # Examples
1835    ///
1836    /// ```
1837    /// #![feature(allocator_api)]
1838    ///
1839    /// use std::rc::Rc;
1840    /// use std::alloc::System;
1841    ///
1842    /// let five = Rc::new_in(5, System);
1843    ///
1844    /// unsafe {
1845    ///     let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1846    ///     Rc::increment_strong_count_in(ptr, System);
1847    ///
1848    ///     let five = Rc::from_raw_in(ptr, System);
1849    ///     assert_eq!(2, Rc::strong_count(&five));
1850    /// #   // Prevent leaks for Miri.
1851    /// #   Rc::decrement_strong_count_in(ptr, System);
1852    /// }
1853    /// ```
1854    #[inline]
1855    #[unstable(feature = "allocator_api", issue = "32838")]
1856    pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
1857    where
1858        A: AllocatorClone,
1859    {
1860        // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1861        let rc = unsafe { mem::ManuallyDrop::new(Rc::<T, A>::from_raw_in(ptr, alloc)) };
1862        // Now increase refcount, but don't drop new refcount either
1863        let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1864    }
1865
1866    /// Decrements the strong reference count on the `Rc<T>` associated with the
1867    /// provided pointer by one.
1868    ///
1869    /// # Safety
1870    ///
1871    /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the
1872    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1873    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1874    /// least 1) when invoking this method, and `ptr` must point to a block of memory
1875    /// allocated by `alloc`. This method can be used to release the final `Rc` and
1876    /// backing storage, but **should not** be called after the final `Rc` has been released.
1877    ///
1878    /// [from_raw_in]: Rc::from_raw_in
1879    ///
1880    /// # Examples
1881    ///
1882    /// ```
1883    /// #![feature(allocator_api)]
1884    ///
1885    /// use std::rc::Rc;
1886    /// use std::alloc::System;
1887    ///
1888    /// let five = Rc::new_in(5, System);
1889    ///
1890    /// unsafe {
1891    ///     let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1892    ///     Rc::increment_strong_count_in(ptr, System);
1893    ///
1894    ///     let five = Rc::from_raw_in(ptr, System);
1895    ///     assert_eq!(2, Rc::strong_count(&five));
1896    ///     Rc::decrement_strong_count_in(ptr, System);
1897    ///     assert_eq!(1, Rc::strong_count(&five));
1898    /// }
1899    /// ```
1900    #[inline]
1901    #[unstable(feature = "allocator_api", issue = "32838")]
1902    pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) {
1903        unsafe { drop(Rc::from_raw_in(ptr, alloc)) };
1904    }
1905
1906    /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1907    /// this allocation.
1908    #[inline]
1909    fn is_unique(this: &Self) -> bool {
1910        Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1911    }
1912
1913    /// Returns a mutable reference into the given `Rc`, if there are
1914    /// no other `Rc` or [`Weak`] pointers to the same allocation.
1915    ///
1916    /// Returns [`None`] otherwise, because it is not safe to
1917    /// mutate a shared value.
1918    ///
1919    /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1920    /// the inner value when there are other `Rc` pointers.
1921    ///
1922    /// [make_mut]: Rc::make_mut
1923    /// [clone]: Clone::clone
1924    ///
1925    /// # Examples
1926    ///
1927    /// ```
1928    /// use std::rc::Rc;
1929    ///
1930    /// let mut x = Rc::new(3);
1931    /// *Rc::get_mut(&mut x).unwrap() = 4;
1932    /// assert_eq!(*x, 4);
1933    ///
1934    /// let _y = Rc::clone(&x);
1935    /// assert!(Rc::get_mut(&mut x).is_none());
1936    /// ```
1937    #[inline]
1938    #[stable(feature = "rc_unique", since = "1.4.0")]
1939    pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1940        if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1941    }
1942
1943    /// Returns a mutable reference into the given `Rc`,
1944    /// without any check.
1945    ///
1946    /// See also [`get_mut`], which is safe and does appropriate checks.
1947    ///
1948    /// [`get_mut`]: Rc::get_mut
1949    ///
1950    /// # Safety
1951    ///
1952    /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
1953    /// they must not be dereferenced or have active borrows for the duration
1954    /// of the returned borrow, and their inner type must be exactly the same as the
1955    /// inner type of this Rc (including lifetimes). This is trivially the case if no
1956    /// such pointers exist, for example immediately after `Rc::new`.
1957    ///
1958    /// # Examples
1959    ///
1960    /// ```
1961    /// #![feature(get_mut_unchecked)]
1962    ///
1963    /// use std::rc::Rc;
1964    ///
1965    /// let mut x = Rc::new(String::new());
1966    /// unsafe {
1967    ///     Rc::get_mut_unchecked(&mut x).push_str("foo")
1968    /// }
1969    /// assert_eq!(*x, "foo");
1970    /// ```
1971    /// Other `Rc` pointers to the same allocation must be to the same type.
1972    /// ```no_run
1973    /// #![feature(get_mut_unchecked)]
1974    ///
1975    /// use std::rc::Rc;
1976    ///
1977    /// let x: Rc<str> = Rc::from("Hello, world!");
1978    /// let mut y: Rc<[u8]> = x.clone().into();
1979    /// unsafe {
1980    ///     // this is Undefined Behavior, because x's inner type is str, not [u8]
1981    ///     Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
1982    /// }
1983    /// println!("{}", &*x); // Invalid UTF-8 in a str
1984    /// ```
1985    /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
1986    /// ```no_run
1987    /// #![feature(get_mut_unchecked)]
1988    ///
1989    /// use std::rc::Rc;
1990    ///
1991    /// let x: Rc<&str> = Rc::new("Hello, world!");
1992    /// {
1993    ///     let s = String::from("Oh, no!");
1994    ///     let mut y: Rc<&str> = x.clone();
1995    ///     unsafe {
1996    ///         // this is Undefined Behavior, because x's inner type
1997    ///         // is &'long str, not &'short str
1998    ///         *Rc::get_mut_unchecked(&mut y) = &s;
1999    ///     }
2000    /// }
2001    /// println!("{}", &*x); // Use-after-free
2002    /// ```
2003    #[inline]
2004    #[unstable(feature = "get_mut_unchecked", issue = "63292")]
2005    pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
2006        // We are careful to *not* create a reference covering the "count" fields, as
2007        // this would conflict with accesses to the reference counts (e.g. by `Weak`).
2008        unsafe { &mut (*this.ptr.as_ptr()).value }
2009    }
2010
2011    #[inline]
2012    #[stable(feature = "ptr_eq", since = "1.17.0")]
2013    /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
2014    /// [`ptr::eq`]. This function ignores the metadata of  `dyn Trait` pointers.
2015    ///
2016    /// # Examples
2017    ///
2018    /// ```
2019    /// use std::rc::Rc;
2020    ///
2021    /// let five = Rc::new(5);
2022    /// let same_five = Rc::clone(&five);
2023    /// let other_five = Rc::new(5);
2024    ///
2025    /// assert!(Rc::ptr_eq(&five, &same_five));
2026    /// assert!(!Rc::ptr_eq(&five, &other_five));
2027    /// ```
2028    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
2029        ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr())
2030    }
2031}
2032
2033#[cfg(not(no_global_oom_handling))]
2034impl<T: ?Sized + CloneToUninit, A: AllocatorClone> Rc<T, A> {
2035    /// Makes a mutable reference into the given `Rc`.
2036    ///
2037    /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
2038    /// [`clone`] the inner value to a new allocation to ensure unique ownership.  This is also
2039    /// referred to as clone-on-write.
2040    ///
2041    /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
2042    /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
2043    /// be cloned.
2044    ///
2045    /// See also [`get_mut`], which will fail rather than cloning the inner value
2046    /// or disassociating [`Weak`] pointers.
2047    ///
2048    /// [`clone`]: Clone::clone
2049    /// [`get_mut`]: Rc::get_mut
2050    ///
2051    /// # Examples
2052    ///
2053    /// ```
2054    /// use std::rc::Rc;
2055    ///
2056    /// let mut data = Rc::new(5);
2057    ///
2058    /// *Rc::make_mut(&mut data) += 1;         // Won't clone anything
2059    /// let mut other_data = Rc::clone(&data); // Won't clone inner data
2060    /// *Rc::make_mut(&mut data) += 1;         // Clones inner data
2061    /// *Rc::make_mut(&mut data) += 1;         // Won't clone anything
2062    /// *Rc::make_mut(&mut other_data) *= 2;   // Won't clone anything
2063    ///
2064    /// // Now `data` and `other_data` point to different allocations.
2065    /// assert_eq!(*data, 8);
2066    /// assert_eq!(*other_data, 12);
2067    /// ```
2068    ///
2069    /// [`Weak`] pointers will be disassociated:
2070    ///
2071    /// ```
2072    /// use std::rc::Rc;
2073    ///
2074    /// let mut data = Rc::new(75);
2075    /// let weak = Rc::downgrade(&data);
2076    ///
2077    /// assert!(75 == *data);
2078    /// assert!(75 == *weak.upgrade().unwrap());
2079    ///
2080    /// *Rc::make_mut(&mut data) += 1;
2081    ///
2082    /// assert!(76 == *data);
2083    /// assert!(weak.upgrade().is_none());
2084    /// ```
2085    #[inline]
2086    #[stable(feature = "rc_unique", since = "1.4.0")]
2087    pub fn make_mut(this: &mut Self) -> &mut T {
2088        let size_of_val = size_of_val::<T>(&**this);
2089
2090        if Rc::strong_count(this) != 1 {
2091            // Gotta clone the data, there are other Rcs.
2092            *this = Rc::clone_from_ref_in(&**this, this.alloc.clone());
2093        } else if Rc::weak_count(this) != 0 {
2094            // Can just steal the data, all that's left is Weaks
2095
2096            let mut in_progress: UniqueRcUninit<T, A> =
2097                UniqueRcUninit::new(&**this, this.alloc.clone());
2098            unsafe {
2099                // Initialize `in_progress` with move of **this.
2100                // We have to express this in terms of bytes because `T: ?Sized`; there is no
2101                // operation that just copies a value based on its `size_of_val()`.
2102                ptr::copy_nonoverlapping(
2103                    ptr::from_ref(&**this).cast::<u8>(),
2104                    in_progress.data_ptr().cast::<u8>(),
2105                    size_of_val,
2106                );
2107
2108                // This leaves us with 0 strong refs, so the data has
2109                // effectively been moved to the new rc.
2110                this.inner().dec_strong();
2111
2112                // Remove implicit strong-weak ref (no need to craft a fake
2113                // Weak here -- we know other Weaks can clean up for us)
2114                this.inner().dec_weak();
2115
2116                // Last chance to not accidentally forget the allocator.
2117                // Only drop at the end of the scope to avoid panics.
2118                let _alloc = ptr::read(&this.alloc);
2119
2120                // Replace `this` with newly constructed Rc that has the moved data.
2121                ptr::write(this, in_progress.into_rc());
2122            }
2123        }
2124        // This unsafety is ok because we're guaranteed that the pointer
2125        // returned is the *only* pointer that will ever be returned to T. Our
2126        // reference count is guaranteed to be 1 at this point, and we required
2127        // the `Rc<T>` itself to be `mut`, so we're returning the only possible
2128        // reference to the allocation.
2129        unsafe { &mut this.ptr.as_mut().value }
2130    }
2131}
2132
2133impl<T: Clone, A: Allocator> Rc<T, A> {
2134    /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
2135    /// clone.
2136    ///
2137    /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
2138    /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
2139    ///
2140    /// # Examples
2141    ///
2142    /// ```
2143    /// # use std::{ptr, rc::Rc};
2144    /// let inner = String::from("test");
2145    /// let ptr = inner.as_ptr();
2146    ///
2147    /// let rc = Rc::new(inner);
2148    /// let inner = Rc::unwrap_or_clone(rc);
2149    /// // The inner value was not cloned
2150    /// assert!(ptr::eq(ptr, inner.as_ptr()));
2151    ///
2152    /// let rc = Rc::new(inner);
2153    /// let rc2 = rc.clone();
2154    /// let inner = Rc::unwrap_or_clone(rc);
2155    /// // Because there were 2 references, we had to clone the inner value.
2156    /// assert!(!ptr::eq(ptr, inner.as_ptr()));
2157    /// // `rc2` is the last reference, so when we unwrap it we get back
2158    /// // the original `String`.
2159    /// let inner = Rc::unwrap_or_clone(rc2);
2160    /// assert!(ptr::eq(ptr, inner.as_ptr()));
2161    /// ```
2162    #[inline]
2163    #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")]
2164    pub fn unwrap_or_clone(this: Self) -> T {
2165        Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
2166    }
2167}
2168
2169impl<A: Allocator> Rc<dyn Any, A> {
2170    /// Attempts to downcast the `Rc<dyn Any>` to a concrete type.
2171    ///
2172    /// # Examples
2173    ///
2174    /// ```
2175    /// use std::any::Any;
2176    /// use std::rc::Rc;
2177    ///
2178    /// fn print_if_string(value: Rc<dyn Any>) {
2179    ///     if let Ok(string) = value.downcast::<String>() {
2180    ///         println!("String ({}): {}", string.len(), string);
2181    ///     }
2182    /// }
2183    ///
2184    /// let my_string = "Hello World".to_string();
2185    /// print_if_string(Rc::new(my_string));
2186    /// print_if_string(Rc::new(0i8));
2187    /// ```
2188    #[inline]
2189    #[stable(feature = "rc_downcast", since = "1.29.0")]
2190    pub fn downcast<T: Any>(self) -> Result<Rc<T, A>, Self> {
2191        if (*self).is::<T>() {
2192            unsafe {
2193                let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2194                Ok(Rc::from_inner_in(ptr.cast(), alloc))
2195            }
2196        } else {
2197            Err(self)
2198        }
2199    }
2200
2201    /// Downcasts the `Rc<dyn Any>` to a concrete type.
2202    ///
2203    /// For a safe alternative see [`downcast`].
2204    ///
2205    /// # Examples
2206    ///
2207    /// ```
2208    /// #![feature(downcast_unchecked)]
2209    ///
2210    /// use std::any::Any;
2211    /// use std::rc::Rc;
2212    ///
2213    /// let x: Rc<dyn Any> = Rc::new(1_usize);
2214    ///
2215    /// unsafe {
2216    ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2217    /// }
2218    /// ```
2219    ///
2220    /// # Safety
2221    ///
2222    /// The contained value must be of type `T`. Calling this method
2223    /// with the incorrect type is *undefined behavior*.
2224    ///
2225    ///
2226    /// [`downcast`]: Self::downcast
2227    #[inline]
2228    #[unstable(feature = "downcast_unchecked", issue = "90850")]
2229    pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T, A> {
2230        unsafe {
2231            let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2232            Rc::from_inner_in(ptr.cast(), alloc)
2233        }
2234    }
2235}
2236
2237impl<T: ?Sized> Rc<T> {
2238    /// Allocates an `RcInner<T>` with sufficient space for
2239    /// a possibly-unsized inner value where the value has the layout provided.
2240    ///
2241    /// The function `mem_to_rc_inner` is called with the data pointer
2242    /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2243    #[cfg(not(no_global_oom_handling))]
2244    unsafe fn allocate_for_layout(
2245        value_layout: Layout,
2246        allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2247        mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2248    ) -> *mut RcInner<T> {
2249        let layout = rc_inner_layout_for_value_layout(value_layout);
2250        unsafe {
2251            Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rc_inner)
2252                .unwrap_or_else(|_| handle_alloc_error(layout))
2253        }
2254    }
2255
2256    /// Allocates an `RcInner<T>` with sufficient space for
2257    /// a possibly-unsized inner value where the value has the layout provided,
2258    /// returning an error if allocation fails.
2259    ///
2260    /// The function `mem_to_rc_inner` is called with the data pointer
2261    /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2262    #[inline]
2263    unsafe fn try_allocate_for_layout(
2264        value_layout: Layout,
2265        allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2266        mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2267    ) -> Result<*mut RcInner<T>, AllocError> {
2268        let layout = rc_inner_layout_for_value_layout(value_layout);
2269
2270        // Allocate for the layout.
2271        let ptr = allocate(layout)?;
2272
2273        // Initialize the RcInner
2274        let inner = mem_to_rc_inner(ptr.as_non_null_ptr().as_ptr());
2275        unsafe {
2276            debug_assert_eq!(Layout::for_value_raw(inner), layout);
2277
2278            (&raw mut (*inner).strong).write(Cell::new(1));
2279            (&raw mut (*inner).weak).write(Cell::new(1));
2280        }
2281
2282        Ok(inner)
2283    }
2284}
2285
2286impl<T: ?Sized, A: Allocator> Rc<T, A> {
2287    /// Allocates an `RcInner<T>` with sufficient space for an unsized inner value
2288    #[cfg(not(no_global_oom_handling))]
2289    unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut RcInner<T> {
2290        // Allocate for the `RcInner<T>` using the given value.
2291        unsafe {
2292            Rc::<T>::allocate_for_layout(
2293                Layout::for_value_raw(ptr),
2294                |layout| alloc.allocate(layout),
2295                |mem| mem.with_metadata_of(ptr as *const RcInner<T>),
2296            )
2297        }
2298    }
2299
2300    #[cfg(not(no_global_oom_handling))]
2301    fn from_box_in(src: Box<T, A>) -> Rc<T, A> {
2302        unsafe {
2303            let value_size = size_of_val(&*src);
2304            let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src));
2305
2306            // Copy value as bytes
2307            ptr::copy_nonoverlapping(
2308                (&raw const *src) as *const u8,
2309                (&raw mut (*ptr).value) as *mut u8,
2310                value_size,
2311            );
2312
2313            // Free the allocation without dropping its contents
2314            let (bptr, alloc) = Box::into_raw_with_allocator(src);
2315            let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop<T>, &alloc);
2316            drop(src);
2317
2318            Self::from_ptr_in(ptr, alloc)
2319        }
2320    }
2321}
2322
2323impl<T> Rc<[T]> {
2324    /// Allocates an `RcInner<[T]>` with the given length.
2325    #[cfg(not(no_global_oom_handling))]
2326    unsafe fn allocate_for_slice(len: usize) -> *mut RcInner<[T]> {
2327        unsafe {
2328            Self::allocate_for_layout(
2329                Layout::array::<T>(len).unwrap(),
2330                |layout| Global.allocate(layout),
2331                |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2332            )
2333        }
2334    }
2335
2336    /// Copy elements from slice into newly allocated `Rc<[T]>`
2337    ///
2338    /// Unsafe because the caller must either take ownership, bind `T: Copy` or
2339    /// bind `T: TrivialClone`.
2340    #[cfg(not(no_global_oom_handling))]
2341    unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
2342        unsafe {
2343            let ptr = Self::allocate_for_slice(v.len());
2344            ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).value) as *mut T, v.len());
2345            Self::from_ptr(ptr)
2346        }
2347    }
2348
2349    /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
2350    ///
2351    /// Behavior is undefined should the size be wrong.
2352    #[cfg(not(no_global_oom_handling))]
2353    unsafe fn from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]> {
2354        // Panic guard while cloning T elements.
2355        // In the event of a panic, elements that have been written
2356        // into the new RcInner will be dropped, then the memory freed.
2357        struct Guard<T> {
2358            mem: NonNull<u8>,
2359            elems: *mut T,
2360            layout: Layout,
2361            n_elems: usize,
2362        }
2363
2364        impl<T> Drop for Guard<T> {
2365            fn drop(&mut self) {
2366                unsafe {
2367                    let slice = from_raw_parts_mut(self.elems, self.n_elems);
2368                    ptr::drop_in_place(slice);
2369
2370                    Global.deallocate(self.mem, self.layout);
2371                }
2372            }
2373        }
2374
2375        unsafe {
2376            let ptr = Self::allocate_for_slice(len);
2377
2378            let mem = ptr as *mut _ as *mut u8;
2379            let layout = Layout::for_value_raw(ptr);
2380
2381            // Pointer to first element
2382            let elems = (&raw mut (*ptr).value) as *mut T;
2383
2384            let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
2385
2386            for (i, item) in iter.enumerate() {
2387                ptr::write(elems.add(i), item);
2388                guard.n_elems += 1;
2389            }
2390
2391            // All clear. Forget the guard so it doesn't free the new RcInner.
2392            mem::forget(guard);
2393
2394            Self::from_ptr(ptr)
2395        }
2396    }
2397}
2398
2399impl<T, A: Allocator> Rc<[T], A> {
2400    /// Allocates an `RcInner<[T]>` with the given length.
2401    #[inline]
2402    #[cfg(not(no_global_oom_handling))]
2403    unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut RcInner<[T]> {
2404        unsafe {
2405            Rc::<[T]>::allocate_for_layout(
2406                Layout::array::<T>(len).unwrap(),
2407                |layout| alloc.allocate(layout),
2408                |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2409            )
2410        }
2411    }
2412}
2413
2414#[cfg(not(no_global_oom_handling))]
2415/// Specialization trait used for `From<&[T]>`.
2416trait RcFromSlice<T> {
2417    fn from_slice(slice: &[T]) -> Self;
2418}
2419
2420#[cfg(not(no_global_oom_handling))]
2421impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
2422    #[inline]
2423    default fn from_slice(v: &[T]) -> Self {
2424        unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
2425    }
2426}
2427
2428#[cfg(not(no_global_oom_handling))]
2429impl<T: TrivialClone> RcFromSlice<T> for Rc<[T]> {
2430    #[inline]
2431    fn from_slice(v: &[T]) -> Self {
2432        // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent
2433        // to the above.
2434        unsafe { Rc::copy_from_slice(v) }
2435    }
2436}
2437
2438#[stable(feature = "rust1", since = "1.0.0")]
2439impl<T: ?Sized, A: Allocator> Deref for Rc<T, A> {
2440    type Target = T;
2441
2442    #[inline(always)]
2443    fn deref(&self) -> &T {
2444        &self.inner().value
2445    }
2446}
2447
2448// The API of this pointer type enforces that if the `T` is pinned, then *all*
2449// clones of this `Rc<T>` are wrapped as `Pin<Rc<T>>`. Since an `&Rc<T>` could
2450// be used to obtain an `Rc<T>` that is not wrapped in `Pin` (and later used
2451// with `Rc::get_mut`), this means that this type treats `&Rc<T>` as evidence
2452// that the `T` is not pinned. The implementations of various traits are written
2453// accordingly. Since this type is not fundamental, downstream crates cannot
2454// provide malicious implementations of any of the traits relevant for `Pin`.
2455#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2456unsafe impl<T: ?Sized, A: Allocator + 'static> PinSafePointer for Rc<T, A> {}
2457
2458//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2459#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2460unsafe impl<T: ?Sized, A: Allocator + 'static> PinSafePointer for UniqueRc<T, A> {}
2461
2462#[unstable(feature = "deref_pure_trait", issue = "87121")]
2463unsafe impl<T: ?Sized, A: Allocator> DerefPure for Rc<T, A> {}
2464
2465//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2466#[unstable(feature = "deref_pure_trait", issue = "87121")]
2467unsafe impl<T: ?Sized, A: Allocator> DerefPure for UniqueRc<T, A> {}
2468
2469#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2470impl<T: ?Sized> LegacyReceiver for Rc<T> {}
2471
2472#[stable(feature = "rust1", since = "1.0.0")]
2473unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
2474    /// Drops the `Rc`.
2475    ///
2476    /// This will decrement the strong reference count. If the strong reference
2477    /// count reaches zero then the only other references (if any) are
2478    /// [`Weak`], so we `drop` the inner value.
2479    ///
2480    /// # Examples
2481    ///
2482    /// ```
2483    /// use std::rc::Rc;
2484    ///
2485    /// struct Foo;
2486    ///
2487    /// impl Drop for Foo {
2488    ///     fn drop(&mut self) {
2489    ///         println!("dropped!");
2490    ///     }
2491    /// }
2492    ///
2493    /// let foo  = Rc::new(Foo);
2494    /// let foo2 = Rc::clone(&foo);
2495    ///
2496    /// drop(foo);    // Doesn't print anything
2497    /// drop(foo2);   // Prints "dropped!"
2498    /// ```
2499    #[inline]
2500    fn drop(&mut self) {
2501        unsafe {
2502            self.inner().dec_strong();
2503            if self.inner().strong() == 0 {
2504                self.drop_slow();
2505            }
2506        }
2507    }
2508}
2509
2510#[stable(feature = "rust1", since = "1.0.0")]
2511impl<T: ?Sized, A: AllocatorClone> Clone for Rc<T, A> {
2512    /// Makes a clone of the `Rc` pointer.
2513    ///
2514    /// This creates another pointer to the same allocation, increasing the
2515    /// strong reference count.
2516    ///
2517    /// # Examples
2518    ///
2519    /// ```
2520    /// use std::rc::Rc;
2521    ///
2522    /// let five = Rc::new(5);
2523    ///
2524    /// let _ = Rc::clone(&five);
2525    /// ```
2526    #[inline]
2527    fn clone(&self) -> Self {
2528        unsafe {
2529            self.inner().inc_strong();
2530            Self::from_inner_in(self.ptr, self.alloc.clone())
2531        }
2532    }
2533}
2534
2535#[unstable(feature = "ergonomic_clones", issue = "132290")]
2536impl<T: ?Sized, A: AllocatorClone> UseCloned for Rc<T, A> {}
2537
2538#[unstable(feature = "share_trait", issue = "156756")]
2539impl<T: ?Sized, A: AllocatorClone> Share for Rc<T, A> {}
2540
2541#[cfg(not(no_global_oom_handling))]
2542#[stable(feature = "rust1", since = "1.0.0")]
2543impl<T: Default> Default for Rc<T> {
2544    /// Creates a new `Rc<T>`, with the `Default` value for `T`.
2545    ///
2546    /// # Examples
2547    ///
2548    /// ```
2549    /// use std::rc::Rc;
2550    ///
2551    /// let x: Rc<i32> = Default::default();
2552    /// assert_eq!(*x, 0);
2553    /// ```
2554    #[inline]
2555    fn default() -> Self {
2556        unsafe {
2557            Self::from_inner(
2558                Box::leak(Box::write(
2559                    Box::new_uninit(),
2560                    RcInner { strong: Cell::new(1), weak: Cell::new(1), value: T::default() },
2561                ))
2562                .into(),
2563            )
2564        }
2565    }
2566}
2567
2568#[cfg(not(no_global_oom_handling))]
2569#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2570impl Default for Rc<str> {
2571    /// Creates an empty `str` inside an `Rc`.
2572    ///
2573    /// This may or may not share an allocation with other Rcs on the same thread.
2574    #[inline]
2575    fn default() -> Self {
2576        let rc = Rc::<[u8]>::default();
2577        // `[u8]` has the same layout as `str`.
2578        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2579    }
2580}
2581
2582#[cfg(not(no_global_oom_handling))]
2583#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2584impl<T> Default for Rc<[T]> {
2585    /// Creates an empty `[T]` inside an `Rc`.
2586    ///
2587    /// This may or may not share an allocation with other Rcs on the same thread.
2588    #[inline]
2589    fn default() -> Self {
2590        let arr: [T; 0] = [];
2591        Rc::from(arr)
2592    }
2593}
2594
2595#[cfg(not(no_global_oom_handling))]
2596#[stable(feature = "pin_default_impls", since = "1.91.0")]
2597impl<T> Default for Pin<Rc<T>>
2598where
2599    T: ?Sized,
2600    Rc<T>: Default,
2601{
2602    #[inline]
2603    fn default() -> Self {
2604        unsafe { Pin::new_unchecked(Rc::<T>::default()) }
2605    }
2606}
2607
2608#[stable(feature = "rust1", since = "1.0.0")]
2609trait RcEqIdent<T: ?Sized + PartialEq, A: Allocator> {
2610    fn eq(&self, other: &Rc<T, A>) -> bool;
2611    fn ne(&self, other: &Rc<T, A>) -> bool;
2612}
2613
2614#[stable(feature = "rust1", since = "1.0.0")]
2615impl<T: ?Sized + PartialEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2616    #[inline]
2617    default fn eq(&self, other: &Rc<T, A>) -> bool {
2618        **self == **other
2619    }
2620
2621    #[inline]
2622    default fn ne(&self, other: &Rc<T, A>) -> bool {
2623        **self != **other
2624    }
2625}
2626
2627// Hack to allow specializing on `Eq` even though `Eq` has a method.
2628#[unsafe(rustc_allow_lifetime_dependent_specialization)]
2629pub(crate) trait MarkerEq: PartialEq<Self> {}
2630
2631impl<T: ?Sized + Eq> MarkerEq for T {}
2632
2633/// We're doing this specialization here, and not as a more general optimization on `&T`, because it
2634/// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
2635/// store large values, that are slow to clone, but also heavy to check for equality, causing this
2636/// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
2637/// the same value, than two `&T`s.
2638///
2639/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
2640#[stable(feature = "rust1", since = "1.0.0")]
2641impl<T: ?Sized + MarkerEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2642    #[inline]
2643    fn eq(&self, other: &Rc<T, A>) -> bool {
2644        ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other
2645    }
2646
2647    #[inline]
2648    fn ne(&self, other: &Rc<T, A>) -> bool {
2649        !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other
2650    }
2651}
2652
2653#[stable(feature = "rust1", since = "1.0.0")]
2654impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Rc<T, A> {
2655    /// Equality for two `Rc`s.
2656    ///
2657    /// Two `Rc`s are equal if their inner values are equal, even if they are
2658    /// stored in different allocation.
2659    ///
2660    /// If `T` also implements `Eq` (implying reflexivity of equality),
2661    /// two `Rc`s that point to the same allocation are
2662    /// always equal.
2663    ///
2664    /// # Examples
2665    ///
2666    /// ```
2667    /// use std::rc::Rc;
2668    ///
2669    /// let five = Rc::new(5);
2670    ///
2671    /// assert!(five == Rc::new(5));
2672    /// ```
2673    #[inline]
2674    fn eq(&self, other: &Rc<T, A>) -> bool {
2675        RcEqIdent::eq(self, other)
2676    }
2677
2678    /// Inequality for two `Rc`s.
2679    ///
2680    /// Two `Rc`s are not equal if their inner values are not equal.
2681    ///
2682    /// If `T` also implements `Eq` (implying reflexivity of equality),
2683    /// two `Rc`s that point to the same allocation are
2684    /// always equal.
2685    ///
2686    /// # Examples
2687    ///
2688    /// ```
2689    /// use std::rc::Rc;
2690    ///
2691    /// let five = Rc::new(5);
2692    ///
2693    /// assert!(five != Rc::new(6));
2694    /// ```
2695    #[inline]
2696    fn ne(&self, other: &Rc<T, A>) -> bool {
2697        RcEqIdent::ne(self, other)
2698    }
2699}
2700
2701#[stable(feature = "rust1", since = "1.0.0")]
2702impl<T: ?Sized + Eq, A: Allocator> Eq for Rc<T, A> {}
2703
2704#[stable(feature = "rust1", since = "1.0.0")]
2705impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Rc<T, A> {
2706    /// Partial comparison for two `Rc`s.
2707    ///
2708    /// The two are compared by calling `partial_cmp()` on their inner values.
2709    ///
2710    /// # Examples
2711    ///
2712    /// ```
2713    /// use std::rc::Rc;
2714    /// use std::cmp::Ordering;
2715    ///
2716    /// let five = Rc::new(5);
2717    ///
2718    /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
2719    /// ```
2720    #[inline(always)]
2721    fn partial_cmp(&self, other: &Rc<T, A>) -> Option<Ordering> {
2722        (**self).partial_cmp(&**other)
2723    }
2724
2725    /// Less-than comparison for two `Rc`s.
2726    ///
2727    /// The two are compared by calling `<` on their inner values.
2728    ///
2729    /// # Examples
2730    ///
2731    /// ```
2732    /// use std::rc::Rc;
2733    ///
2734    /// let five = Rc::new(5);
2735    ///
2736    /// assert!(five < Rc::new(6));
2737    /// ```
2738    #[inline(always)]
2739    fn lt(&self, other: &Rc<T, A>) -> bool {
2740        **self < **other
2741    }
2742
2743    /// 'Less than or equal to' comparison for two `Rc`s.
2744    ///
2745    /// The two are compared by calling `<=` on their inner values.
2746    ///
2747    /// # Examples
2748    ///
2749    /// ```
2750    /// use std::rc::Rc;
2751    ///
2752    /// let five = Rc::new(5);
2753    ///
2754    /// assert!(five <= Rc::new(5));
2755    /// ```
2756    #[inline(always)]
2757    fn le(&self, other: &Rc<T, A>) -> bool {
2758        **self <= **other
2759    }
2760
2761    /// Greater-than comparison for two `Rc`s.
2762    ///
2763    /// The two are compared by calling `>` on their inner values.
2764    ///
2765    /// # Examples
2766    ///
2767    /// ```
2768    /// use std::rc::Rc;
2769    ///
2770    /// let five = Rc::new(5);
2771    ///
2772    /// assert!(five > Rc::new(4));
2773    /// ```
2774    #[inline(always)]
2775    fn gt(&self, other: &Rc<T, A>) -> bool {
2776        **self > **other
2777    }
2778
2779    /// 'Greater than or equal to' comparison for two `Rc`s.
2780    ///
2781    /// The two are compared by calling `>=` on their inner values.
2782    ///
2783    /// # Examples
2784    ///
2785    /// ```
2786    /// use std::rc::Rc;
2787    ///
2788    /// let five = Rc::new(5);
2789    ///
2790    /// assert!(five >= Rc::new(5));
2791    /// ```
2792    #[inline(always)]
2793    fn ge(&self, other: &Rc<T, A>) -> bool {
2794        **self >= **other
2795    }
2796}
2797
2798#[stable(feature = "rust1", since = "1.0.0")]
2799impl<T: ?Sized + Ord, A: Allocator> Ord for Rc<T, A> {
2800    /// Comparison for two `Rc`s.
2801    ///
2802    /// The two are compared by calling `cmp()` on their inner values.
2803    ///
2804    /// # Examples
2805    ///
2806    /// ```
2807    /// use std::rc::Rc;
2808    /// use std::cmp::Ordering;
2809    ///
2810    /// let five = Rc::new(5);
2811    ///
2812    /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
2813    /// ```
2814    #[inline]
2815    fn cmp(&self, other: &Rc<T, A>) -> Ordering {
2816        (**self).cmp(&**other)
2817    }
2818}
2819
2820#[stable(feature = "rust1", since = "1.0.0")]
2821impl<T: ?Sized + Hash, A: Allocator> Hash for Rc<T, A> {
2822    fn hash<H: Hasher>(&self, state: &mut H) {
2823        (**self).hash(state);
2824    }
2825}
2826
2827#[stable(feature = "rust1", since = "1.0.0")]
2828impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for Rc<T, A> {
2829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2830        fmt::Display::fmt(&**self, f)
2831    }
2832}
2833
2834#[stable(feature = "rust1", since = "1.0.0")]
2835impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Rc<T, A> {
2836    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2837        fmt::Debug::fmt(&**self, f)
2838    }
2839}
2840
2841#[stable(feature = "rust1", since = "1.0.0")]
2842impl<T: ?Sized, A: Allocator> fmt::Pointer for Rc<T, A> {
2843    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2844        fmt::Pointer::fmt(&(&raw const **self), f)
2845    }
2846}
2847
2848#[cfg(not(no_global_oom_handling))]
2849#[stable(feature = "from_for_ptrs", since = "1.6.0")]
2850impl<T> From<T> for Rc<T> {
2851    /// Converts a generic type `T` into an `Rc<T>`
2852    ///
2853    /// The conversion allocates on the heap and moves `t`
2854    /// from the stack into it.
2855    ///
2856    /// # Example
2857    /// ```rust
2858    /// # use std::rc::Rc;
2859    /// let x = 5;
2860    /// let rc = Rc::new(5);
2861    ///
2862    /// assert_eq!(Rc::from(x), rc);
2863    /// ```
2864    fn from(t: T) -> Self {
2865        Rc::new(t)
2866    }
2867}
2868
2869#[cfg(not(no_global_oom_handling))]
2870#[stable(feature = "shared_from_array", since = "1.74.0")]
2871impl<T, const N: usize> From<[T; N]> for Rc<[T]> {
2872    /// Converts a [`[T; N]`](prim@array) into an `Rc<[T]>`.
2873    ///
2874    /// The conversion moves the array into a newly allocated `Rc`.
2875    ///
2876    /// # Example
2877    ///
2878    /// ```
2879    /// # use std::rc::Rc;
2880    /// let original: [i32; 3] = [1, 2, 3];
2881    /// let shared: Rc<[i32]> = Rc::from(original);
2882    /// assert_eq!(&[1, 2, 3], &shared[..]);
2883    /// ```
2884    #[inline]
2885    fn from(v: [T; N]) -> Rc<[T]> {
2886        Rc::<[T; N]>::from(v)
2887    }
2888}
2889
2890#[cfg(not(no_global_oom_handling))]
2891#[stable(feature = "shared_from_slice", since = "1.21.0")]
2892impl<T: Clone> From<&[T]> for Rc<[T]> {
2893    /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2894    ///
2895    /// # Example
2896    ///
2897    /// ```
2898    /// # use std::rc::Rc;
2899    /// let original: &[i32] = &[1, 2, 3];
2900    /// let shared: Rc<[i32]> = Rc::from(original);
2901    /// assert_eq!(&[1, 2, 3], &shared[..]);
2902    /// ```
2903    #[inline]
2904    fn from(v: &[T]) -> Rc<[T]> {
2905        <Self as RcFromSlice<T>>::from_slice(v)
2906    }
2907}
2908
2909#[cfg(not(no_global_oom_handling))]
2910#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2911impl<T: Clone> From<&mut [T]> for Rc<[T]> {
2912    /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2913    ///
2914    /// # Example
2915    ///
2916    /// ```
2917    /// # use std::rc::Rc;
2918    /// let mut original = [1, 2, 3];
2919    /// let original: &mut [i32] = &mut original;
2920    /// let shared: Rc<[i32]> = Rc::from(original);
2921    /// assert_eq!(&[1, 2, 3], &shared[..]);
2922    /// ```
2923    #[inline]
2924    fn from(v: &mut [T]) -> Rc<[T]> {
2925        Rc::from(&*v)
2926    }
2927}
2928
2929#[cfg(not(no_global_oom_handling))]
2930#[stable(feature = "shared_from_slice", since = "1.21.0")]
2931impl From<&str> for Rc<str> {
2932    /// Allocates a reference-counted string slice and copies `v` into it.
2933    ///
2934    /// # Example
2935    ///
2936    /// ```
2937    /// # use std::rc::Rc;
2938    /// let shared: Rc<str> = Rc::from("statue");
2939    /// assert_eq!("statue", &shared[..]);
2940    /// ```
2941    #[inline]
2942    fn from(v: &str) -> Rc<str> {
2943        let rc = Rc::<[u8]>::from(v.as_bytes());
2944        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2945    }
2946}
2947
2948#[cfg(not(no_global_oom_handling))]
2949#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2950impl From<&mut str> for Rc<str> {
2951    /// Allocates a reference-counted string slice and copies `v` into it.
2952    ///
2953    /// # Example
2954    ///
2955    /// ```
2956    /// # use std::rc::Rc;
2957    /// let mut original = String::from("statue");
2958    /// let original: &mut str = &mut original;
2959    /// let shared: Rc<str> = Rc::from(original);
2960    /// assert_eq!("statue", &shared[..]);
2961    /// ```
2962    #[inline]
2963    fn from(v: &mut str) -> Rc<str> {
2964        Rc::from(&*v)
2965    }
2966}
2967
2968#[cfg(not(no_global_oom_handling))]
2969#[stable(feature = "shared_from_slice", since = "1.21.0")]
2970impl From<String> for Rc<str> {
2971    /// Allocates a reference-counted string slice and copies `v` into it.
2972    ///
2973    /// # Example
2974    ///
2975    /// ```
2976    /// # use std::rc::Rc;
2977    /// let original: String = "statue".to_owned();
2978    /// let shared: Rc<str> = Rc::from(original);
2979    /// assert_eq!("statue", &shared[..]);
2980    /// ```
2981    #[inline]
2982    fn from(v: String) -> Rc<str> {
2983        Rc::from(&v[..])
2984    }
2985}
2986
2987#[cfg(not(no_global_oom_handling))]
2988#[stable(feature = "shared_from_slice", since = "1.21.0")]
2989impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Rc<T, A> {
2990    /// Move a boxed object to a new, reference counted, allocation.
2991    ///
2992    /// # Example
2993    ///
2994    /// ```
2995    /// # use std::rc::Rc;
2996    /// let original: Box<i32> = Box::new(1);
2997    /// let shared: Rc<i32> = Rc::from(original);
2998    /// assert_eq!(1, *shared);
2999    /// ```
3000    #[inline]
3001    fn from(v: Box<T, A>) -> Rc<T, A> {
3002        Rc::from_box_in(v)
3003    }
3004}
3005
3006#[cfg(not(no_global_oom_handling))]
3007#[stable(feature = "shared_from_slice", since = "1.21.0")]
3008impl<T, A: AllocatorClone> From<Vec<T, A>> for Rc<[T], A> {
3009    /// Allocates a reference-counted slice and moves `v`'s items into it.
3010    ///
3011    /// # Example
3012    ///
3013    /// ```
3014    /// # use std::rc::Rc;
3015    /// let unique: Vec<i32> = vec![1, 2, 3];
3016    /// let shared: Rc<[i32]> = Rc::from(unique);
3017    /// assert_eq!(&[1, 2, 3], &shared[..]);
3018    /// ```
3019    #[inline]
3020    fn from(v: Vec<T, A>) -> Rc<[T], A> {
3021        unsafe {
3022            let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator();
3023
3024            let rc_ptr = Self::allocate_for_slice_in(len, &alloc);
3025            ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).value) as *mut T, len);
3026
3027            // Create a `Vec<T, &A>` with length 0, to deallocate the buffer
3028            // without dropping its contents or the allocator
3029            let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc);
3030
3031            Self::from_ptr_in(rc_ptr, alloc)
3032        }
3033    }
3034}
3035
3036#[stable(feature = "shared_from_cow", since = "1.45.0")]
3037impl<'a, B> From<Cow<'a, B>> for Rc<B>
3038where
3039    B: ToOwned + ?Sized,
3040    Rc<B>: From<&'a B> + From<B::Owned>,
3041{
3042    /// Creates a reference-counted pointer from a clone-on-write pointer by
3043    /// copying its content.
3044    ///
3045    /// # Example
3046    ///
3047    /// ```rust
3048    /// # use std::rc::Rc;
3049    /// # use std::borrow::Cow;
3050    /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
3051    /// let shared: Rc<str> = Rc::from(cow);
3052    /// assert_eq!("eggplant", &shared[..]);
3053    /// ```
3054    #[inline]
3055    fn from(cow: Cow<'a, B>) -> Rc<B> {
3056        match cow {
3057            Cow::Borrowed(s) => Rc::from(s),
3058            Cow::Owned(s) => Rc::from(s),
3059        }
3060    }
3061}
3062
3063#[stable(feature = "shared_from_str", since = "1.62.0")]
3064impl From<Rc<str>> for Rc<[u8]> {
3065    /// Converts a reference-counted string slice into a byte slice.
3066    ///
3067    /// # Example
3068    ///
3069    /// ```
3070    /// # use std::rc::Rc;
3071    /// let string: Rc<str> = Rc::from("eggplant");
3072    /// let bytes: Rc<[u8]> = Rc::from(string);
3073    /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
3074    /// ```
3075    #[inline]
3076    fn from(rc: Rc<str>) -> Self {
3077        // SAFETY: `str` has the same layout as `[u8]`.
3078        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
3079    }
3080}
3081
3082#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
3083impl<T, A: Allocator, const N: usize> TryFrom<Rc<[T], A>> for Rc<[T; N], A> {
3084    type Error = Rc<[T], A>;
3085
3086    fn try_from(boxed_slice: Rc<[T], A>) -> Result<Self, Self::Error> {
3087        if boxed_slice.len() == N {
3088            let (ptr, alloc) = Rc::into_inner_with_allocator(boxed_slice);
3089            Ok(unsafe { Rc::from_inner_in(ptr.cast(), alloc) })
3090        } else {
3091            Err(boxed_slice)
3092        }
3093    }
3094}
3095
3096#[cfg(not(no_global_oom_handling))]
3097#[stable(feature = "shared_from_iter", since = "1.37.0")]
3098impl<T> FromIterator<T> for Rc<[T]> {
3099    /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
3100    ///
3101    /// # Performance characteristics
3102    ///
3103    /// ## The general case
3104    ///
3105    /// In the general case, collecting into `Rc<[T]>` is done by first
3106    /// collecting into a `Vec<T>`. That is, when writing the following:
3107    ///
3108    /// ```rust
3109    /// # use std::rc::Rc;
3110    /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
3111    /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3112    /// ```
3113    ///
3114    /// this behaves as if we wrote:
3115    ///
3116    /// ```rust
3117    /// # use std::rc::Rc;
3118    /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
3119    ///     .collect::<Vec<_>>() // The first set of allocations happens here.
3120    ///     .into(); // A second allocation for `Rc<[T]>` happens here.
3121    /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3122    /// ```
3123    ///
3124    /// This will allocate as many times as needed for constructing the `Vec<T>`
3125    /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
3126    ///
3127    /// ## Iterators of known length
3128    ///
3129    /// When your `Iterator` implements `TrustedLen` and is of an exact size,
3130    /// a single allocation will be made for the `Rc<[T]>`. For example:
3131    ///
3132    /// ```rust
3133    /// # use std::rc::Rc;
3134    /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
3135    /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
3136    /// ```
3137    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
3138        ToRcSlice::to_rc_slice(iter.into_iter())
3139    }
3140}
3141
3142/// Specialization trait used for collecting into `Rc<[T]>`.
3143#[cfg(not(no_global_oom_handling))]
3144trait ToRcSlice<T>: Iterator<Item = T> + Sized {
3145    fn to_rc_slice(self) -> Rc<[T]>;
3146}
3147
3148#[cfg(not(no_global_oom_handling))]
3149impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
3150    default fn to_rc_slice(self) -> Rc<[T]> {
3151        self.collect::<Vec<T>>().into()
3152    }
3153}
3154
3155#[cfg(not(no_global_oom_handling))]
3156impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
3157    fn to_rc_slice(self) -> Rc<[T]> {
3158        // This is the case for a `TrustedLen` iterator.
3159        let (low, high) = self.size_hint();
3160        if let Some(high) = high {
3161            debug_assert_eq!(
3162                low,
3163                high,
3164                "TrustedLen iterator's size hint is not exact: {:?}",
3165                (low, high)
3166            );
3167
3168            unsafe {
3169                // SAFETY: We need to ensure that the iterator has an exact length and we have.
3170                Rc::from_iter_exact(self, low)
3171            }
3172        } else {
3173            // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
3174            // length exceeding `usize::MAX`.
3175            // The default implementation would collect into a vec which would panic.
3176            // Thus we panic here immediately without invoking `Vec` code.
3177            panic!("capacity overflow");
3178        }
3179    }
3180}
3181
3182/// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
3183/// managed allocation.
3184///
3185/// The allocation is accessed by calling [`upgrade`] on the `Weak`
3186/// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
3187///
3188/// Since a `Weak` reference does not count towards ownership, it will not
3189/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
3190/// guarantees about the value still being present. Thus it may return [`None`]
3191/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
3192/// itself (the backing store) from being deallocated.
3193///
3194/// A `Weak` pointer is useful for keeping a temporary reference to the allocation
3195/// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
3196/// prevent circular references between [`Rc`] pointers, since mutual owning references
3197/// would never allow either [`Rc`] to be dropped. For example, a tree could
3198/// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
3199/// pointers from children back to their parents.
3200///
3201/// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
3202///
3203/// [`upgrade`]: Weak::upgrade
3204#[stable(feature = "rc_weak", since = "1.4.0")]
3205#[rustc_diagnostic_item = "RcWeak"]
3206pub struct Weak<
3207    T: ?Sized,
3208    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3209> {
3210    // This is a `NonNull` to allow optimizing the size of this type in enums,
3211    // but it is not necessarily a valid pointer.
3212    // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
3213    // to allocate space on the heap. That's not a value a real pointer
3214    // will ever have because RcInner has alignment at least 2.
3215    ptr: NonNull<RcInner<T>>,
3216    alloc: A,
3217}
3218
3219#[stable(feature = "rc_weak", since = "1.4.0")]
3220impl<T: ?Sized, A: Allocator> !Send for Weak<T, A> {}
3221#[stable(feature = "rc_weak", since = "1.4.0")]
3222impl<T: ?Sized, A: Allocator> !Sync for Weak<T, A> {}
3223
3224#[unstable(feature = "coerce_unsized", issue = "18598")]
3225impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Weak<U, A>> for Weak<T, A> {}
3226
3227#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3228impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
3229
3230// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned.
3231#[unstable(feature = "cell_get_cloned", issue = "145329")]
3232unsafe impl<T: ?Sized> CloneFromCell for Weak<T> {}
3233
3234impl<T> Weak<T> {
3235    /// Constructs a new `Weak<T>`, without allocating any memory.
3236    /// Calling [`upgrade`] on the return value always gives [`None`].
3237    ///
3238    /// [`upgrade`]: Weak::upgrade
3239    ///
3240    /// # Examples
3241    ///
3242    /// ```
3243    /// use std::rc::Weak;
3244    ///
3245    /// let empty: Weak<i64> = Weak::new();
3246    /// assert!(empty.upgrade().is_none());
3247    /// ```
3248    #[inline]
3249    #[stable(feature = "downgraded_weak", since = "1.10.0")]
3250    #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")]
3251    #[must_use]
3252    pub const fn new() -> Weak<T> {
3253        Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global }
3254    }
3255}
3256
3257impl<T, A: Allocator> Weak<T, A> {
3258    /// Constructs a new `Weak<T>`, without allocating any memory, technically in the provided
3259    /// allocator.
3260    /// Calling [`upgrade`] on the return value always gives [`None`].
3261    ///
3262    /// [`upgrade`]: Weak::upgrade
3263    ///
3264    /// # Examples
3265    ///
3266    /// ```
3267    /// use std::rc::Weak;
3268    ///
3269    /// let empty: Weak<i64> = Weak::new();
3270    /// assert!(empty.upgrade().is_none());
3271    /// ```
3272    #[inline]
3273    #[unstable(feature = "allocator_api", issue = "32838")]
3274    pub fn new_in(alloc: A) -> Weak<T, A> {
3275        Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc }
3276    }
3277}
3278
3279pub(crate) fn is_dangling<T: ?Sized>(ptr: *const T) -> bool {
3280    (ptr.cast::<()>()).addr() == usize::MAX
3281}
3282
3283/// Helper type to allow accessing the reference counts without
3284/// making any assertions about the data field.
3285struct WeakInner<'a> {
3286    weak: &'a Cell<usize>,
3287    strong: &'a Cell<usize>,
3288}
3289
3290impl<T: ?Sized> Weak<T> {
3291    /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3292    ///
3293    /// This can be used to safely get a strong reference (by calling [`upgrade`]
3294    /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3295    ///
3296    /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3297    /// as these don't own anything; the method still works on them).
3298    ///
3299    /// # Safety
3300    ///
3301    /// The pointer must have originated from the [`into_raw`] and must still own its potential
3302    /// weak reference, and `ptr` must point to a block of memory allocated by the global allocator.
3303    ///
3304    /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3305    /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3306    /// count is not modified by this operation) and therefore it must be paired with a previous
3307    /// call to [`into_raw`].
3308    ///
3309    /// # Examples
3310    ///
3311    /// ```
3312    /// use std::rc::{Rc, Weak};
3313    ///
3314    /// let strong = Rc::new("hello".to_owned());
3315    ///
3316    /// let raw_1 = Rc::downgrade(&strong).into_raw();
3317    /// let raw_2 = Rc::downgrade(&strong).into_raw();
3318    ///
3319    /// assert_eq!(2, Rc::weak_count(&strong));
3320    ///
3321    /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3322    /// assert_eq!(1, Rc::weak_count(&strong));
3323    ///
3324    /// drop(strong);
3325    ///
3326    /// // Decrement the last weak count.
3327    /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3328    /// ```
3329    ///
3330    /// [`into_raw`]: Weak::into_raw
3331    /// [`upgrade`]: Weak::upgrade
3332    /// [`new`]: Weak::new
3333    #[inline]
3334    #[stable(feature = "weak_into_raw", since = "1.45.0")]
3335    pub unsafe fn from_raw(ptr: *const T) -> Self {
3336        unsafe { Self::from_raw_in(ptr, Global) }
3337    }
3338
3339    /// Consumes the `Weak<T>` and turns it into a raw pointer.
3340    ///
3341    /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3342    /// one weak reference (the weak count is not modified by this operation). It can be turned
3343    /// back into the `Weak<T>` with [`from_raw`].
3344    ///
3345    /// The same restrictions of accessing the target of the pointer as with
3346    /// [`as_ptr`] apply.
3347    ///
3348    /// # Examples
3349    ///
3350    /// ```
3351    /// use std::rc::{Rc, Weak};
3352    ///
3353    /// let strong = Rc::new("hello".to_owned());
3354    /// let weak = Rc::downgrade(&strong);
3355    /// let raw = weak.into_raw();
3356    ///
3357    /// assert_eq!(1, Rc::weak_count(&strong));
3358    /// assert_eq!("hello", unsafe { &*raw });
3359    ///
3360    /// drop(unsafe { Weak::from_raw(raw) });
3361    /// assert_eq!(0, Rc::weak_count(&strong));
3362    /// ```
3363    ///
3364    /// [`from_raw`]: Weak::from_raw
3365    /// [`as_ptr`]: Weak::as_ptr
3366    #[must_use = "losing the pointer will leak memory"]
3367    #[stable(feature = "weak_into_raw", since = "1.45.0")]
3368    pub fn into_raw(self) -> *const T {
3369        mem::ManuallyDrop::new(self).as_ptr()
3370    }
3371}
3372
3373impl<T: ?Sized, A: Allocator> Weak<T, A> {
3374    /// Returns a reference to the underlying allocator.
3375    #[inline]
3376    #[unstable(feature = "allocator_api", issue = "32838")]
3377    pub fn allocator(&self) -> &A {
3378        &self.alloc
3379    }
3380
3381    /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
3382    ///
3383    /// The pointer is valid only if there are some strong references. The pointer may be dangling,
3384    /// unaligned or even [`null`] otherwise.
3385    ///
3386    /// # Examples
3387    ///
3388    /// ```
3389    /// use std::rc::Rc;
3390    /// use std::ptr;
3391    ///
3392    /// let strong = Rc::new("hello".to_owned());
3393    /// let weak = Rc::downgrade(&strong);
3394    /// // Both point to the same object
3395    /// assert!(ptr::eq(&*strong, weak.as_ptr()));
3396    /// // The strong here keeps it alive, so we can still access the object.
3397    /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
3398    ///
3399    /// drop(strong);
3400    /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
3401    /// // undefined behavior.
3402    /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
3403    /// ```
3404    ///
3405    /// [`null`]: ptr::null
3406    #[must_use]
3407    #[stable(feature = "rc_as_ptr", since = "1.45.0")]
3408    pub fn as_ptr(&self) -> *const T {
3409        let ptr: *mut RcInner<T> = NonNull::as_ptr(self.ptr);
3410
3411        if is_dangling(ptr) {
3412            // If the pointer is dangling, we return the sentinel directly. This cannot be
3413            // a valid payload address, as the payload is at least as aligned as RcInner (usize).
3414            ptr as *const T
3415        } else {
3416            // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
3417            // The payload may be dropped at this point, and we have to maintain provenance,
3418            // so use raw pointer manipulation.
3419            unsafe { &raw mut (*ptr).value }
3420        }
3421    }
3422
3423    /// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
3424    ///
3425    /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3426    /// one weak reference (the weak count is not modified by this operation). It can be turned
3427    /// back into the `Weak<T>` with [`from_raw_in`].
3428    ///
3429    /// The same restrictions of accessing the target of the pointer as with
3430    /// [`as_ptr`] apply.
3431    ///
3432    /// # Examples
3433    ///
3434    /// ```
3435    /// #![feature(allocator_api)]
3436    /// use std::rc::{Rc, Weak};
3437    /// use std::alloc::System;
3438    ///
3439    /// let strong = Rc::new_in("hello".to_owned(), System);
3440    /// let weak = Rc::downgrade(&strong);
3441    /// let (raw, alloc) = weak.into_raw_with_allocator();
3442    ///
3443    /// assert_eq!(1, Rc::weak_count(&strong));
3444    /// assert_eq!("hello", unsafe { &*raw });
3445    ///
3446    /// drop(unsafe { Weak::from_raw_in(raw, alloc) });
3447    /// assert_eq!(0, Rc::weak_count(&strong));
3448    /// ```
3449    ///
3450    /// [`from_raw_in`]: Weak::from_raw_in
3451    /// [`as_ptr`]: Weak::as_ptr
3452    #[must_use = "losing the pointer will leak memory"]
3453    #[inline]
3454    #[unstable(feature = "allocator_api", issue = "32838")]
3455    pub fn into_raw_with_allocator(self) -> (*const T, A) {
3456        let this = mem::ManuallyDrop::new(self);
3457        let result = this.as_ptr();
3458        // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
3459        let alloc = unsafe { ptr::read(&this.alloc) };
3460        (result, alloc)
3461    }
3462
3463    /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3464    ///
3465    /// This can be used to safely get a strong reference (by calling [`upgrade`]
3466    /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3467    ///
3468    /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3469    /// as these don't own anything; the method still works on them).
3470    ///
3471    /// # Safety
3472    ///
3473    /// The pointer must have originated from the [`into_raw`] and must still own its potential
3474    /// weak reference, and `ptr` must point to a block of memory allocated by `alloc`.
3475    ///
3476    /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3477    /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3478    /// count is not modified by this operation) and therefore it must be paired with a previous
3479    /// call to [`into_raw`].
3480    ///
3481    /// # Examples
3482    ///
3483    /// ```
3484    /// use std::rc::{Rc, Weak};
3485    ///
3486    /// let strong = Rc::new("hello".to_owned());
3487    ///
3488    /// let raw_1 = Rc::downgrade(&strong).into_raw();
3489    /// let raw_2 = Rc::downgrade(&strong).into_raw();
3490    ///
3491    /// assert_eq!(2, Rc::weak_count(&strong));
3492    ///
3493    /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3494    /// assert_eq!(1, Rc::weak_count(&strong));
3495    ///
3496    /// drop(strong);
3497    ///
3498    /// // Decrement the last weak count.
3499    /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3500    /// ```
3501    ///
3502    /// [`into_raw`]: Weak::into_raw
3503    /// [`upgrade`]: Weak::upgrade
3504    /// [`new`]: Weak::new
3505    #[inline]
3506    #[unstable(feature = "allocator_api", issue = "32838")]
3507    pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
3508        // See Weak::as_ptr for context on how the input pointer is derived.
3509
3510        let ptr = if is_dangling(ptr) {
3511            // This is a dangling Weak.
3512            ptr as *mut RcInner<T>
3513        } else {
3514            // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
3515            // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
3516            let offset = unsafe { data_offset(ptr) };
3517            // Thus, we reverse the offset to get the whole RcInner.
3518            // SAFETY: the pointer originated from a Weak, so this offset is safe.
3519            unsafe { ptr.byte_sub(offset) as *mut RcInner<T> }
3520        };
3521
3522        // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
3523        Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc }
3524    }
3525
3526    /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
3527    /// dropping of the inner value if successful.
3528    ///
3529    /// Returns [`None`] in the following cases:
3530    ///
3531    /// 1. The inner value has since been dropped or moved out.
3532    ///
3533    /// 2. This `Weak` does not point to an allocation.
3534    ///
3535    /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade.
3536    ///
3537    /// # Examples
3538    ///
3539    /// ```
3540    /// use std::rc::Rc;
3541    ///
3542    /// let five = Rc::new(5);
3543    ///
3544    /// let weak_five = Rc::downgrade(&five);
3545    ///
3546    /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
3547    /// assert!(strong_five.is_some());
3548    ///
3549    /// // Destroy all strong pointers.
3550    /// drop(strong_five);
3551    /// drop(five);
3552    ///
3553    /// assert!(weak_five.upgrade().is_none());
3554    /// ```
3555    #[must_use = "this returns a new `Rc`, \
3556                  without modifying the original weak pointer"]
3557    #[stable(feature = "rc_weak", since = "1.4.0")]
3558    pub fn upgrade(&self) -> Option<Rc<T, A>>
3559    where
3560        A: AllocatorClone,
3561    {
3562        let inner = self.inner()?;
3563
3564        if inner.strong() == 0 {
3565            None
3566        } else {
3567            unsafe {
3568                inner.inc_strong();
3569                Some(Rc::from_inner_in(self.ptr, self.alloc.clone()))
3570            }
3571        }
3572    }
3573
3574    /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
3575    ///
3576    /// If `self` was created using [`Weak::new`], this will return 0.
3577    #[must_use]
3578    #[stable(feature = "weak_counts", since = "1.41.0")]
3579    pub fn strong_count(&self) -> usize {
3580        if let Some(inner) = self.inner() { inner.strong() } else { 0 }
3581    }
3582
3583    /// Gets the number of `Weak` pointers pointing to this allocation.
3584    ///
3585    /// If no strong pointers remain, this will return zero.
3586    #[must_use]
3587    #[stable(feature = "weak_counts", since = "1.41.0")]
3588    pub fn weak_count(&self) -> usize {
3589        if let Some(inner) = self.inner() {
3590            if inner.strong() > 0 {
3591                inner.weak() - 1 // subtract the implicit weak ptr
3592            } else {
3593                0
3594            }
3595        } else {
3596            0
3597        }
3598    }
3599
3600    /// Returns `None` when the pointer is dangling and there is no allocated `RcInner`,
3601    /// (i.e., when this `Weak` was created by `Weak::new`).
3602    #[inline]
3603    fn inner(&self) -> Option<WeakInner<'_>> {
3604        if is_dangling(self.ptr.as_ptr()) {
3605            None
3606        } else {
3607            // We are careful to *not* create a reference covering the "data" field, as
3608            // the field may be mutated concurrently (for example, if the last `Rc`
3609            // is dropped, the data field will be dropped in-place).
3610            Some(unsafe {
3611                let ptr = self.ptr.as_ptr();
3612                WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
3613            })
3614        }
3615    }
3616
3617    /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
3618    /// both don't point to any allocation (because they were created with `Weak::new()`). However,
3619    /// this function ignores the metadata of  `dyn Trait` pointers.
3620    ///
3621    /// # Notes
3622    ///
3623    /// Since this compares pointers it means that `Weak::new()` will equal each
3624    /// other, even though they don't point to any allocation.
3625    ///
3626    /// # Examples
3627    ///
3628    /// ```
3629    /// use std::rc::Rc;
3630    ///
3631    /// let first_rc = Rc::new(5);
3632    /// let first = Rc::downgrade(&first_rc);
3633    /// let second = Rc::downgrade(&first_rc);
3634    ///
3635    /// assert!(first.ptr_eq(&second));
3636    ///
3637    /// let third_rc = Rc::new(5);
3638    /// let third = Rc::downgrade(&third_rc);
3639    ///
3640    /// assert!(!first.ptr_eq(&third));
3641    /// ```
3642    ///
3643    /// Comparing `Weak::new`.
3644    ///
3645    /// ```
3646    /// use std::rc::{Rc, Weak};
3647    ///
3648    /// let first = Weak::new();
3649    /// let second = Weak::new();
3650    /// assert!(first.ptr_eq(&second));
3651    ///
3652    /// let third_rc = Rc::new(());
3653    /// let third = Rc::downgrade(&third_rc);
3654    /// assert!(!first.ptr_eq(&third));
3655    /// ```
3656    #[inline]
3657    #[must_use]
3658    #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
3659    pub fn ptr_eq(&self, other: &Self) -> bool {
3660        ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr())
3661    }
3662}
3663
3664#[stable(feature = "rc_weak", since = "1.4.0")]
3665unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak<T, A> {
3666    /// Drops the `Weak` pointer.
3667    ///
3668    /// # Examples
3669    ///
3670    /// ```
3671    /// use std::rc::{Rc, Weak};
3672    ///
3673    /// struct Foo;
3674    ///
3675    /// impl Drop for Foo {
3676    ///     fn drop(&mut self) {
3677    ///         println!("dropped!");
3678    ///     }
3679    /// }
3680    ///
3681    /// let foo = Rc::new(Foo);
3682    /// let weak_foo = Rc::downgrade(&foo);
3683    /// let other_weak_foo = Weak::clone(&weak_foo);
3684    ///
3685    /// drop(weak_foo);   // Doesn't print anything
3686    /// drop(foo);        // Prints "dropped!"
3687    ///
3688    /// assert!(other_weak_foo.upgrade().is_none());
3689    /// ```
3690    fn drop(&mut self) {
3691        let inner = if let Some(inner) = self.inner() { inner } else { return };
3692
3693        inner.dec_weak();
3694        // the weak count starts at 1, and will only go to zero if all
3695        // the strong pointers have disappeared.
3696        if inner.weak() == 0 {
3697            unsafe {
3698                self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
3699            }
3700        }
3701    }
3702}
3703
3704#[stable(feature = "rc_weak", since = "1.4.0")]
3705impl<T: ?Sized, A: AllocatorClone> Clone for Weak<T, A> {
3706    /// Makes a clone of the `Weak` pointer that points to the same allocation.
3707    ///
3708    /// # Examples
3709    ///
3710    /// ```
3711    /// use std::rc::{Rc, Weak};
3712    ///
3713    /// let weak_five = Rc::downgrade(&Rc::new(5));
3714    ///
3715    /// let _ = Weak::clone(&weak_five);
3716    /// ```
3717    #[inline]
3718    fn clone(&self) -> Weak<T, A> {
3719        if let Some(inner) = self.inner() {
3720            inner.inc_weak()
3721        }
3722        Weak { ptr: self.ptr, alloc: self.alloc.clone() }
3723    }
3724}
3725
3726#[unstable(feature = "ergonomic_clones", issue = "132290")]
3727impl<T: ?Sized, A: AllocatorClone> UseCloned for Weak<T, A> {}
3728
3729#[stable(feature = "rc_weak", since = "1.4.0")]
3730impl<T: ?Sized, A: Allocator> fmt::Debug for Weak<T, A> {
3731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3732        write!(f, "(Weak)")
3733    }
3734}
3735
3736#[stable(feature = "downgraded_weak", since = "1.10.0")]
3737impl<T> Default for Weak<T> {
3738    /// Constructs a new `Weak<T>`, without allocating any memory.
3739    /// Calling [`upgrade`] on the return value always gives [`None`].
3740    ///
3741    /// [`upgrade`]: Weak::upgrade
3742    ///
3743    /// # Examples
3744    ///
3745    /// ```
3746    /// use std::rc::Weak;
3747    ///
3748    /// let empty: Weak<i64> = Default::default();
3749    /// assert!(empty.upgrade().is_none());
3750    /// ```
3751    fn default() -> Weak<T> {
3752        Weak::new()
3753    }
3754}
3755
3756// NOTE: If you mem::forget Rcs (or Weaks), drop is skipped and the ref-count
3757// is not decremented, meaning the ref-count can overflow, and then you can
3758// free the allocation while outstanding Rcs (or Weaks) exist, which would be
3759// unsound. We abort because this is such a degenerate scenario that we don't
3760// care about what happens -- no real program should ever experience this.
3761//
3762// This should have negligible overhead since you don't actually need to
3763// clone these much in Rust thanks to ownership and move-semantics.
3764
3765#[doc(hidden)]
3766trait RcInnerPtr {
3767    fn weak_ref(&self) -> &Cell<usize>;
3768    fn strong_ref(&self) -> &Cell<usize>;
3769
3770    #[inline]
3771    fn strong(&self) -> usize {
3772        self.strong_ref().get()
3773    }
3774
3775    #[inline]
3776    fn inc_strong(&self) {
3777        let strong = self.strong();
3778
3779        // We insert an `assume` here to hint LLVM at an otherwise
3780        // missed optimization.
3781        // SAFETY: The reference count will never be zero when this is
3782        // called.
3783        unsafe {
3784            hint::assert_unchecked(strong != 0);
3785        }
3786
3787        let strong = strong.wrapping_add(1);
3788        self.strong_ref().set(strong);
3789
3790        // We want to abort on overflow instead of dropping the value.
3791        // Checking for overflow after the store instead of before
3792        // allows for slightly better code generation.
3793        if core::intrinsics::unlikely(strong == 0) {
3794            abort();
3795        }
3796    }
3797
3798    #[inline]
3799    fn dec_strong(&self) {
3800        self.strong_ref().set(self.strong() - 1);
3801    }
3802
3803    #[inline]
3804    fn weak(&self) -> usize {
3805        self.weak_ref().get()
3806    }
3807
3808    #[inline]
3809    fn inc_weak(&self) {
3810        let weak = self.weak();
3811
3812        // We insert an `assume` here to hint LLVM at an otherwise
3813        // missed optimization.
3814        // SAFETY: The reference count will never be zero when this is
3815        // called.
3816        unsafe {
3817            hint::assert_unchecked(weak != 0);
3818        }
3819
3820        let weak = weak.wrapping_add(1);
3821        self.weak_ref().set(weak);
3822
3823        // We want to abort on overflow instead of dropping the value.
3824        // Checking for overflow after the store instead of before
3825        // allows for slightly better code generation.
3826        if core::intrinsics::unlikely(weak == 0) {
3827            abort();
3828        }
3829    }
3830
3831    #[inline]
3832    fn dec_weak(&self) {
3833        self.weak_ref().set(self.weak() - 1);
3834    }
3835}
3836
3837impl<T: ?Sized> RcInnerPtr for RcInner<T> {
3838    #[inline(always)]
3839    fn weak_ref(&self) -> &Cell<usize> {
3840        &self.weak
3841    }
3842
3843    #[inline(always)]
3844    fn strong_ref(&self) -> &Cell<usize> {
3845        &self.strong
3846    }
3847}
3848
3849impl<'a> RcInnerPtr for WeakInner<'a> {
3850    #[inline(always)]
3851    fn weak_ref(&self) -> &Cell<usize> {
3852        self.weak
3853    }
3854
3855    #[inline(always)]
3856    fn strong_ref(&self) -> &Cell<usize> {
3857        self.strong
3858    }
3859}
3860
3861#[stable(feature = "rust1", since = "1.0.0")]
3862impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Rc<T, A> {
3863    fn borrow(&self) -> &T {
3864        self
3865    }
3866}
3867
3868#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
3869impl<T: ?Sized, A: Allocator> AsRef<T> for Rc<T, A> {
3870    fn as_ref(&self) -> &T {
3871        self
3872    }
3873}
3874
3875#[stable(feature = "pin", since = "1.33.0")]
3876impl<T: ?Sized, A: Allocator> Unpin for Rc<T, A> {}
3877
3878/// Gets the offset within an `RcInner` for the payload behind a pointer.
3879///
3880/// # Safety
3881///
3882/// The pointer must point to (and have valid metadata for) a previously
3883/// valid instance of T, but the T is allowed to be dropped.
3884unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
3885    // Align the unsized value to the end of the RcInner.
3886    // Because RcInner is repr(C), it will always be the last field in memory.
3887    // SAFETY: since the only unsized types possible are slices, trait objects,
3888    // and extern types, the input safety requirement is currently enough to
3889    // satisfy the requirements of Alignment::of_val_raw; this is an implementation
3890    // detail of the language that must not be relied upon outside of std.
3891    unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) }
3892}
3893
3894#[inline]
3895fn data_offset_alignment(alignment: Alignment) -> usize {
3896    let layout = Layout::new::<RcInner<()>>();
3897    layout.size() + layout.padding_needed_for(alignment)
3898}
3899
3900/// A uniquely owned [`Rc`].
3901///
3902/// This represents an `Rc` that is known to be uniquely owned -- that is, have exactly one strong
3903/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
3904/// references will fail unless the `UniqueRc` they point to has been converted into a regular `Rc`.
3905///
3906/// Because they are uniquely owned, the contents of a `UniqueRc` can be freely mutated. A common
3907/// use case is to have an object be mutable during its initialization phase but then have it become
3908/// immutable and converted to a normal `Rc`.
3909///
3910/// This can be used as a flexible way to create cyclic data structures, as in the example below.
3911///
3912/// ```
3913/// #![feature(unique_rc_arc)]
3914/// use std::rc::{Rc, Weak, UniqueRc};
3915///
3916/// struct Gadget {
3917///     #[allow(dead_code)]
3918///     me: Weak<Gadget>,
3919/// }
3920///
3921/// fn create_gadget() -> Option<Rc<Gadget>> {
3922///     let mut rc = UniqueRc::new(Gadget {
3923///         me: Weak::new(),
3924///     });
3925///     rc.me = UniqueRc::downgrade(&rc);
3926///     Some(UniqueRc::into_rc(rc))
3927/// }
3928///
3929/// create_gadget().unwrap();
3930/// ```
3931///
3932/// An advantage of using `UniqueRc` over [`Rc::new_cyclic`] to build cyclic data structures is that
3933/// [`Rc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
3934/// previous example, `UniqueRc` allows for more flexibility in the construction of cyclic data,
3935/// including fallible or async constructors.
3936#[unstable(feature = "unique_rc_arc", issue = "112566")]
3937pub struct UniqueRc<
3938    T: ?Sized,
3939    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3940> {
3941    ptr: NonNull<RcInner<T>>,
3942    // Define the ownership of `RcInner<T>` for drop-check
3943    _marker: PhantomData<RcInner<T>>,
3944    // Invariance is necessary for soundness: once other `Weak`
3945    // references exist, we already have a form of shared mutability!
3946    _marker2: PhantomData<*mut T>,
3947    alloc: A,
3948}
3949
3950// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3951// but having an explicit negative impl is nice for documentation purposes
3952// and results in nicer error messages.
3953#[unstable(feature = "unique_rc_arc", issue = "112566")]
3954impl<T: ?Sized, A: Allocator> !Send for UniqueRc<T, A> {}
3955
3956// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3957// but having an explicit negative impl is nice for documentation purposes
3958// and results in nicer error messages.
3959#[unstable(feature = "unique_rc_arc", issue = "112566")]
3960impl<T: ?Sized, A: Allocator> !Sync for UniqueRc<T, A> {}
3961
3962#[unstable(feature = "unique_rc_arc", issue = "112566")]
3963impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueRc<U, A>>
3964    for UniqueRc<T, A>
3965{
3966}
3967
3968//#[unstable(feature = "unique_rc_arc", issue = "112566")]
3969#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3970impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<UniqueRc<U>> for UniqueRc<T> {}
3971
3972#[unstable(feature = "unique_rc_arc", issue = "112566")]
3973impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for UniqueRc<T, A> {
3974    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3975        fmt::Display::fmt(&**self, f)
3976    }
3977}
3978
3979#[unstable(feature = "unique_rc_arc", issue = "112566")]
3980impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for UniqueRc<T, A> {
3981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3982        fmt::Debug::fmt(&**self, f)
3983    }
3984}
3985
3986#[unstable(feature = "unique_rc_arc", issue = "112566")]
3987impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueRc<T, A> {
3988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3989        fmt::Pointer::fmt(&(&raw const **self), f)
3990    }
3991}
3992
3993#[unstable(feature = "unique_rc_arc", issue = "112566")]
3994impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueRc<T, A> {
3995    fn borrow(&self) -> &T {
3996        self
3997    }
3998}
3999
4000#[unstable(feature = "unique_rc_arc", issue = "112566")]
4001impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueRc<T, A> {
4002    fn borrow_mut(&mut self) -> &mut T {
4003        self
4004    }
4005}
4006
4007#[unstable(feature = "unique_rc_arc", issue = "112566")]
4008impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueRc<T, A> {
4009    fn as_ref(&self) -> &T {
4010        self
4011    }
4012}
4013
4014#[unstable(feature = "unique_rc_arc", issue = "112566")]
4015impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueRc<T, A> {
4016    fn as_mut(&mut self) -> &mut T {
4017        self
4018    }
4019}
4020
4021#[unstable(feature = "unique_rc_arc", issue = "112566")]
4022impl<T: ?Sized, A: Allocator> Unpin for UniqueRc<T, A> {}
4023
4024#[cfg(not(no_global_oom_handling))]
4025#[unstable(feature = "unique_rc_arc", issue = "112566")]
4026impl<T> From<T> for UniqueRc<T> {
4027    #[inline(always)]
4028    fn from(value: T) -> Self {
4029        Self::new(value)
4030    }
4031}
4032
4033#[unstable(feature = "unique_rc_arc", issue = "112566")]
4034impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for UniqueRc<T, A> {
4035    /// Equality for two `UniqueRc`s.
4036    ///
4037    /// Two `UniqueRc`s are equal if their inner values are equal.
4038    ///
4039    /// # Examples
4040    ///
4041    /// ```
4042    /// #![feature(unique_rc_arc)]
4043    /// use std::rc::UniqueRc;
4044    ///
4045    /// let five = UniqueRc::new(5);
4046    ///
4047    /// assert!(five == UniqueRc::new(5));
4048    /// ```
4049    #[inline]
4050    fn eq(&self, other: &Self) -> bool {
4051        PartialEq::eq(&**self, &**other)
4052    }
4053
4054    /// Inequality for two `UniqueRc`s.
4055    ///
4056    /// Two `UniqueRc`s are not equal if their inner values are not equal.
4057    ///
4058    /// # Examples
4059    ///
4060    /// ```
4061    /// #![feature(unique_rc_arc)]
4062    /// use std::rc::UniqueRc;
4063    ///
4064    /// let five = UniqueRc::new(5);
4065    ///
4066    /// assert!(five != UniqueRc::new(6));
4067    /// ```
4068    #[inline]
4069    fn ne(&self, other: &Self) -> bool {
4070        PartialEq::ne(&**self, &**other)
4071    }
4072}
4073
4074#[unstable(feature = "unique_rc_arc", issue = "112566")]
4075impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for UniqueRc<T, A> {
4076    /// Partial comparison for two `UniqueRc`s.
4077    ///
4078    /// The two are compared by calling `partial_cmp()` on their inner values.
4079    ///
4080    /// # Examples
4081    ///
4082    /// ```
4083    /// #![feature(unique_rc_arc)]
4084    /// use std::rc::UniqueRc;
4085    /// use std::cmp::Ordering;
4086    ///
4087    /// let five = UniqueRc::new(5);
4088    ///
4089    /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueRc::new(6)));
4090    /// ```
4091    #[inline(always)]
4092    fn partial_cmp(&self, other: &UniqueRc<T, A>) -> Option<Ordering> {
4093        (**self).partial_cmp(&**other)
4094    }
4095
4096    /// Less-than comparison for two `UniqueRc`s.
4097    ///
4098    /// The two are compared by calling `<` on their inner values.
4099    ///
4100    /// # Examples
4101    ///
4102    /// ```
4103    /// #![feature(unique_rc_arc)]
4104    /// use std::rc::UniqueRc;
4105    ///
4106    /// let five = UniqueRc::new(5);
4107    ///
4108    /// assert!(five < UniqueRc::new(6));
4109    /// ```
4110    #[inline(always)]
4111    fn lt(&self, other: &UniqueRc<T, A>) -> bool {
4112        **self < **other
4113    }
4114
4115    /// 'Less than or equal to' comparison for two `UniqueRc`s.
4116    ///
4117    /// The two are compared by calling `<=` on their inner values.
4118    ///
4119    /// # Examples
4120    ///
4121    /// ```
4122    /// #![feature(unique_rc_arc)]
4123    /// use std::rc::UniqueRc;
4124    ///
4125    /// let five = UniqueRc::new(5);
4126    ///
4127    /// assert!(five <= UniqueRc::new(5));
4128    /// ```
4129    #[inline(always)]
4130    fn le(&self, other: &UniqueRc<T, A>) -> bool {
4131        **self <= **other
4132    }
4133
4134    /// Greater-than comparison for two `UniqueRc`s.
4135    ///
4136    /// The two are compared by calling `>` on their inner values.
4137    ///
4138    /// # Examples
4139    ///
4140    /// ```
4141    /// #![feature(unique_rc_arc)]
4142    /// use std::rc::UniqueRc;
4143    ///
4144    /// let five = UniqueRc::new(5);
4145    ///
4146    /// assert!(five > UniqueRc::new(4));
4147    /// ```
4148    #[inline(always)]
4149    fn gt(&self, other: &UniqueRc<T, A>) -> bool {
4150        **self > **other
4151    }
4152
4153    /// 'Greater than or equal to' comparison for two `UniqueRc`s.
4154    ///
4155    /// The two are compared by calling `>=` on their inner values.
4156    ///
4157    /// # Examples
4158    ///
4159    /// ```
4160    /// #![feature(unique_rc_arc)]
4161    /// use std::rc::UniqueRc;
4162    ///
4163    /// let five = UniqueRc::new(5);
4164    ///
4165    /// assert!(five >= UniqueRc::new(5));
4166    /// ```
4167    #[inline(always)]
4168    fn ge(&self, other: &UniqueRc<T, A>) -> bool {
4169        **self >= **other
4170    }
4171}
4172
4173#[unstable(feature = "unique_rc_arc", issue = "112566")]
4174impl<T: ?Sized + Ord, A: Allocator> Ord for UniqueRc<T, A> {
4175    /// Comparison for two `UniqueRc`s.
4176    ///
4177    /// The two are compared by calling `cmp()` on their inner values.
4178    ///
4179    /// # Examples
4180    ///
4181    /// ```
4182    /// #![feature(unique_rc_arc)]
4183    /// use std::rc::UniqueRc;
4184    /// use std::cmp::Ordering;
4185    ///
4186    /// let five = UniqueRc::new(5);
4187    ///
4188    /// assert_eq!(Ordering::Less, five.cmp(&UniqueRc::new(6)));
4189    /// ```
4190    #[inline]
4191    fn cmp(&self, other: &UniqueRc<T, A>) -> Ordering {
4192        (**self).cmp(&**other)
4193    }
4194}
4195
4196#[unstable(feature = "unique_rc_arc", issue = "112566")]
4197impl<T: ?Sized + Eq, A: Allocator> Eq for UniqueRc<T, A> {}
4198
4199#[unstable(feature = "unique_rc_arc", issue = "112566")]
4200impl<T: ?Sized + Hash, A: Allocator> Hash for UniqueRc<T, A> {
4201    fn hash<H: Hasher>(&self, state: &mut H) {
4202        (**self).hash(state);
4203    }
4204}
4205
4206// Depends on A = Global
4207impl<T> UniqueRc<T> {
4208    /// Creates a new `UniqueRc`.
4209    ///
4210    /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4211    /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4212    /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4213    /// point to the new [`Rc`].
4214    #[cfg(not(no_global_oom_handling))]
4215    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4216    pub fn new(value: T) -> Self {
4217        Self::new_in(value, Global)
4218    }
4219
4220    /// Maps the value in a `UniqueRc`, reusing the allocation if possible.
4221    ///
4222    /// `f` is called on a reference to the value in the `UniqueRc`, and the result is returned,
4223    /// also in a `UniqueRc`.
4224    ///
4225    /// Note: this is an associated function, which means that you have
4226    /// to call it as `UniqueRc::map(u, f)` instead of `u.map(f)`. This
4227    /// is so that there is no conflict with a method on the inner type.
4228    ///
4229    /// # Examples
4230    ///
4231    /// ```
4232    /// #![feature(smart_pointer_try_map)]
4233    /// #![feature(unique_rc_arc)]
4234    ///
4235    /// use std::rc::UniqueRc;
4236    ///
4237    /// let r = UniqueRc::new(7);
4238    /// let new = UniqueRc::map(r, |i| i + 7);
4239    /// assert_eq!(*new, 14);
4240    /// ```
4241    #[cfg(not(no_global_oom_handling))]
4242    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4243    pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> UniqueRc<U> {
4244        if size_of::<T>() == size_of::<U>()
4245            && align_of::<T>() == align_of::<U>()
4246            && UniqueRc::weak_count(&this) == 0
4247        {
4248            unsafe {
4249                let ptr = UniqueRc::into_raw(this);
4250                let value = ptr.read();
4251                let mut allocation = UniqueRc::from_raw(ptr.cast::<mem::MaybeUninit<U>>());
4252
4253                allocation.write(f(value));
4254                allocation.assume_init()
4255            }
4256        } else {
4257            UniqueRc::new(f(UniqueRc::unwrap(this)))
4258        }
4259    }
4260
4261    /// Attempts to map the value in a `UniqueRc`, reusing the allocation if possible.
4262    ///
4263    /// `f` is called on a reference to the value in the `UniqueRc`, and if the operation succeeds,
4264    /// the result is returned, also in a `UniqueRc`.
4265    ///
4266    /// Note: this is an associated function, which means that you have
4267    /// to call it as `UniqueRc::try_map(u, f)` instead of `u.try_map(f)`. This
4268    /// is so that there is no conflict with a method on the inner type.
4269    ///
4270    /// # Examples
4271    ///
4272    /// ```
4273    /// #![feature(smart_pointer_try_map)]
4274    /// #![feature(unique_rc_arc)]
4275    ///
4276    /// use std::rc::UniqueRc;
4277    ///
4278    /// let b = UniqueRc::new(7);
4279    /// let new = UniqueRc::try_map(b, u32::try_from).unwrap();
4280    /// assert_eq!(*new, 7);
4281    /// ```
4282    #[cfg(not(no_global_oom_handling))]
4283    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4284    pub fn try_map<R>(
4285        this: Self,
4286        f: impl FnOnce(T) -> R,
4287    ) -> <R::Residual as Residual<UniqueRc<R::Output>>>::TryType
4288    where
4289        R: Try,
4290        R::Residual: Residual<UniqueRc<R::Output>>,
4291    {
4292        if size_of::<T>() == size_of::<R::Output>()
4293            && align_of::<T>() == align_of::<R::Output>()
4294            && UniqueRc::weak_count(&this) == 0
4295        {
4296            unsafe {
4297                let ptr = UniqueRc::into_raw(this);
4298                let value = ptr.read();
4299                let mut allocation = UniqueRc::from_raw(ptr.cast::<mem::MaybeUninit<R::Output>>());
4300
4301                allocation.write(f(value)?);
4302                try { allocation.assume_init() }
4303            }
4304        } else {
4305            try { UniqueRc::new(f(UniqueRc::unwrap(this))?) }
4306        }
4307    }
4308
4309    #[cfg(not(no_global_oom_handling))]
4310    fn unwrap(this: Self) -> T {
4311        let this = ManuallyDrop::new(this);
4312        let val: T = unsafe { ptr::read(&**this) };
4313
4314        let _weak = Weak { ptr: this.ptr, alloc: Global };
4315
4316        val
4317    }
4318}
4319
4320impl<T: ?Sized> UniqueRc<T> {
4321    #[cfg(not(no_global_oom_handling))]
4322    unsafe fn from_raw(ptr: *const T) -> Self {
4323        let offset = unsafe { data_offset(ptr) };
4324
4325        // Reverse the offset to find the original RcInner.
4326        let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
4327
4328        Self {
4329            ptr: unsafe { NonNull::new_unchecked(rc_ptr) },
4330            _marker: PhantomData,
4331            _marker2: PhantomData,
4332            alloc: Global,
4333        }
4334    }
4335
4336    #[cfg(not(no_global_oom_handling))]
4337    fn into_raw(this: Self) -> *const T {
4338        let this = ManuallyDrop::new(this);
4339        Self::as_ptr(&*this)
4340    }
4341}
4342
4343impl<T, A: Allocator> UniqueRc<T, A> {
4344    /// Creates a new `UniqueRc` in the provided allocator.
4345    ///
4346    /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4347    /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4348    /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4349    /// point to the new [`Rc`].
4350    #[cfg(not(no_global_oom_handling))]
4351    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4352    pub fn new_in(value: T, alloc: A) -> Self {
4353        let (ptr, alloc) = Box::into_unique(Box::new_in(
4354            RcInner {
4355                strong: Cell::new(0),
4356                // keep one weak reference so if all the weak pointers that are created are dropped
4357                // the UniqueRc still stays valid.
4358                weak: Cell::new(1),
4359                value,
4360            },
4361            alloc,
4362        ));
4363        Self { ptr: ptr.into(), _marker: PhantomData, _marker2: PhantomData, alloc }
4364    }
4365}
4366
4367impl<T: ?Sized, A: Allocator> UniqueRc<T, A> {
4368    /// Converts the `UniqueRc` into a regular [`Rc`].
4369    ///
4370    /// This consumes the `UniqueRc` and returns a regular [`Rc`] that contains the `value` that
4371    /// is passed to `into_rc`.
4372    ///
4373    /// Any weak references created before this method is called can now be upgraded to strong
4374    /// references.
4375    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4376    pub fn into_rc(this: Self) -> Rc<T, A> {
4377        let mut this = ManuallyDrop::new(this);
4378
4379        // Move the allocator out.
4380        // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
4381        // a `ManuallyDrop`.
4382        let alloc: A = unsafe { ptr::read(&this.alloc) };
4383
4384        // SAFETY: This pointer was allocated at creation time so we know it is valid.
4385        unsafe {
4386            // Convert our weak reference into a strong reference
4387            this.ptr.as_mut().strong.set(1);
4388            Rc::from_inner_in(this.ptr, alloc)
4389        }
4390    }
4391
4392    #[cfg(not(no_global_oom_handling))]
4393    fn weak_count(this: &Self) -> usize {
4394        this.inner().weak() - 1
4395    }
4396
4397    #[cfg(not(no_global_oom_handling))]
4398    fn inner(&self) -> &RcInner<T> {
4399        // SAFETY: while this UniqueRc is alive we're guaranteed that the inner pointer is valid.
4400        unsafe { self.ptr.as_ref() }
4401    }
4402
4403    #[cfg(not(no_global_oom_handling))]
4404    fn as_ptr(this: &Self) -> *const T {
4405        let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
4406
4407        // SAFETY: This cannot go through Deref::deref or UniqueRc::inner because
4408        // this is required to retain raw/mut provenance such that e.g. `get_mut` can
4409        // write through the pointer after the Rc is recovered through `from_raw`.
4410        unsafe { &raw mut (*ptr).value }
4411    }
4412
4413    #[inline]
4414    #[cfg(not(no_global_oom_handling))]
4415    fn into_inner_with_allocator(this: Self) -> (NonNull<RcInner<T>>, A) {
4416        let this = mem::ManuallyDrop::new(this);
4417        (this.ptr, unsafe { ptr::read(&this.alloc) })
4418    }
4419
4420    #[inline]
4421    #[cfg(not(no_global_oom_handling))]
4422    unsafe fn from_inner_in(ptr: NonNull<RcInner<T>>, alloc: A) -> Self {
4423        Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
4424    }
4425}
4426
4427impl<T: ?Sized, A: AllocatorClone> UniqueRc<T, A> {
4428    /// Creates a new weak reference to the `UniqueRc`.
4429    ///
4430    /// Attempting to upgrade this weak reference will fail before the `UniqueRc` has been converted
4431    /// to a [`Rc`] using [`UniqueRc::into_rc`].
4432    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4433    pub fn downgrade(this: &Self) -> Weak<T, A> {
4434        // SAFETY: This pointer was allocated at creation time and we guarantee that we only have
4435        // one strong reference before converting to a regular Rc.
4436        unsafe {
4437            this.ptr.as_ref().inc_weak();
4438        }
4439        Weak { ptr: this.ptr, alloc: this.alloc.clone() }
4440    }
4441}
4442
4443#[cfg(not(no_global_oom_handling))]
4444impl<T, A: Allocator> UniqueRc<mem::MaybeUninit<T>, A> {
4445    unsafe fn assume_init(self) -> UniqueRc<T, A> {
4446        let (ptr, alloc) = UniqueRc::into_inner_with_allocator(self);
4447        unsafe { UniqueRc::from_inner_in(ptr.cast(), alloc) }
4448    }
4449}
4450
4451#[unstable(feature = "unique_rc_arc", issue = "112566")]
4452impl<T: ?Sized, A: Allocator> Deref for UniqueRc<T, A> {
4453    type Target = T;
4454
4455    fn deref(&self) -> &T {
4456        // SAFETY: This pointer was allocated at creation time so we know it is valid.
4457        unsafe { &self.ptr.as_ref().value }
4458    }
4459}
4460
4461#[unstable(feature = "unique_rc_arc", issue = "112566")]
4462impl<T: ?Sized, A: Allocator> DerefMut for UniqueRc<T, A> {
4463    fn deref_mut(&mut self) -> &mut T {
4464        // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
4465        // have unique ownership and therefore it's safe to make a mutable reference because
4466        // `UniqueRc` owns the only strong reference to itself.
4467        unsafe { &mut (*self.ptr.as_ptr()).value }
4468    }
4469}
4470
4471#[unstable(feature = "unique_rc_arc", issue = "112566")]
4472unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueRc<T, A> {
4473    fn drop(&mut self) {
4474        unsafe {
4475            // destroy the contained object
4476            drop_in_place(DerefMut::deref_mut(self));
4477
4478            // remove the implicit "strong weak" pointer now that we've destroyed the contents.
4479            self.ptr.as_ref().dec_weak();
4480
4481            if self.ptr.as_ref().weak() == 0 {
4482                self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
4483            }
4484        }
4485    }
4486}
4487
4488/// A unique owning pointer to a [`RcInner`] **that does not imply the contents are initialized,**
4489/// but will deallocate it (without dropping the value) when dropped.
4490///
4491/// This is a helper for [`Rc::make_mut()`] to ensure correct cleanup on panic.
4492/// It is nearly a duplicate of `UniqueRc<MaybeUninit<T>, A>` except that it allows `T: !Sized`,
4493/// which `MaybeUninit` does not.
4494struct UniqueRcUninit<T: ?Sized, A: Allocator> {
4495    ptr: NonNull<RcInner<T>>,
4496    layout_for_value: Layout,
4497    alloc: Option<A>,
4498}
4499
4500impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
4501    /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it.
4502    #[cfg(not(no_global_oom_handling))]
4503    fn new(for_value: &T, alloc: A) -> UniqueRcUninit<T, A> {
4504        let layout = Layout::for_value(for_value);
4505        let ptr = unsafe {
4506            Rc::allocate_for_layout(
4507                layout,
4508                |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4509                |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4510            )
4511        };
4512        Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }
4513    }
4514
4515    /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it,
4516    /// returning an error if allocation fails.
4517    fn try_new(for_value: &T, alloc: A) -> Result<UniqueRcUninit<T, A>, AllocError> {
4518        let layout = Layout::for_value(for_value);
4519        let ptr = unsafe {
4520            Rc::try_allocate_for_layout(
4521                layout,
4522                |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4523                |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4524            )?
4525        };
4526        Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) })
4527    }
4528
4529    /// Returns the pointer to be written into to initialize the [`Rc`].
4530    fn data_ptr(&mut self) -> *mut T {
4531        let offset = data_offset_alignment(self.layout_for_value.alignment());
4532        unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T }
4533    }
4534
4535    /// Upgrade this into a normal [`Rc`].
4536    ///
4537    /// # Safety
4538    ///
4539    /// The data must have been initialized (by writing to [`Self::data_ptr()`]).
4540    unsafe fn into_rc(self) -> Rc<T, A> {
4541        let mut this = ManuallyDrop::new(self);
4542        let ptr = this.ptr;
4543        let alloc = this.alloc.take().unwrap();
4544
4545        // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
4546        // for having initialized the data.
4547        unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }
4548    }
4549}
4550
4551impl<T: ?Sized, A: Allocator> Drop for UniqueRcUninit<T, A> {
4552    fn drop(&mut self) {
4553        // SAFETY:
4554        // * new() produced a pointer safe to deallocate.
4555        // * We own the pointer unless into_rc() was called, which forgets us.
4556        unsafe {
4557            self.alloc.take().unwrap().deallocate(
4558                self.ptr.cast(),
4559                rc_inner_layout_for_value_layout(self.layout_for_value),
4560            );
4561        }
4562    }
4563}
4564
4565#[unstable(feature = "allocator_api", issue = "32838")]
4566unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Rc<T, A> {
4567    #[inline]
4568    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4569        (**self).allocate(layout)
4570    }
4571
4572    #[inline]
4573    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4574        (**self).allocate_zeroed(layout)
4575    }
4576
4577    #[inline]
4578    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
4579        // SAFETY: the safety contract must be upheld by the caller
4580        unsafe { (**self).deallocate(ptr, layout) }
4581    }
4582
4583    #[inline]
4584    unsafe fn grow(
4585        &self,
4586        ptr: NonNull<u8>,
4587        old_layout: Layout,
4588        new_layout: Layout,
4589    ) -> Result<NonNull<[u8]>, AllocError> {
4590        // SAFETY: the safety contract must be upheld by the caller
4591        unsafe { (**self).grow(ptr, old_layout, new_layout) }
4592    }
4593
4594    #[inline]
4595    unsafe fn grow_zeroed(
4596        &self,
4597        ptr: NonNull<u8>,
4598        old_layout: Layout,
4599        new_layout: Layout,
4600    ) -> Result<NonNull<[u8]>, AllocError> {
4601        // SAFETY: the safety contract must be upheld by the caller
4602        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
4603    }
4604
4605    #[inline]
4606    unsafe fn shrink(
4607        &self,
4608        ptr: NonNull<u8>,
4609        old_layout: Layout,
4610        new_layout: Layout,
4611    ) -> Result<NonNull<[u8]>, AllocError> {
4612        // SAFETY: the safety contract must be upheld by the caller
4613        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
4614    }
4615}
4616
4617#[unstable(feature = "allocator_api", issue = "32838")]
4618unsafe impl<T: Allocator + ?Sized, A: AllocatorClone> AllocatorClone for Rc<T, A> {}