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