Skip to main content

alloc/
rc.rs

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