Skip to main content

alloc/
rc.rs

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