Skip to main content

alloc/
rc.rs

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