Skip to main content

alloc/
rc.rs

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