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`][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    /// [from_raw_in]: Rc::from_raw_in
1551    ///
1552    /// # Examples
1553    ///
1554    /// ```
1555    /// use std::rc::Rc;
1556    ///
1557    /// let five = Rc::new(5);
1558    ///
1559    /// unsafe {
1560    ///     let ptr = Rc::into_raw(five);
1561    ///     Rc::increment_strong_count(ptr);
1562    ///
1563    ///     let five = Rc::from_raw(ptr);
1564    ///     assert_eq!(2, Rc::strong_count(&five));
1565    /// #   // Prevent leaks for Miri.
1566    /// #   Rc::decrement_strong_count(ptr);
1567    /// }
1568    /// ```
1569    #[inline]
1570    #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1571    pub unsafe fn increment_strong_count(ptr: *const T) {
1572        unsafe { Self::increment_strong_count_in(ptr, Global) }
1573    }
1574
1575    /// Decrements the strong reference count on the `Rc<T>` associated with the
1576    /// provided pointer by one.
1577    ///
1578    /// # Safety
1579    ///
1580    /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1581    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1582    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1583    /// least 1) when invoking this method, and `ptr` must point to a block of memory
1584    /// allocated by the global allocator. This method can be used to release the final `Rc` and
1585    /// backing storage, but **should not** be called after the final `Rc` has been released.
1586    ///
1587    /// [from_raw_in]: Rc::from_raw_in
1588    ///
1589    /// # Examples
1590    ///
1591    /// ```
1592    /// use std::rc::Rc;
1593    ///
1594    /// let five = Rc::new(5);
1595    ///
1596    /// unsafe {
1597    ///     let ptr = Rc::into_raw(five);
1598    ///     Rc::increment_strong_count(ptr);
1599    ///
1600    ///     let five = Rc::from_raw(ptr);
1601    ///     assert_eq!(2, Rc::strong_count(&five));
1602    ///     Rc::decrement_strong_count(ptr);
1603    ///     assert_eq!(1, Rc::strong_count(&five));
1604    /// }
1605    /// ```
1606    #[inline]
1607    #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1608    pub unsafe fn decrement_strong_count(ptr: *const T) {
1609        unsafe { Self::decrement_strong_count_in(ptr, Global) }
1610    }
1611}
1612
1613impl<T: ?Sized, A: Allocator> Rc<T, A> {
1614    /// Returns a reference to the underlying allocator.
1615    ///
1616    /// Note: this is an associated function, which means that you have
1617    /// to call it as `Rc::allocator(&r)` instead of `r.allocator()`. This
1618    /// is so that there is no conflict with a method on the inner type.
1619    #[inline]
1620    #[unstable(feature = "allocator_api", issue = "32838")]
1621    pub fn allocator(this: &Self) -> &A {
1622        &this.alloc
1623    }
1624
1625    /// Consumes the `Rc`, returning the wrapped pointer and allocator.
1626    ///
1627    /// To avoid a memory leak the pointer must be converted back to an `Rc` using
1628    /// [`Rc::from_raw_in`].
1629    ///
1630    /// # Examples
1631    ///
1632    /// ```
1633    /// #![feature(allocator_api)]
1634    /// use std::rc::Rc;
1635    /// use std::alloc::System;
1636    ///
1637    /// let x = Rc::new_in("hello".to_owned(), System);
1638    /// let (ptr, alloc) = Rc::into_raw_with_allocator(x);
1639    /// assert_eq!(unsafe { &*ptr }, "hello");
1640    /// let x = unsafe { Rc::from_raw_in(ptr, alloc) };
1641    /// assert_eq!(&*x, "hello");
1642    /// ```
1643    #[must_use = "losing the pointer will leak memory"]
1644    #[unstable(feature = "allocator_api", issue = "32838")]
1645    pub fn into_raw_with_allocator(this: Self) -> (*const T, A) {
1646        let this = mem::ManuallyDrop::new(this);
1647        let ptr = Self::as_ptr(&this);
1648        // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
1649        let alloc = unsafe { ptr::read(&this.alloc) };
1650        (ptr, alloc)
1651    }
1652
1653    /// Provides a raw pointer to the data.
1654    ///
1655    /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
1656    /// for as long as there are strong counts in the `Rc`.
1657    ///
1658    /// # Examples
1659    ///
1660    /// ```
1661    /// use std::rc::Rc;
1662    ///
1663    /// let x = Rc::new(0);
1664    /// let y = Rc::clone(&x);
1665    /// let x_ptr = Rc::as_ptr(&x);
1666    /// assert_eq!(x_ptr, Rc::as_ptr(&y));
1667    /// assert_eq!(unsafe { *x_ptr }, 0);
1668    /// ```
1669    #[stable(feature = "weak_into_raw", since = "1.45.0")]
1670    #[rustc_never_returns_null_ptr]
1671    pub fn as_ptr(this: &Self) -> *const T {
1672        let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
1673
1674        // SAFETY: This cannot go through Deref::deref or Rc::inner because
1675        // this is required to retain raw/mut provenance such that e.g. `get_mut` can
1676        // write through the pointer after the Rc is recovered through `from_raw`.
1677        unsafe { &raw mut (*ptr).value }
1678    }
1679
1680    /// Constructs an `Rc<T, A>` from a raw pointer in the provided allocator.
1681    ///
1682    /// The raw pointer must have been previously returned by a call to [`Rc<U,
1683    /// A>::into_raw`][into_raw] or [`Rc<U, A>::into_raw_with_allocator`][into_raw_with_allocator].
1684    ///
1685    /// # Safety
1686    ///
1687    /// * Creating a `Rc<T, A>` from a pointer other than one returned from
1688    ///   [`Rc<U, A>::into_raw`][into_raw] or [`Rc<U, A>::into_raw_with_allocator`][into_raw_with_allocator]
1689    ///   is undefined behavior.
1690    /// * If `U` is sized, it must have the same size and alignment as `T`. This
1691    ///   is trivially true if `U` is `T`.
1692    /// * If `U` is unsized, its data pointer must have the same size and
1693    ///   alignment as `T`. This is trivially true if `Rc<U, A>` was constructed
1694    ///   through `Rc<T, A>` and then converted to `Rc<U, A>` through an [unsized
1695    ///   coercion].
1696    /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size
1697    ///   and alignment, this is basically like transmuting references of
1698    ///   different types. See [`mem::transmute`][transmute] for more information
1699    ///   on what restrictions apply in this case.
1700    /// * The raw pointer must point to a block of memory allocated by `alloc`
1701    /// * The user of `from_raw` has to make sure a specific value of `T` is only
1702    ///   dropped once.
1703    ///
1704    /// This function is unsafe because improper use may lead to memory unsafety,
1705    /// even if the returned `Rc<T, A>` is never accessed.
1706    ///
1707    /// [into_raw]: Rc::into_raw
1708    /// [into_raw_with_allocator]: Rc::into_raw_with_allocator
1709    /// [transmute]: core::mem::transmute
1710    /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions
1711    ///
1712    /// # Examples
1713    ///
1714    /// ```
1715    /// #![feature(allocator_api)]
1716    ///
1717    /// use std::rc::Rc;
1718    /// use std::alloc::System;
1719    ///
1720    /// let x = Rc::new_in("hello".to_owned(), System);
1721    /// let (x_ptr, _alloc) = Rc::into_raw_with_allocator(x);
1722    ///
1723    /// unsafe {
1724    ///     // Convert back to an `Rc` to prevent leak.
1725    ///     let x = Rc::from_raw_in(x_ptr, System);
1726    ///     assert_eq!(&*x, "hello");
1727    ///
1728    ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
1729    /// }
1730    ///
1731    /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
1732    /// ```
1733    ///
1734    /// Convert a slice back into its original array:
1735    ///
1736    /// ```
1737    /// #![feature(allocator_api)]
1738    ///
1739    /// use std::rc::Rc;
1740    /// use std::alloc::System;
1741    ///
1742    /// let x: Rc<[u32], _> = Rc::new_in([1, 2, 3], System);
1743    /// let x_ptr: *const [u32] = Rc::into_raw_with_allocator(x).0;
1744    ///
1745    /// unsafe {
1746    ///     let x: Rc<[u32; 3], _> = Rc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System);
1747    ///     assert_eq!(&*x, &[1, 2, 3]);
1748    /// }
1749    /// ```
1750    #[unstable(feature = "allocator_api", issue = "32838")]
1751    pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
1752        let offset = unsafe { data_offset(ptr) };
1753
1754        // Reverse the offset to find the original RcInner.
1755        let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
1756
1757        unsafe { Self::from_ptr_in(rc_ptr, alloc) }
1758    }
1759
1760    /// Creates a new [`Weak`] pointer to this allocation.
1761    ///
1762    /// # Examples
1763    ///
1764    /// ```
1765    /// use std::rc::Rc;
1766    ///
1767    /// let five = Rc::new(5);
1768    ///
1769    /// let weak_five = Rc::downgrade(&five);
1770    /// ```
1771    #[must_use = "this returns a new `Weak` pointer, \
1772                  without modifying the original `Rc`"]
1773    #[stable(feature = "rc_weak", since = "1.4.0")]
1774    pub fn downgrade(this: &Self) -> Weak<T, A>
1775    where
1776        A: Clone,
1777    {
1778        this.inner().inc_weak();
1779        // Make sure we do not create a dangling Weak
1780        debug_assert!(!is_dangling(this.ptr.as_ptr()));
1781        Weak { ptr: this.ptr, alloc: this.alloc.clone() }
1782    }
1783
1784    /// Gets the number of [`Weak`] pointers to this allocation.
1785    ///
1786    /// # Examples
1787    ///
1788    /// ```
1789    /// use std::rc::Rc;
1790    ///
1791    /// let five = Rc::new(5);
1792    /// let _weak_five = Rc::downgrade(&five);
1793    ///
1794    /// assert_eq!(1, Rc::weak_count(&five));
1795    /// ```
1796    #[inline]
1797    #[stable(feature = "rc_counts", since = "1.15.0")]
1798    pub fn weak_count(this: &Self) -> usize {
1799        this.inner().weak() - 1
1800    }
1801
1802    /// Gets the number of strong (`Rc`) pointers to this allocation.
1803    ///
1804    /// # Examples
1805    ///
1806    /// ```
1807    /// use std::rc::Rc;
1808    ///
1809    /// let five = Rc::new(5);
1810    /// let _also_five = Rc::clone(&five);
1811    ///
1812    /// assert_eq!(2, Rc::strong_count(&five));
1813    /// ```
1814    #[inline]
1815    #[stable(feature = "rc_counts", since = "1.15.0")]
1816    pub fn strong_count(this: &Self) -> usize {
1817        this.inner().strong()
1818    }
1819
1820    /// Increments the strong reference count on the `Rc<T>` associated with the
1821    /// provided pointer by one.
1822    ///
1823    /// # Safety
1824    ///
1825    /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1826    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1827    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1828    /// least 1) for the duration of this method, and `ptr` must point to a block of memory
1829    /// allocated by `alloc`.
1830    ///
1831    /// [from_raw_in]: Rc::from_raw_in
1832    ///
1833    /// # Examples
1834    ///
1835    /// ```
1836    /// #![feature(allocator_api)]
1837    ///
1838    /// use std::rc::Rc;
1839    /// use std::alloc::System;
1840    ///
1841    /// let five = Rc::new_in(5, System);
1842    ///
1843    /// unsafe {
1844    ///     let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1845    ///     Rc::increment_strong_count_in(ptr, System);
1846    ///
1847    ///     let five = Rc::from_raw_in(ptr, System);
1848    ///     assert_eq!(2, Rc::strong_count(&five));
1849    /// #   // Prevent leaks for Miri.
1850    /// #   Rc::decrement_strong_count_in(ptr, System);
1851    /// }
1852    /// ```
1853    #[inline]
1854    #[unstable(feature = "allocator_api", issue = "32838")]
1855    pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
1856    where
1857        A: Clone,
1858    {
1859        // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1860        let rc = unsafe { mem::ManuallyDrop::new(Rc::<T, A>::from_raw_in(ptr, alloc)) };
1861        // Now increase refcount, but don't drop new refcount either
1862        let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1863    }
1864
1865    /// Decrements the strong reference count on the `Rc<T>` associated with the
1866    /// provided pointer by one.
1867    ///
1868    /// # Safety
1869    ///
1870    /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the
1871    /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1872    /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1873    /// least 1) when invoking this method, and `ptr` must point to a block of memory
1874    /// allocated by `alloc`. This method can be used to release the final `Rc` and
1875    /// backing storage, but **should not** be called after the final `Rc` has been released.
1876    ///
1877    /// [from_raw_in]: Rc::from_raw_in
1878    ///
1879    /// # Examples
1880    ///
1881    /// ```
1882    /// #![feature(allocator_api)]
1883    ///
1884    /// use std::rc::Rc;
1885    /// use std::alloc::System;
1886    ///
1887    /// let five = Rc::new_in(5, System);
1888    ///
1889    /// unsafe {
1890    ///     let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1891    ///     Rc::increment_strong_count_in(ptr, System);
1892    ///
1893    ///     let five = Rc::from_raw_in(ptr, System);
1894    ///     assert_eq!(2, Rc::strong_count(&five));
1895    ///     Rc::decrement_strong_count_in(ptr, System);
1896    ///     assert_eq!(1, Rc::strong_count(&five));
1897    /// }
1898    /// ```
1899    #[inline]
1900    #[unstable(feature = "allocator_api", issue = "32838")]
1901    pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) {
1902        unsafe { drop(Rc::from_raw_in(ptr, alloc)) };
1903    }
1904
1905    /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1906    /// this allocation.
1907    #[inline]
1908    fn is_unique(this: &Self) -> bool {
1909        Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1910    }
1911
1912    /// Returns a mutable reference into the given `Rc`, if there are
1913    /// no other `Rc` or [`Weak`] pointers to the same allocation.
1914    ///
1915    /// Returns [`None`] otherwise, because it is not safe to
1916    /// mutate a shared value.
1917    ///
1918    /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1919    /// the inner value when there are other `Rc` pointers.
1920    ///
1921    /// [make_mut]: Rc::make_mut
1922    /// [clone]: Clone::clone
1923    ///
1924    /// # Examples
1925    ///
1926    /// ```
1927    /// use std::rc::Rc;
1928    ///
1929    /// let mut x = Rc::new(3);
1930    /// *Rc::get_mut(&mut x).unwrap() = 4;
1931    /// assert_eq!(*x, 4);
1932    ///
1933    /// let _y = Rc::clone(&x);
1934    /// assert!(Rc::get_mut(&mut x).is_none());
1935    /// ```
1936    #[inline]
1937    #[stable(feature = "rc_unique", since = "1.4.0")]
1938    pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1939        if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1940    }
1941
1942    /// Returns a mutable reference into the given `Rc`,
1943    /// without any check.
1944    ///
1945    /// See also [`get_mut`], which is safe and does appropriate checks.
1946    ///
1947    /// [`get_mut`]: Rc::get_mut
1948    ///
1949    /// # Safety
1950    ///
1951    /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
1952    /// they must not be dereferenced or have active borrows for the duration
1953    /// of the returned borrow, and their inner type must be exactly the same as the
1954    /// inner type of this Rc (including lifetimes). This is trivially the case if no
1955    /// such pointers exist, for example immediately after `Rc::new`.
1956    ///
1957    /// # Examples
1958    ///
1959    /// ```
1960    /// #![feature(get_mut_unchecked)]
1961    ///
1962    /// use std::rc::Rc;
1963    ///
1964    /// let mut x = Rc::new(String::new());
1965    /// unsafe {
1966    ///     Rc::get_mut_unchecked(&mut x).push_str("foo")
1967    /// }
1968    /// assert_eq!(*x, "foo");
1969    /// ```
1970    /// Other `Rc` pointers to the same allocation must be to the same type.
1971    /// ```no_run
1972    /// #![feature(get_mut_unchecked)]
1973    ///
1974    /// use std::rc::Rc;
1975    ///
1976    /// let x: Rc<str> = Rc::from("Hello, world!");
1977    /// let mut y: Rc<[u8]> = x.clone().into();
1978    /// unsafe {
1979    ///     // this is Undefined Behavior, because x's inner type is str, not [u8]
1980    ///     Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
1981    /// }
1982    /// println!("{}", &*x); // Invalid UTF-8 in a str
1983    /// ```
1984    /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
1985    /// ```no_run
1986    /// #![feature(get_mut_unchecked)]
1987    ///
1988    /// use std::rc::Rc;
1989    ///
1990    /// let x: Rc<&str> = Rc::new("Hello, world!");
1991    /// {
1992    ///     let s = String::from("Oh, no!");
1993    ///     let mut y: Rc<&str> = x.clone();
1994    ///     unsafe {
1995    ///         // this is Undefined Behavior, because x's inner type
1996    ///         // is &'long str, not &'short str
1997    ///         *Rc::get_mut_unchecked(&mut y) = &s;
1998    ///     }
1999    /// }
2000    /// println!("{}", &*x); // Use-after-free
2001    /// ```
2002    #[inline]
2003    #[unstable(feature = "get_mut_unchecked", issue = "63292")]
2004    pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
2005        // We are careful to *not* create a reference covering the "count" fields, as
2006        // this would conflict with accesses to the reference counts (e.g. by `Weak`).
2007        unsafe { &mut (*this.ptr.as_ptr()).value }
2008    }
2009
2010    #[inline]
2011    #[stable(feature = "ptr_eq", since = "1.17.0")]
2012    /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
2013    /// [`ptr::eq`]. This function ignores the metadata of  `dyn Trait` pointers.
2014    ///
2015    /// # Examples
2016    ///
2017    /// ```
2018    /// use std::rc::Rc;
2019    ///
2020    /// let five = Rc::new(5);
2021    /// let same_five = Rc::clone(&five);
2022    /// let other_five = Rc::new(5);
2023    ///
2024    /// assert!(Rc::ptr_eq(&five, &same_five));
2025    /// assert!(!Rc::ptr_eq(&five, &other_five));
2026    /// ```
2027    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
2028        ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr())
2029    }
2030}
2031
2032#[cfg(not(no_global_oom_handling))]
2033impl<T: ?Sized + CloneToUninit, A: Allocator + Clone> Rc<T, A> {
2034    /// Makes a mutable reference into the given `Rc`.
2035    ///
2036    /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
2037    /// [`clone`] the inner value to a new allocation to ensure unique ownership.  This is also
2038    /// referred to as clone-on-write.
2039    ///
2040    /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
2041    /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
2042    /// be cloned.
2043    ///
2044    /// See also [`get_mut`], which will fail rather than cloning the inner value
2045    /// or disassociating [`Weak`] pointers.
2046    ///
2047    /// [`clone`]: Clone::clone
2048    /// [`get_mut`]: Rc::get_mut
2049    ///
2050    /// # Examples
2051    ///
2052    /// ```
2053    /// use std::rc::Rc;
2054    ///
2055    /// let mut data = Rc::new(5);
2056    ///
2057    /// *Rc::make_mut(&mut data) += 1;         // Won't clone anything
2058    /// let mut other_data = Rc::clone(&data); // Won't clone inner data
2059    /// *Rc::make_mut(&mut data) += 1;         // Clones inner data
2060    /// *Rc::make_mut(&mut data) += 1;         // Won't clone anything
2061    /// *Rc::make_mut(&mut other_data) *= 2;   // Won't clone anything
2062    ///
2063    /// // Now `data` and `other_data` point to different allocations.
2064    /// assert_eq!(*data, 8);
2065    /// assert_eq!(*other_data, 12);
2066    /// ```
2067    ///
2068    /// [`Weak`] pointers will be disassociated:
2069    ///
2070    /// ```
2071    /// use std::rc::Rc;
2072    ///
2073    /// let mut data = Rc::new(75);
2074    /// let weak = Rc::downgrade(&data);
2075    ///
2076    /// assert!(75 == *data);
2077    /// assert!(75 == *weak.upgrade().unwrap());
2078    ///
2079    /// *Rc::make_mut(&mut data) += 1;
2080    ///
2081    /// assert!(76 == *data);
2082    /// assert!(weak.upgrade().is_none());
2083    /// ```
2084    #[inline]
2085    #[stable(feature = "rc_unique", since = "1.4.0")]
2086    pub fn make_mut(this: &mut Self) -> &mut T {
2087        let size_of_val = size_of_val::<T>(&**this);
2088
2089        if Rc::strong_count(this) != 1 {
2090            // Gotta clone the data, there are other Rcs.
2091            *this = Rc::clone_from_ref_in(&**this, this.alloc.clone());
2092        } else if Rc::weak_count(this) != 0 {
2093            // Can just steal the data, all that's left is Weaks
2094
2095            // We don't need panic-protection like the above branch does, but we might as well
2096            // use the same mechanism.
2097            let mut in_progress: UniqueRcUninit<T, A> =
2098                UniqueRcUninit::new(&**this, this.alloc.clone());
2099            unsafe {
2100                // Initialize `in_progress` with move of **this.
2101                // We have to express this in terms of bytes because `T: ?Sized`; there is no
2102                // operation that just copies a value based on its `size_of_val()`.
2103                ptr::copy_nonoverlapping(
2104                    ptr::from_ref(&**this).cast::<u8>(),
2105                    in_progress.data_ptr().cast::<u8>(),
2106                    size_of_val,
2107                );
2108
2109                this.inner().dec_strong();
2110                // Remove implicit strong-weak ref (no need to craft a fake
2111                // Weak here -- we know other Weaks can clean up for us)
2112                this.inner().dec_weak();
2113                // Replace `this` with newly constructed Rc that has the moved data.
2114                ptr::write(this, in_progress.into_rc());
2115            }
2116        }
2117        // This unsafety is ok because we're guaranteed that the pointer
2118        // returned is the *only* pointer that will ever be returned to T. Our
2119        // reference count is guaranteed to be 1 at this point, and we required
2120        // the `Rc<T>` itself to be `mut`, so we're returning the only possible
2121        // reference to the allocation.
2122        unsafe { &mut this.ptr.as_mut().value }
2123    }
2124}
2125
2126impl<T: Clone, A: Allocator> Rc<T, A> {
2127    /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
2128    /// clone.
2129    ///
2130    /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
2131    /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
2132    ///
2133    /// # Examples
2134    ///
2135    /// ```
2136    /// # use std::{ptr, rc::Rc};
2137    /// let inner = String::from("test");
2138    /// let ptr = inner.as_ptr();
2139    ///
2140    /// let rc = Rc::new(inner);
2141    /// let inner = Rc::unwrap_or_clone(rc);
2142    /// // The inner value was not cloned
2143    /// assert!(ptr::eq(ptr, inner.as_ptr()));
2144    ///
2145    /// let rc = Rc::new(inner);
2146    /// let rc2 = rc.clone();
2147    /// let inner = Rc::unwrap_or_clone(rc);
2148    /// // Because there were 2 references, we had to clone the inner value.
2149    /// assert!(!ptr::eq(ptr, inner.as_ptr()));
2150    /// // `rc2` is the last reference, so when we unwrap it we get back
2151    /// // the original `String`.
2152    /// let inner = Rc::unwrap_or_clone(rc2);
2153    /// assert!(ptr::eq(ptr, inner.as_ptr()));
2154    /// ```
2155    #[inline]
2156    #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")]
2157    pub fn unwrap_or_clone(this: Self) -> T {
2158        Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
2159    }
2160}
2161
2162impl<A: Allocator> Rc<dyn Any, A> {
2163    /// Attempts to downcast the `Rc<dyn Any>` to a concrete type.
2164    ///
2165    /// # Examples
2166    ///
2167    /// ```
2168    /// use std::any::Any;
2169    /// use std::rc::Rc;
2170    ///
2171    /// fn print_if_string(value: Rc<dyn Any>) {
2172    ///     if let Ok(string) = value.downcast::<String>() {
2173    ///         println!("String ({}): {}", string.len(), string);
2174    ///     }
2175    /// }
2176    ///
2177    /// let my_string = "Hello World".to_string();
2178    /// print_if_string(Rc::new(my_string));
2179    /// print_if_string(Rc::new(0i8));
2180    /// ```
2181    #[inline]
2182    #[stable(feature = "rc_downcast", since = "1.29.0")]
2183    pub fn downcast<T: Any>(self) -> Result<Rc<T, A>, Self> {
2184        if (*self).is::<T>() {
2185            unsafe {
2186                let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2187                Ok(Rc::from_inner_in(ptr.cast(), alloc))
2188            }
2189        } else {
2190            Err(self)
2191        }
2192    }
2193
2194    /// Downcasts the `Rc<dyn Any>` to a concrete type.
2195    ///
2196    /// For a safe alternative see [`downcast`].
2197    ///
2198    /// # Examples
2199    ///
2200    /// ```
2201    /// #![feature(downcast_unchecked)]
2202    ///
2203    /// use std::any::Any;
2204    /// use std::rc::Rc;
2205    ///
2206    /// let x: Rc<dyn Any> = Rc::new(1_usize);
2207    ///
2208    /// unsafe {
2209    ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2210    /// }
2211    /// ```
2212    ///
2213    /// # Safety
2214    ///
2215    /// The contained value must be of type `T`. Calling this method
2216    /// with the incorrect type is *undefined behavior*.
2217    ///
2218    ///
2219    /// [`downcast`]: Self::downcast
2220    #[inline]
2221    #[unstable(feature = "downcast_unchecked", issue = "90850")]
2222    pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T, A> {
2223        unsafe {
2224            let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2225            Rc::from_inner_in(ptr.cast(), alloc)
2226        }
2227    }
2228}
2229
2230impl<T: ?Sized> Rc<T> {
2231    /// Allocates an `RcInner<T>` with sufficient space for
2232    /// a possibly-unsized inner value where the value has the layout provided.
2233    ///
2234    /// The function `mem_to_rc_inner` is called with the data pointer
2235    /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2236    #[cfg(not(no_global_oom_handling))]
2237    unsafe fn allocate_for_layout(
2238        value_layout: Layout,
2239        allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2240        mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2241    ) -> *mut RcInner<T> {
2242        let layout = rc_inner_layout_for_value_layout(value_layout);
2243        unsafe {
2244            Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rc_inner)
2245                .unwrap_or_else(|_| handle_alloc_error(layout))
2246        }
2247    }
2248
2249    /// Allocates an `RcInner<T>` with sufficient space for
2250    /// a possibly-unsized inner value where the value has the layout provided,
2251    /// returning an error if allocation fails.
2252    ///
2253    /// The function `mem_to_rc_inner` is called with the data pointer
2254    /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2255    #[inline]
2256    unsafe fn try_allocate_for_layout(
2257        value_layout: Layout,
2258        allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2259        mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2260    ) -> Result<*mut RcInner<T>, AllocError> {
2261        let layout = rc_inner_layout_for_value_layout(value_layout);
2262
2263        // Allocate for the layout.
2264        let ptr = allocate(layout)?;
2265
2266        // Initialize the RcInner
2267        let inner = mem_to_rc_inner(ptr.as_non_null_ptr().as_ptr());
2268        unsafe {
2269            debug_assert_eq!(Layout::for_value_raw(inner), layout);
2270
2271            (&raw mut (*inner).strong).write(Cell::new(1));
2272            (&raw mut (*inner).weak).write(Cell::new(1));
2273        }
2274
2275        Ok(inner)
2276    }
2277}
2278
2279impl<T: ?Sized, A: Allocator> Rc<T, A> {
2280    /// Allocates an `RcInner<T>` with sufficient space for an unsized inner value
2281    #[cfg(not(no_global_oom_handling))]
2282    unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut RcInner<T> {
2283        // Allocate for the `RcInner<T>` using the given value.
2284        unsafe {
2285            Rc::<T>::allocate_for_layout(
2286                Layout::for_value_raw(ptr),
2287                |layout| alloc.allocate(layout),
2288                |mem| mem.with_metadata_of(ptr as *const RcInner<T>),
2289            )
2290        }
2291    }
2292
2293    #[cfg(not(no_global_oom_handling))]
2294    fn from_box_in(src: Box<T, A>) -> Rc<T, A> {
2295        unsafe {
2296            let value_size = size_of_val(&*src);
2297            let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src));
2298
2299            // Copy value as bytes
2300            ptr::copy_nonoverlapping(
2301                (&raw const *src) as *const u8,
2302                (&raw mut (*ptr).value) as *mut u8,
2303                value_size,
2304            );
2305
2306            // Free the allocation without dropping its contents
2307            let (bptr, alloc) = Box::into_raw_with_allocator(src);
2308            let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop<T>, alloc.by_ref());
2309            drop(src);
2310
2311            Self::from_ptr_in(ptr, alloc)
2312        }
2313    }
2314}
2315
2316impl<T> Rc<[T]> {
2317    /// Allocates an `RcInner<[T]>` with the given length.
2318    #[cfg(not(no_global_oom_handling))]
2319    unsafe fn allocate_for_slice(len: usize) -> *mut RcInner<[T]> {
2320        unsafe {
2321            Self::allocate_for_layout(
2322                Layout::array::<T>(len).unwrap(),
2323                |layout| Global.allocate(layout),
2324                |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2325            )
2326        }
2327    }
2328
2329    /// Copy elements from slice into newly allocated `Rc<[T]>`
2330    ///
2331    /// Unsafe because the caller must either take ownership, bind `T: Copy` or
2332    /// bind `T: TrivialClone`.
2333    #[cfg(not(no_global_oom_handling))]
2334    unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
2335        unsafe {
2336            let ptr = Self::allocate_for_slice(v.len());
2337            ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).value) as *mut T, v.len());
2338            Self::from_ptr(ptr)
2339        }
2340    }
2341
2342    /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
2343    ///
2344    /// Behavior is undefined should the size be wrong.
2345    #[cfg(not(no_global_oom_handling))]
2346    unsafe fn from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]> {
2347        // Panic guard while cloning T elements.
2348        // In the event of a panic, elements that have been written
2349        // into the new RcInner will be dropped, then the memory freed.
2350        struct Guard<T> {
2351            mem: NonNull<u8>,
2352            elems: *mut T,
2353            layout: Layout,
2354            n_elems: usize,
2355        }
2356
2357        impl<T> Drop for Guard<T> {
2358            fn drop(&mut self) {
2359                unsafe {
2360                    let slice = from_raw_parts_mut(self.elems, self.n_elems);
2361                    ptr::drop_in_place(slice);
2362
2363                    Global.deallocate(self.mem, self.layout);
2364                }
2365            }
2366        }
2367
2368        unsafe {
2369            let ptr = Self::allocate_for_slice(len);
2370
2371            let mem = ptr as *mut _ as *mut u8;
2372            let layout = Layout::for_value_raw(ptr);
2373
2374            // Pointer to first element
2375            let elems = (&raw mut (*ptr).value) as *mut T;
2376
2377            let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
2378
2379            for (i, item) in iter.enumerate() {
2380                ptr::write(elems.add(i), item);
2381                guard.n_elems += 1;
2382            }
2383
2384            // All clear. Forget the guard so it doesn't free the new RcInner.
2385            mem::forget(guard);
2386
2387            Self::from_ptr(ptr)
2388        }
2389    }
2390}
2391
2392impl<T, A: Allocator> Rc<[T], A> {
2393    /// Allocates an `RcInner<[T]>` with the given length.
2394    #[inline]
2395    #[cfg(not(no_global_oom_handling))]
2396    unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut RcInner<[T]> {
2397        unsafe {
2398            Rc::<[T]>::allocate_for_layout(
2399                Layout::array::<T>(len).unwrap(),
2400                |layout| alloc.allocate(layout),
2401                |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2402            )
2403        }
2404    }
2405}
2406
2407#[cfg(not(no_global_oom_handling))]
2408/// Specialization trait used for `From<&[T]>`.
2409trait RcFromSlice<T> {
2410    fn from_slice(slice: &[T]) -> Self;
2411}
2412
2413#[cfg(not(no_global_oom_handling))]
2414impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
2415    #[inline]
2416    default fn from_slice(v: &[T]) -> Self {
2417        unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
2418    }
2419}
2420
2421#[cfg(not(no_global_oom_handling))]
2422impl<T: TrivialClone> RcFromSlice<T> for Rc<[T]> {
2423    #[inline]
2424    fn from_slice(v: &[T]) -> Self {
2425        // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent
2426        // to the above.
2427        unsafe { Rc::copy_from_slice(v) }
2428    }
2429}
2430
2431#[stable(feature = "rust1", since = "1.0.0")]
2432impl<T: ?Sized, A: Allocator> Deref for Rc<T, A> {
2433    type Target = T;
2434
2435    #[inline(always)]
2436    fn deref(&self) -> &T {
2437        &self.inner().value
2438    }
2439}
2440
2441#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2442unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Rc<T, A> {}
2443
2444//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2445#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2446unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for UniqueRc<T, A> {}
2447
2448#[unstable(feature = "deref_pure_trait", issue = "87121")]
2449unsafe impl<T: ?Sized, A: Allocator> DerefPure for Rc<T, A> {}
2450
2451//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2452#[unstable(feature = "deref_pure_trait", issue = "87121")]
2453unsafe impl<T: ?Sized, A: Allocator> DerefPure for UniqueRc<T, A> {}
2454
2455#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2456impl<T: ?Sized> LegacyReceiver for Rc<T> {}
2457
2458#[stable(feature = "rust1", since = "1.0.0")]
2459unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
2460    /// Drops the `Rc`.
2461    ///
2462    /// This will decrement the strong reference count. If the strong reference
2463    /// count reaches zero then the only other references (if any) are
2464    /// [`Weak`], so we `drop` the inner value.
2465    ///
2466    /// # Examples
2467    ///
2468    /// ```
2469    /// use std::rc::Rc;
2470    ///
2471    /// struct Foo;
2472    ///
2473    /// impl Drop for Foo {
2474    ///     fn drop(&mut self) {
2475    ///         println!("dropped!");
2476    ///     }
2477    /// }
2478    ///
2479    /// let foo  = Rc::new(Foo);
2480    /// let foo2 = Rc::clone(&foo);
2481    ///
2482    /// drop(foo);    // Doesn't print anything
2483    /// drop(foo2);   // Prints "dropped!"
2484    /// ```
2485    #[inline]
2486    fn drop(&mut self) {
2487        unsafe {
2488            self.inner().dec_strong();
2489            if self.inner().strong() == 0 {
2490                self.drop_slow();
2491            }
2492        }
2493    }
2494}
2495
2496#[stable(feature = "rust1", since = "1.0.0")]
2497impl<T: ?Sized, A: Allocator + Clone> Clone for Rc<T, A> {
2498    /// Makes a clone of the `Rc` pointer.
2499    ///
2500    /// This creates another pointer to the same allocation, increasing the
2501    /// strong reference count.
2502    ///
2503    /// # Examples
2504    ///
2505    /// ```
2506    /// use std::rc::Rc;
2507    ///
2508    /// let five = Rc::new(5);
2509    ///
2510    /// let _ = Rc::clone(&five);
2511    /// ```
2512    #[inline]
2513    fn clone(&self) -> Self {
2514        unsafe {
2515            self.inner().inc_strong();
2516            Self::from_inner_in(self.ptr, self.alloc.clone())
2517        }
2518    }
2519}
2520
2521#[unstable(feature = "ergonomic_clones", issue = "132290")]
2522impl<T: ?Sized, A: Allocator + Clone> UseCloned for Rc<T, A> {}
2523
2524#[unstable(feature = "share_trait", issue = "156756")]
2525impl<T: ?Sized, A: Allocator + Clone> Share for Rc<T, A> {}
2526
2527#[cfg(not(no_global_oom_handling))]
2528#[stable(feature = "rust1", since = "1.0.0")]
2529impl<T: Default> Default for Rc<T> {
2530    /// Creates a new `Rc<T>`, with the `Default` value for `T`.
2531    ///
2532    /// # Examples
2533    ///
2534    /// ```
2535    /// use std::rc::Rc;
2536    ///
2537    /// let x: Rc<i32> = Default::default();
2538    /// assert_eq!(*x, 0);
2539    /// ```
2540    #[inline]
2541    fn default() -> Self {
2542        unsafe {
2543            Self::from_inner(
2544                Box::leak(Box::write(
2545                    Box::new_uninit(),
2546                    RcInner { strong: Cell::new(1), weak: Cell::new(1), value: T::default() },
2547                ))
2548                .into(),
2549            )
2550        }
2551    }
2552}
2553
2554#[cfg(not(no_global_oom_handling))]
2555#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2556impl Default for Rc<str> {
2557    /// Creates an empty `str` inside an `Rc`.
2558    ///
2559    /// This may or may not share an allocation with other Rcs on the same thread.
2560    #[inline]
2561    fn default() -> Self {
2562        let rc = Rc::<[u8]>::default();
2563        // `[u8]` has the same layout as `str`.
2564        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2565    }
2566}
2567
2568#[cfg(not(no_global_oom_handling))]
2569#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2570impl<T> Default for Rc<[T]> {
2571    /// Creates an empty `[T]` inside an `Rc`.
2572    ///
2573    /// This may or may not share an allocation with other Rcs on the same thread.
2574    #[inline]
2575    fn default() -> Self {
2576        let arr: [T; 0] = [];
2577        Rc::from(arr)
2578    }
2579}
2580
2581#[cfg(not(no_global_oom_handling))]
2582#[stable(feature = "pin_default_impls", since = "1.91.0")]
2583impl<T> Default for Pin<Rc<T>>
2584where
2585    T: ?Sized,
2586    Rc<T>: Default,
2587{
2588    #[inline]
2589    fn default() -> Self {
2590        unsafe { Pin::new_unchecked(Rc::<T>::default()) }
2591    }
2592}
2593
2594#[stable(feature = "rust1", since = "1.0.0")]
2595trait RcEqIdent<T: ?Sized + PartialEq, A: Allocator> {
2596    fn eq(&self, other: &Rc<T, A>) -> bool;
2597    fn ne(&self, other: &Rc<T, A>) -> bool;
2598}
2599
2600#[stable(feature = "rust1", since = "1.0.0")]
2601impl<T: ?Sized + PartialEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2602    #[inline]
2603    default fn eq(&self, other: &Rc<T, A>) -> bool {
2604        **self == **other
2605    }
2606
2607    #[inline]
2608    default fn ne(&self, other: &Rc<T, A>) -> bool {
2609        **self != **other
2610    }
2611}
2612
2613// Hack to allow specializing on `Eq` even though `Eq` has a method.
2614#[rustc_unsafe_specialization_marker]
2615pub(crate) trait MarkerEq: PartialEq<Self> {}
2616
2617impl<T: ?Sized + Eq> MarkerEq for T {}
2618
2619/// We're doing this specialization here, and not as a more general optimization on `&T`, because it
2620/// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
2621/// store large values, that are slow to clone, but also heavy to check for equality, causing this
2622/// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
2623/// the same value, than two `&T`s.
2624///
2625/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
2626#[stable(feature = "rust1", since = "1.0.0")]
2627impl<T: ?Sized + MarkerEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2628    #[inline]
2629    fn eq(&self, other: &Rc<T, A>) -> bool {
2630        ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other
2631    }
2632
2633    #[inline]
2634    fn ne(&self, other: &Rc<T, A>) -> bool {
2635        !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other
2636    }
2637}
2638
2639#[stable(feature = "rust1", since = "1.0.0")]
2640impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Rc<T, A> {
2641    /// Equality for two `Rc`s.
2642    ///
2643    /// Two `Rc`s are equal if their inner values are equal, even if they are
2644    /// stored in different allocation.
2645    ///
2646    /// If `T` also implements `Eq` (implying reflexivity of equality),
2647    /// two `Rc`s that point to the same allocation are
2648    /// always equal.
2649    ///
2650    /// # Examples
2651    ///
2652    /// ```
2653    /// use std::rc::Rc;
2654    ///
2655    /// let five = Rc::new(5);
2656    ///
2657    /// assert!(five == Rc::new(5));
2658    /// ```
2659    #[inline]
2660    fn eq(&self, other: &Rc<T, A>) -> bool {
2661        RcEqIdent::eq(self, other)
2662    }
2663
2664    /// Inequality for two `Rc`s.
2665    ///
2666    /// Two `Rc`s are not equal if their inner values are not equal.
2667    ///
2668    /// If `T` also implements `Eq` (implying reflexivity of equality),
2669    /// two `Rc`s that point to the same allocation are
2670    /// always equal.
2671    ///
2672    /// # Examples
2673    ///
2674    /// ```
2675    /// use std::rc::Rc;
2676    ///
2677    /// let five = Rc::new(5);
2678    ///
2679    /// assert!(five != Rc::new(6));
2680    /// ```
2681    #[inline]
2682    fn ne(&self, other: &Rc<T, A>) -> bool {
2683        RcEqIdent::ne(self, other)
2684    }
2685}
2686
2687#[stable(feature = "rust1", since = "1.0.0")]
2688impl<T: ?Sized + Eq, A: Allocator> Eq for Rc<T, A> {}
2689
2690#[stable(feature = "rust1", since = "1.0.0")]
2691impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Rc<T, A> {
2692    /// Partial comparison for two `Rc`s.
2693    ///
2694    /// The two are compared by calling `partial_cmp()` on their inner values.
2695    ///
2696    /// # Examples
2697    ///
2698    /// ```
2699    /// use std::rc::Rc;
2700    /// use std::cmp::Ordering;
2701    ///
2702    /// let five = Rc::new(5);
2703    ///
2704    /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
2705    /// ```
2706    #[inline(always)]
2707    fn partial_cmp(&self, other: &Rc<T, A>) -> Option<Ordering> {
2708        (**self).partial_cmp(&**other)
2709    }
2710
2711    /// Less-than comparison for two `Rc`s.
2712    ///
2713    /// The two are compared by calling `<` on their inner values.
2714    ///
2715    /// # Examples
2716    ///
2717    /// ```
2718    /// use std::rc::Rc;
2719    ///
2720    /// let five = Rc::new(5);
2721    ///
2722    /// assert!(five < Rc::new(6));
2723    /// ```
2724    #[inline(always)]
2725    fn lt(&self, other: &Rc<T, A>) -> bool {
2726        **self < **other
2727    }
2728
2729    /// 'Less than or equal to' comparison for two `Rc`s.
2730    ///
2731    /// The two are compared by calling `<=` on their inner values.
2732    ///
2733    /// # Examples
2734    ///
2735    /// ```
2736    /// use std::rc::Rc;
2737    ///
2738    /// let five = Rc::new(5);
2739    ///
2740    /// assert!(five <= Rc::new(5));
2741    /// ```
2742    #[inline(always)]
2743    fn le(&self, other: &Rc<T, A>) -> bool {
2744        **self <= **other
2745    }
2746
2747    /// Greater-than comparison for two `Rc`s.
2748    ///
2749    /// The two are compared by calling `>` on their inner values.
2750    ///
2751    /// # Examples
2752    ///
2753    /// ```
2754    /// use std::rc::Rc;
2755    ///
2756    /// let five = Rc::new(5);
2757    ///
2758    /// assert!(five > Rc::new(4));
2759    /// ```
2760    #[inline(always)]
2761    fn gt(&self, other: &Rc<T, A>) -> bool {
2762        **self > **other
2763    }
2764
2765    /// 'Greater than or equal to' comparison for two `Rc`s.
2766    ///
2767    /// The two are compared by calling `>=` on their inner values.
2768    ///
2769    /// # Examples
2770    ///
2771    /// ```
2772    /// use std::rc::Rc;
2773    ///
2774    /// let five = Rc::new(5);
2775    ///
2776    /// assert!(five >= Rc::new(5));
2777    /// ```
2778    #[inline(always)]
2779    fn ge(&self, other: &Rc<T, A>) -> bool {
2780        **self >= **other
2781    }
2782}
2783
2784#[stable(feature = "rust1", since = "1.0.0")]
2785impl<T: ?Sized + Ord, A: Allocator> Ord for Rc<T, A> {
2786    /// Comparison for two `Rc`s.
2787    ///
2788    /// The two are compared by calling `cmp()` on their inner values.
2789    ///
2790    /// # Examples
2791    ///
2792    /// ```
2793    /// use std::rc::Rc;
2794    /// use std::cmp::Ordering;
2795    ///
2796    /// let five = Rc::new(5);
2797    ///
2798    /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
2799    /// ```
2800    #[inline]
2801    fn cmp(&self, other: &Rc<T, A>) -> Ordering {
2802        (**self).cmp(&**other)
2803    }
2804}
2805
2806#[stable(feature = "rust1", since = "1.0.0")]
2807impl<T: ?Sized + Hash, A: Allocator> Hash for Rc<T, A> {
2808    fn hash<H: Hasher>(&self, state: &mut H) {
2809        (**self).hash(state);
2810    }
2811}
2812
2813#[stable(feature = "rust1", since = "1.0.0")]
2814impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for Rc<T, A> {
2815    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2816        fmt::Display::fmt(&**self, f)
2817    }
2818}
2819
2820#[stable(feature = "rust1", since = "1.0.0")]
2821impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Rc<T, A> {
2822    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2823        fmt::Debug::fmt(&**self, f)
2824    }
2825}
2826
2827#[stable(feature = "rust1", since = "1.0.0")]
2828impl<T: ?Sized, A: Allocator> fmt::Pointer for Rc<T, A> {
2829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2830        fmt::Pointer::fmt(&(&raw const **self), f)
2831    }
2832}
2833
2834#[cfg(not(no_global_oom_handling))]
2835#[stable(feature = "from_for_ptrs", since = "1.6.0")]
2836impl<T> From<T> for Rc<T> {
2837    /// Converts a generic type `T` into an `Rc<T>`
2838    ///
2839    /// The conversion allocates on the heap and moves `t`
2840    /// from the stack into it.
2841    ///
2842    /// # Example
2843    /// ```rust
2844    /// # use std::rc::Rc;
2845    /// let x = 5;
2846    /// let rc = Rc::new(5);
2847    ///
2848    /// assert_eq!(Rc::from(x), rc);
2849    /// ```
2850    fn from(t: T) -> Self {
2851        Rc::new(t)
2852    }
2853}
2854
2855#[cfg(not(no_global_oom_handling))]
2856#[stable(feature = "shared_from_array", since = "1.74.0")]
2857impl<T, const N: usize> From<[T; N]> for Rc<[T]> {
2858    /// Converts a [`[T; N]`](prim@array) into an `Rc<[T]>`.
2859    ///
2860    /// The conversion moves the array into a newly allocated `Rc`.
2861    ///
2862    /// # Example
2863    ///
2864    /// ```
2865    /// # use std::rc::Rc;
2866    /// let original: [i32; 3] = [1, 2, 3];
2867    /// let shared: Rc<[i32]> = Rc::from(original);
2868    /// assert_eq!(&[1, 2, 3], &shared[..]);
2869    /// ```
2870    #[inline]
2871    fn from(v: [T; N]) -> Rc<[T]> {
2872        Rc::<[T; N]>::from(v)
2873    }
2874}
2875
2876#[cfg(not(no_global_oom_handling))]
2877#[stable(feature = "shared_from_slice", since = "1.21.0")]
2878impl<T: Clone> From<&[T]> for Rc<[T]> {
2879    /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2880    ///
2881    /// # Example
2882    ///
2883    /// ```
2884    /// # use std::rc::Rc;
2885    /// let original: &[i32] = &[1, 2, 3];
2886    /// let shared: Rc<[i32]> = Rc::from(original);
2887    /// assert_eq!(&[1, 2, 3], &shared[..]);
2888    /// ```
2889    #[inline]
2890    fn from(v: &[T]) -> Rc<[T]> {
2891        <Self as RcFromSlice<T>>::from_slice(v)
2892    }
2893}
2894
2895#[cfg(not(no_global_oom_handling))]
2896#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2897impl<T: Clone> From<&mut [T]> for Rc<[T]> {
2898    /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2899    ///
2900    /// # Example
2901    ///
2902    /// ```
2903    /// # use std::rc::Rc;
2904    /// let mut original = [1, 2, 3];
2905    /// let original: &mut [i32] = &mut original;
2906    /// let shared: Rc<[i32]> = Rc::from(original);
2907    /// assert_eq!(&[1, 2, 3], &shared[..]);
2908    /// ```
2909    #[inline]
2910    fn from(v: &mut [T]) -> Rc<[T]> {
2911        Rc::from(&*v)
2912    }
2913}
2914
2915#[cfg(not(no_global_oom_handling))]
2916#[stable(feature = "shared_from_slice", since = "1.21.0")]
2917impl From<&str> for Rc<str> {
2918    /// Allocates a reference-counted string slice and copies `v` into it.
2919    ///
2920    /// # Example
2921    ///
2922    /// ```
2923    /// # use std::rc::Rc;
2924    /// let shared: Rc<str> = Rc::from("statue");
2925    /// assert_eq!("statue", &shared[..]);
2926    /// ```
2927    #[inline]
2928    fn from(v: &str) -> Rc<str> {
2929        let rc = Rc::<[u8]>::from(v.as_bytes());
2930        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2931    }
2932}
2933
2934#[cfg(not(no_global_oom_handling))]
2935#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2936impl From<&mut str> for Rc<str> {
2937    /// Allocates a reference-counted string slice and copies `v` into it.
2938    ///
2939    /// # Example
2940    ///
2941    /// ```
2942    /// # use std::rc::Rc;
2943    /// let mut original = String::from("statue");
2944    /// let original: &mut str = &mut original;
2945    /// let shared: Rc<str> = Rc::from(original);
2946    /// assert_eq!("statue", &shared[..]);
2947    /// ```
2948    #[inline]
2949    fn from(v: &mut str) -> Rc<str> {
2950        Rc::from(&*v)
2951    }
2952}
2953
2954#[cfg(not(no_global_oom_handling))]
2955#[stable(feature = "shared_from_slice", since = "1.21.0")]
2956impl From<String> for Rc<str> {
2957    /// Allocates a reference-counted string slice and copies `v` into it.
2958    ///
2959    /// # Example
2960    ///
2961    /// ```
2962    /// # use std::rc::Rc;
2963    /// let original: String = "statue".to_owned();
2964    /// let shared: Rc<str> = Rc::from(original);
2965    /// assert_eq!("statue", &shared[..]);
2966    /// ```
2967    #[inline]
2968    fn from(v: String) -> Rc<str> {
2969        Rc::from(&v[..])
2970    }
2971}
2972
2973#[cfg(not(no_global_oom_handling))]
2974#[stable(feature = "shared_from_slice", since = "1.21.0")]
2975impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Rc<T, A> {
2976    /// Move a boxed object to a new, reference counted, allocation.
2977    ///
2978    /// # Example
2979    ///
2980    /// ```
2981    /// # use std::rc::Rc;
2982    /// let original: Box<i32> = Box::new(1);
2983    /// let shared: Rc<i32> = Rc::from(original);
2984    /// assert_eq!(1, *shared);
2985    /// ```
2986    #[inline]
2987    fn from(v: Box<T, A>) -> Rc<T, A> {
2988        Rc::from_box_in(v)
2989    }
2990}
2991
2992#[cfg(not(no_global_oom_handling))]
2993#[stable(feature = "shared_from_slice", since = "1.21.0")]
2994impl<T, A: Allocator> From<Vec<T, A>> for Rc<[T], A> {
2995    /// Allocates a reference-counted slice and moves `v`'s items into it.
2996    ///
2997    /// # Example
2998    ///
2999    /// ```
3000    /// # use std::rc::Rc;
3001    /// let unique: Vec<i32> = vec![1, 2, 3];
3002    /// let shared: Rc<[i32]> = Rc::from(unique);
3003    /// assert_eq!(&[1, 2, 3], &shared[..]);
3004    /// ```
3005    #[inline]
3006    fn from(v: Vec<T, A>) -> Rc<[T], A> {
3007        unsafe {
3008            let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
3009
3010            let rc_ptr = Self::allocate_for_slice_in(len, &alloc);
3011            ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).value) as *mut T, len);
3012
3013            // Create a `Vec<T, &A>` with length 0, to deallocate the buffer
3014            // without dropping its contents or the allocator
3015            let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc);
3016
3017            Self::from_ptr_in(rc_ptr, alloc)
3018        }
3019    }
3020}
3021
3022#[stable(feature = "shared_from_cow", since = "1.45.0")]
3023impl<'a, B> From<Cow<'a, B>> for Rc<B>
3024where
3025    B: ToOwned + ?Sized,
3026    Rc<B>: From<&'a B> + From<B::Owned>,
3027{
3028    /// Creates a reference-counted pointer from a clone-on-write pointer by
3029    /// copying its content.
3030    ///
3031    /// # Example
3032    ///
3033    /// ```rust
3034    /// # use std::rc::Rc;
3035    /// # use std::borrow::Cow;
3036    /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
3037    /// let shared: Rc<str> = Rc::from(cow);
3038    /// assert_eq!("eggplant", &shared[..]);
3039    /// ```
3040    #[inline]
3041    fn from(cow: Cow<'a, B>) -> Rc<B> {
3042        match cow {
3043            Cow::Borrowed(s) => Rc::from(s),
3044            Cow::Owned(s) => Rc::from(s),
3045        }
3046    }
3047}
3048
3049#[stable(feature = "shared_from_str", since = "1.62.0")]
3050impl From<Rc<str>> for Rc<[u8]> {
3051    /// Converts a reference-counted string slice into a byte slice.
3052    ///
3053    /// # Example
3054    ///
3055    /// ```
3056    /// # use std::rc::Rc;
3057    /// let string: Rc<str> = Rc::from("eggplant");
3058    /// let bytes: Rc<[u8]> = Rc::from(string);
3059    /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
3060    /// ```
3061    #[inline]
3062    fn from(rc: Rc<str>) -> Self {
3063        // SAFETY: `str` has the same layout as `[u8]`.
3064        unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
3065    }
3066}
3067
3068#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
3069impl<T, A: Allocator, const N: usize> TryFrom<Rc<[T], A>> for Rc<[T; N], A> {
3070    type Error = Rc<[T], A>;
3071
3072    fn try_from(boxed_slice: Rc<[T], A>) -> Result<Self, Self::Error> {
3073        if boxed_slice.len() == N {
3074            let (ptr, alloc) = Rc::into_inner_with_allocator(boxed_slice);
3075            Ok(unsafe { Rc::from_inner_in(ptr.cast(), alloc) })
3076        } else {
3077            Err(boxed_slice)
3078        }
3079    }
3080}
3081
3082#[cfg(not(no_global_oom_handling))]
3083#[stable(feature = "shared_from_iter", since = "1.37.0")]
3084impl<T> FromIterator<T> for Rc<[T]> {
3085    /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
3086    ///
3087    /// # Performance characteristics
3088    ///
3089    /// ## The general case
3090    ///
3091    /// In the general case, collecting into `Rc<[T]>` is done by first
3092    /// collecting into a `Vec<T>`. That is, when writing the following:
3093    ///
3094    /// ```rust
3095    /// # use std::rc::Rc;
3096    /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
3097    /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3098    /// ```
3099    ///
3100    /// this behaves as if we wrote:
3101    ///
3102    /// ```rust
3103    /// # use std::rc::Rc;
3104    /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
3105    ///     .collect::<Vec<_>>() // The first set of allocations happens here.
3106    ///     .into(); // A second allocation for `Rc<[T]>` happens here.
3107    /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3108    /// ```
3109    ///
3110    /// This will allocate as many times as needed for constructing the `Vec<T>`
3111    /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
3112    ///
3113    /// ## Iterators of known length
3114    ///
3115    /// When your `Iterator` implements `TrustedLen` and is of an exact size,
3116    /// a single allocation will be made for the `Rc<[T]>`. For example:
3117    ///
3118    /// ```rust
3119    /// # use std::rc::Rc;
3120    /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
3121    /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
3122    /// ```
3123    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
3124        ToRcSlice::to_rc_slice(iter.into_iter())
3125    }
3126}
3127
3128/// Specialization trait used for collecting into `Rc<[T]>`.
3129#[cfg(not(no_global_oom_handling))]
3130trait ToRcSlice<T>: Iterator<Item = T> + Sized {
3131    fn to_rc_slice(self) -> Rc<[T]>;
3132}
3133
3134#[cfg(not(no_global_oom_handling))]
3135impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
3136    default fn to_rc_slice(self) -> Rc<[T]> {
3137        self.collect::<Vec<T>>().into()
3138    }
3139}
3140
3141#[cfg(not(no_global_oom_handling))]
3142impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
3143    fn to_rc_slice(self) -> Rc<[T]> {
3144        // This is the case for a `TrustedLen` iterator.
3145        let (low, high) = self.size_hint();
3146        if let Some(high) = high {
3147            debug_assert_eq!(
3148                low,
3149                high,
3150                "TrustedLen iterator's size hint is not exact: {:?}",
3151                (low, high)
3152            );
3153
3154            unsafe {
3155                // SAFETY: We need to ensure that the iterator has an exact length and we have.
3156                Rc::from_iter_exact(self, low)
3157            }
3158        } else {
3159            // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
3160            // length exceeding `usize::MAX`.
3161            // The default implementation would collect into a vec which would panic.
3162            // Thus we panic here immediately without invoking `Vec` code.
3163            panic!("capacity overflow");
3164        }
3165    }
3166}
3167
3168/// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
3169/// managed allocation.
3170///
3171/// The allocation is accessed by calling [`upgrade`] on the `Weak`
3172/// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
3173///
3174/// Since a `Weak` reference does not count towards ownership, it will not
3175/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
3176/// guarantees about the value still being present. Thus it may return [`None`]
3177/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
3178/// itself (the backing store) from being deallocated.
3179///
3180/// A `Weak` pointer is useful for keeping a temporary reference to the allocation
3181/// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
3182/// prevent circular references between [`Rc`] pointers, since mutual owning references
3183/// would never allow either [`Rc`] to be dropped. For example, a tree could
3184/// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
3185/// pointers from children back to their parents.
3186///
3187/// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
3188///
3189/// [`upgrade`]: Weak::upgrade
3190#[stable(feature = "rc_weak", since = "1.4.0")]
3191#[rustc_diagnostic_item = "RcWeak"]
3192pub struct Weak<
3193    T: ?Sized,
3194    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3195> {
3196    // This is a `NonNull` to allow optimizing the size of this type in enums,
3197    // but it is not necessarily a valid pointer.
3198    // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
3199    // to allocate space on the heap. That's not a value a real pointer
3200    // will ever have because RcInner has alignment at least 2.
3201    ptr: NonNull<RcInner<T>>,
3202    alloc: A,
3203}
3204
3205#[stable(feature = "rc_weak", since = "1.4.0")]
3206impl<T: ?Sized, A: Allocator> !Send for Weak<T, A> {}
3207#[stable(feature = "rc_weak", since = "1.4.0")]
3208impl<T: ?Sized, A: Allocator> !Sync for Weak<T, A> {}
3209
3210#[unstable(feature = "coerce_unsized", issue = "18598")]
3211impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Weak<U, A>> for Weak<T, A> {}
3212
3213#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3214impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
3215
3216// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned.
3217#[unstable(feature = "cell_get_cloned", issue = "145329")]
3218unsafe impl<T: ?Sized> CloneFromCell for Weak<T> {}
3219
3220impl<T> Weak<T> {
3221    /// Constructs a new `Weak<T>`, without allocating any memory.
3222    /// Calling [`upgrade`] on the return value always gives [`None`].
3223    ///
3224    /// [`upgrade`]: Weak::upgrade
3225    ///
3226    /// # Examples
3227    ///
3228    /// ```
3229    /// use std::rc::Weak;
3230    ///
3231    /// let empty: Weak<i64> = Weak::new();
3232    /// assert!(empty.upgrade().is_none());
3233    /// ```
3234    #[inline]
3235    #[stable(feature = "downgraded_weak", since = "1.10.0")]
3236    #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")]
3237    #[must_use]
3238    pub const fn new() -> Weak<T> {
3239        Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global }
3240    }
3241}
3242
3243impl<T, A: Allocator> Weak<T, A> {
3244    /// Constructs a new `Weak<T>`, without allocating any memory, technically in the provided
3245    /// allocator.
3246    /// Calling [`upgrade`] on the return value always gives [`None`].
3247    ///
3248    /// [`upgrade`]: Weak::upgrade
3249    ///
3250    /// # Examples
3251    ///
3252    /// ```
3253    /// use std::rc::Weak;
3254    ///
3255    /// let empty: Weak<i64> = Weak::new();
3256    /// assert!(empty.upgrade().is_none());
3257    /// ```
3258    #[inline]
3259    #[unstable(feature = "allocator_api", issue = "32838")]
3260    pub fn new_in(alloc: A) -> Weak<T, A> {
3261        Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc }
3262    }
3263}
3264
3265pub(crate) fn is_dangling<T: ?Sized>(ptr: *const T) -> bool {
3266    (ptr.cast::<()>()).addr() == usize::MAX
3267}
3268
3269/// Helper type to allow accessing the reference counts without
3270/// making any assertions about the data field.
3271struct WeakInner<'a> {
3272    weak: &'a Cell<usize>,
3273    strong: &'a Cell<usize>,
3274}
3275
3276impl<T: ?Sized> Weak<T> {
3277    /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3278    ///
3279    /// This can be used to safely get a strong reference (by calling [`upgrade`]
3280    /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3281    ///
3282    /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3283    /// as these don't own anything; the method still works on them).
3284    ///
3285    /// # Safety
3286    ///
3287    /// The pointer must have originated from the [`into_raw`] and must still own its potential
3288    /// weak reference, and `ptr` must point to a block of memory allocated by the global allocator.
3289    ///
3290    /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3291    /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3292    /// count is not modified by this operation) and therefore it must be paired with a previous
3293    /// call to [`into_raw`].
3294    ///
3295    /// # Examples
3296    ///
3297    /// ```
3298    /// use std::rc::{Rc, Weak};
3299    ///
3300    /// let strong = Rc::new("hello".to_owned());
3301    ///
3302    /// let raw_1 = Rc::downgrade(&strong).into_raw();
3303    /// let raw_2 = Rc::downgrade(&strong).into_raw();
3304    ///
3305    /// assert_eq!(2, Rc::weak_count(&strong));
3306    ///
3307    /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3308    /// assert_eq!(1, Rc::weak_count(&strong));
3309    ///
3310    /// drop(strong);
3311    ///
3312    /// // Decrement the last weak count.
3313    /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3314    /// ```
3315    ///
3316    /// [`into_raw`]: Weak::into_raw
3317    /// [`upgrade`]: Weak::upgrade
3318    /// [`new`]: Weak::new
3319    #[inline]
3320    #[stable(feature = "weak_into_raw", since = "1.45.0")]
3321    pub unsafe fn from_raw(ptr: *const T) -> Self {
3322        unsafe { Self::from_raw_in(ptr, Global) }
3323    }
3324
3325    /// Consumes the `Weak<T>` and turns it into a raw pointer.
3326    ///
3327    /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3328    /// one weak reference (the weak count is not modified by this operation). It can be turned
3329    /// back into the `Weak<T>` with [`from_raw`].
3330    ///
3331    /// The same restrictions of accessing the target of the pointer as with
3332    /// [`as_ptr`] apply.
3333    ///
3334    /// # Examples
3335    ///
3336    /// ```
3337    /// use std::rc::{Rc, Weak};
3338    ///
3339    /// let strong = Rc::new("hello".to_owned());
3340    /// let weak = Rc::downgrade(&strong);
3341    /// let raw = weak.into_raw();
3342    ///
3343    /// assert_eq!(1, Rc::weak_count(&strong));
3344    /// assert_eq!("hello", unsafe { &*raw });
3345    ///
3346    /// drop(unsafe { Weak::from_raw(raw) });
3347    /// assert_eq!(0, Rc::weak_count(&strong));
3348    /// ```
3349    ///
3350    /// [`from_raw`]: Weak::from_raw
3351    /// [`as_ptr`]: Weak::as_ptr
3352    #[must_use = "losing the pointer will leak memory"]
3353    #[stable(feature = "weak_into_raw", since = "1.45.0")]
3354    pub fn into_raw(self) -> *const T {
3355        mem::ManuallyDrop::new(self).as_ptr()
3356    }
3357}
3358
3359impl<T: ?Sized, A: Allocator> Weak<T, A> {
3360    /// Returns a reference to the underlying allocator.
3361    #[inline]
3362    #[unstable(feature = "allocator_api", issue = "32838")]
3363    pub fn allocator(&self) -> &A {
3364        &self.alloc
3365    }
3366
3367    /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
3368    ///
3369    /// The pointer is valid only if there are some strong references. The pointer may be dangling,
3370    /// unaligned or even [`null`] otherwise.
3371    ///
3372    /// # Examples
3373    ///
3374    /// ```
3375    /// use std::rc::Rc;
3376    /// use std::ptr;
3377    ///
3378    /// let strong = Rc::new("hello".to_owned());
3379    /// let weak = Rc::downgrade(&strong);
3380    /// // Both point to the same object
3381    /// assert!(ptr::eq(&*strong, weak.as_ptr()));
3382    /// // The strong here keeps it alive, so we can still access the object.
3383    /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
3384    ///
3385    /// drop(strong);
3386    /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
3387    /// // undefined behavior.
3388    /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
3389    /// ```
3390    ///
3391    /// [`null`]: ptr::null
3392    #[must_use]
3393    #[stable(feature = "rc_as_ptr", since = "1.45.0")]
3394    pub fn as_ptr(&self) -> *const T {
3395        let ptr: *mut RcInner<T> = NonNull::as_ptr(self.ptr);
3396
3397        if is_dangling(ptr) {
3398            // If the pointer is dangling, we return the sentinel directly. This cannot be
3399            // a valid payload address, as the payload is at least as aligned as RcInner (usize).
3400            ptr as *const T
3401        } else {
3402            // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
3403            // The payload may be dropped at this point, and we have to maintain provenance,
3404            // so use raw pointer manipulation.
3405            unsafe { &raw mut (*ptr).value }
3406        }
3407    }
3408
3409    /// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
3410    ///
3411    /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3412    /// one weak reference (the weak count is not modified by this operation). It can be turned
3413    /// back into the `Weak<T>` with [`from_raw_in`].
3414    ///
3415    /// The same restrictions of accessing the target of the pointer as with
3416    /// [`as_ptr`] apply.
3417    ///
3418    /// # Examples
3419    ///
3420    /// ```
3421    /// #![feature(allocator_api)]
3422    /// use std::rc::{Rc, Weak};
3423    /// use std::alloc::System;
3424    ///
3425    /// let strong = Rc::new_in("hello".to_owned(), System);
3426    /// let weak = Rc::downgrade(&strong);
3427    /// let (raw, alloc) = weak.into_raw_with_allocator();
3428    ///
3429    /// assert_eq!(1, Rc::weak_count(&strong));
3430    /// assert_eq!("hello", unsafe { &*raw });
3431    ///
3432    /// drop(unsafe { Weak::from_raw_in(raw, alloc) });
3433    /// assert_eq!(0, Rc::weak_count(&strong));
3434    /// ```
3435    ///
3436    /// [`from_raw_in`]: Weak::from_raw_in
3437    /// [`as_ptr`]: Weak::as_ptr
3438    #[must_use = "losing the pointer will leak memory"]
3439    #[inline]
3440    #[unstable(feature = "allocator_api", issue = "32838")]
3441    pub fn into_raw_with_allocator(self) -> (*const T, A) {
3442        let this = mem::ManuallyDrop::new(self);
3443        let result = this.as_ptr();
3444        // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
3445        let alloc = unsafe { ptr::read(&this.alloc) };
3446        (result, alloc)
3447    }
3448
3449    /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3450    ///
3451    /// This can be used to safely get a strong reference (by calling [`upgrade`]
3452    /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3453    ///
3454    /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3455    /// as these don't own anything; the method still works on them).
3456    ///
3457    /// # Safety
3458    ///
3459    /// The pointer must have originated from the [`into_raw`] and must still own its potential
3460    /// weak reference, and `ptr` must point to a block of memory allocated by `alloc`.
3461    ///
3462    /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3463    /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3464    /// count is not modified by this operation) and therefore it must be paired with a previous
3465    /// call to [`into_raw`].
3466    ///
3467    /// # Examples
3468    ///
3469    /// ```
3470    /// use std::rc::{Rc, Weak};
3471    ///
3472    /// let strong = Rc::new("hello".to_owned());
3473    ///
3474    /// let raw_1 = Rc::downgrade(&strong).into_raw();
3475    /// let raw_2 = Rc::downgrade(&strong).into_raw();
3476    ///
3477    /// assert_eq!(2, Rc::weak_count(&strong));
3478    ///
3479    /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3480    /// assert_eq!(1, Rc::weak_count(&strong));
3481    ///
3482    /// drop(strong);
3483    ///
3484    /// // Decrement the last weak count.
3485    /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3486    /// ```
3487    ///
3488    /// [`into_raw`]: Weak::into_raw
3489    /// [`upgrade`]: Weak::upgrade
3490    /// [`new`]: Weak::new
3491    #[inline]
3492    #[unstable(feature = "allocator_api", issue = "32838")]
3493    pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
3494        // See Weak::as_ptr for context on how the input pointer is derived.
3495
3496        let ptr = if is_dangling(ptr) {
3497            // This is a dangling Weak.
3498            ptr as *mut RcInner<T>
3499        } else {
3500            // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
3501            // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
3502            let offset = unsafe { data_offset(ptr) };
3503            // Thus, we reverse the offset to get the whole RcInner.
3504            // SAFETY: the pointer originated from a Weak, so this offset is safe.
3505            unsafe { ptr.byte_sub(offset) as *mut RcInner<T> }
3506        };
3507
3508        // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
3509        Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc }
3510    }
3511
3512    /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
3513    /// dropping of the inner value if successful.
3514    ///
3515    /// Returns [`None`] in the following cases:
3516    ///
3517    /// 1. The inner value has since been dropped or moved out.
3518    ///
3519    /// 2. This `Weak` does not point to an allocation.
3520    ///
3521    /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade.
3522    ///
3523    /// # Examples
3524    ///
3525    /// ```
3526    /// use std::rc::Rc;
3527    ///
3528    /// let five = Rc::new(5);
3529    ///
3530    /// let weak_five = Rc::downgrade(&five);
3531    ///
3532    /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
3533    /// assert!(strong_five.is_some());
3534    ///
3535    /// // Destroy all strong pointers.
3536    /// drop(strong_five);
3537    /// drop(five);
3538    ///
3539    /// assert!(weak_five.upgrade().is_none());
3540    /// ```
3541    #[must_use = "this returns a new `Rc`, \
3542                  without modifying the original weak pointer"]
3543    #[stable(feature = "rc_weak", since = "1.4.0")]
3544    pub fn upgrade(&self) -> Option<Rc<T, A>>
3545    where
3546        A: Clone,
3547    {
3548        let inner = self.inner()?;
3549
3550        if inner.strong() == 0 {
3551            None
3552        } else {
3553            unsafe {
3554                inner.inc_strong();
3555                Some(Rc::from_inner_in(self.ptr, self.alloc.clone()))
3556            }
3557        }
3558    }
3559
3560    /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
3561    ///
3562    /// If `self` was created using [`Weak::new`], this will return 0.
3563    #[must_use]
3564    #[stable(feature = "weak_counts", since = "1.41.0")]
3565    pub fn strong_count(&self) -> usize {
3566        if let Some(inner) = self.inner() { inner.strong() } else { 0 }
3567    }
3568
3569    /// Gets the number of `Weak` pointers pointing to this allocation.
3570    ///
3571    /// If no strong pointers remain, this will return zero.
3572    #[must_use]
3573    #[stable(feature = "weak_counts", since = "1.41.0")]
3574    pub fn weak_count(&self) -> usize {
3575        if let Some(inner) = self.inner() {
3576            if inner.strong() > 0 {
3577                inner.weak() - 1 // subtract the implicit weak ptr
3578            } else {
3579                0
3580            }
3581        } else {
3582            0
3583        }
3584    }
3585
3586    /// Returns `None` when the pointer is dangling and there is no allocated `RcInner`,
3587    /// (i.e., when this `Weak` was created by `Weak::new`).
3588    #[inline]
3589    fn inner(&self) -> Option<WeakInner<'_>> {
3590        if is_dangling(self.ptr.as_ptr()) {
3591            None
3592        } else {
3593            // We are careful to *not* create a reference covering the "data" field, as
3594            // the field may be mutated concurrently (for example, if the last `Rc`
3595            // is dropped, the data field will be dropped in-place).
3596            Some(unsafe {
3597                let ptr = self.ptr.as_ptr();
3598                WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
3599            })
3600        }
3601    }
3602
3603    /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
3604    /// both don't point to any allocation (because they were created with `Weak::new()`). However,
3605    /// this function ignores the metadata of  `dyn Trait` pointers.
3606    ///
3607    /// # Notes
3608    ///
3609    /// Since this compares pointers it means that `Weak::new()` will equal each
3610    /// other, even though they don't point to any allocation.
3611    ///
3612    /// # Examples
3613    ///
3614    /// ```
3615    /// use std::rc::Rc;
3616    ///
3617    /// let first_rc = Rc::new(5);
3618    /// let first = Rc::downgrade(&first_rc);
3619    /// let second = Rc::downgrade(&first_rc);
3620    ///
3621    /// assert!(first.ptr_eq(&second));
3622    ///
3623    /// let third_rc = Rc::new(5);
3624    /// let third = Rc::downgrade(&third_rc);
3625    ///
3626    /// assert!(!first.ptr_eq(&third));
3627    /// ```
3628    ///
3629    /// Comparing `Weak::new`.
3630    ///
3631    /// ```
3632    /// use std::rc::{Rc, Weak};
3633    ///
3634    /// let first = Weak::new();
3635    /// let second = Weak::new();
3636    /// assert!(first.ptr_eq(&second));
3637    ///
3638    /// let third_rc = Rc::new(());
3639    /// let third = Rc::downgrade(&third_rc);
3640    /// assert!(!first.ptr_eq(&third));
3641    /// ```
3642    #[inline]
3643    #[must_use]
3644    #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
3645    pub fn ptr_eq(&self, other: &Self) -> bool {
3646        ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr())
3647    }
3648}
3649
3650#[stable(feature = "rc_weak", since = "1.4.0")]
3651unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak<T, A> {
3652    /// Drops the `Weak` pointer.
3653    ///
3654    /// # Examples
3655    ///
3656    /// ```
3657    /// use std::rc::{Rc, Weak};
3658    ///
3659    /// struct Foo;
3660    ///
3661    /// impl Drop for Foo {
3662    ///     fn drop(&mut self) {
3663    ///         println!("dropped!");
3664    ///     }
3665    /// }
3666    ///
3667    /// let foo = Rc::new(Foo);
3668    /// let weak_foo = Rc::downgrade(&foo);
3669    /// let other_weak_foo = Weak::clone(&weak_foo);
3670    ///
3671    /// drop(weak_foo);   // Doesn't print anything
3672    /// drop(foo);        // Prints "dropped!"
3673    ///
3674    /// assert!(other_weak_foo.upgrade().is_none());
3675    /// ```
3676    fn drop(&mut self) {
3677        let inner = if let Some(inner) = self.inner() { inner } else { return };
3678
3679        inner.dec_weak();
3680        // the weak count starts at 1, and will only go to zero if all
3681        // the strong pointers have disappeared.
3682        if inner.weak() == 0 {
3683            unsafe {
3684                self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
3685            }
3686        }
3687    }
3688}
3689
3690#[stable(feature = "rc_weak", since = "1.4.0")]
3691impl<T: ?Sized, A: Allocator + Clone> Clone for Weak<T, A> {
3692    /// Makes a clone of the `Weak` pointer that points to the same allocation.
3693    ///
3694    /// # Examples
3695    ///
3696    /// ```
3697    /// use std::rc::{Rc, Weak};
3698    ///
3699    /// let weak_five = Rc::downgrade(&Rc::new(5));
3700    ///
3701    /// let _ = Weak::clone(&weak_five);
3702    /// ```
3703    #[inline]
3704    fn clone(&self) -> Weak<T, A> {
3705        if let Some(inner) = self.inner() {
3706            inner.inc_weak()
3707        }
3708        Weak { ptr: self.ptr, alloc: self.alloc.clone() }
3709    }
3710}
3711
3712#[unstable(feature = "ergonomic_clones", issue = "132290")]
3713impl<T: ?Sized, A: Allocator + Clone> UseCloned for Weak<T, A> {}
3714
3715#[stable(feature = "rc_weak", since = "1.4.0")]
3716impl<T: ?Sized, A: Allocator> fmt::Debug for Weak<T, A> {
3717    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3718        write!(f, "(Weak)")
3719    }
3720}
3721
3722#[stable(feature = "downgraded_weak", since = "1.10.0")]
3723impl<T> Default for Weak<T> {
3724    /// Constructs a new `Weak<T>`, without allocating any memory.
3725    /// Calling [`upgrade`] on the return value always gives [`None`].
3726    ///
3727    /// [`upgrade`]: Weak::upgrade
3728    ///
3729    /// # Examples
3730    ///
3731    /// ```
3732    /// use std::rc::Weak;
3733    ///
3734    /// let empty: Weak<i64> = Default::default();
3735    /// assert!(empty.upgrade().is_none());
3736    /// ```
3737    fn default() -> Weak<T> {
3738        Weak::new()
3739    }
3740}
3741
3742// NOTE: If you mem::forget Rcs (or Weaks), drop is skipped and the ref-count
3743// is not decremented, meaning the ref-count can overflow, and then you can
3744// free the allocation while outstanding Rcs (or Weaks) exist, which would be
3745// unsound. We abort because this is such a degenerate scenario that we don't
3746// care about what happens -- no real program should ever experience this.
3747//
3748// This should have negligible overhead since you don't actually need to
3749// clone these much in Rust thanks to ownership and move-semantics.
3750
3751#[doc(hidden)]
3752trait RcInnerPtr {
3753    fn weak_ref(&self) -> &Cell<usize>;
3754    fn strong_ref(&self) -> &Cell<usize>;
3755
3756    #[inline]
3757    fn strong(&self) -> usize {
3758        self.strong_ref().get()
3759    }
3760
3761    #[inline]
3762    fn inc_strong(&self) {
3763        let strong = self.strong();
3764
3765        // We insert an `assume` here to hint LLVM at an otherwise
3766        // missed optimization.
3767        // SAFETY: The reference count will never be zero when this is
3768        // called.
3769        unsafe {
3770            hint::assert_unchecked(strong != 0);
3771        }
3772
3773        let strong = strong.wrapping_add(1);
3774        self.strong_ref().set(strong);
3775
3776        // We want to abort on overflow instead of dropping the value.
3777        // Checking for overflow after the store instead of before
3778        // allows for slightly better code generation.
3779        if core::intrinsics::unlikely(strong == 0) {
3780            abort();
3781        }
3782    }
3783
3784    #[inline]
3785    fn dec_strong(&self) {
3786        self.strong_ref().set(self.strong() - 1);
3787    }
3788
3789    #[inline]
3790    fn weak(&self) -> usize {
3791        self.weak_ref().get()
3792    }
3793
3794    #[inline]
3795    fn inc_weak(&self) {
3796        let weak = self.weak();
3797
3798        // We insert an `assume` here to hint LLVM at an otherwise
3799        // missed optimization.
3800        // SAFETY: The reference count will never be zero when this is
3801        // called.
3802        unsafe {
3803            hint::assert_unchecked(weak != 0);
3804        }
3805
3806        let weak = weak.wrapping_add(1);
3807        self.weak_ref().set(weak);
3808
3809        // We want to abort on overflow instead of dropping the value.
3810        // Checking for overflow after the store instead of before
3811        // allows for slightly better code generation.
3812        if core::intrinsics::unlikely(weak == 0) {
3813            abort();
3814        }
3815    }
3816
3817    #[inline]
3818    fn dec_weak(&self) {
3819        self.weak_ref().set(self.weak() - 1);
3820    }
3821}
3822
3823impl<T: ?Sized> RcInnerPtr for RcInner<T> {
3824    #[inline(always)]
3825    fn weak_ref(&self) -> &Cell<usize> {
3826        &self.weak
3827    }
3828
3829    #[inline(always)]
3830    fn strong_ref(&self) -> &Cell<usize> {
3831        &self.strong
3832    }
3833}
3834
3835impl<'a> RcInnerPtr for WeakInner<'a> {
3836    #[inline(always)]
3837    fn weak_ref(&self) -> &Cell<usize> {
3838        self.weak
3839    }
3840
3841    #[inline(always)]
3842    fn strong_ref(&self) -> &Cell<usize> {
3843        self.strong
3844    }
3845}
3846
3847#[stable(feature = "rust1", since = "1.0.0")]
3848impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Rc<T, A> {
3849    fn borrow(&self) -> &T {
3850        &**self
3851    }
3852}
3853
3854#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
3855impl<T: ?Sized, A: Allocator> AsRef<T> for Rc<T, A> {
3856    fn as_ref(&self) -> &T {
3857        &**self
3858    }
3859}
3860
3861#[stable(feature = "pin", since = "1.33.0")]
3862impl<T: ?Sized, A: Allocator> Unpin for Rc<T, A> {}
3863
3864/// Gets the offset within an `RcInner` for the payload behind a pointer.
3865///
3866/// # Safety
3867///
3868/// The pointer must point to (and have valid metadata for) a previously
3869/// valid instance of T, but the T is allowed to be dropped.
3870unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
3871    // Align the unsized value to the end of the RcInner.
3872    // Because RcInner is repr(C), it will always be the last field in memory.
3873    // SAFETY: since the only unsized types possible are slices, trait objects,
3874    // and extern types, the input safety requirement is currently enough to
3875    // satisfy the requirements of Alignment::of_val_raw; this is an implementation
3876    // detail of the language that must not be relied upon outside of std.
3877    unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) }
3878}
3879
3880#[inline]
3881fn data_offset_alignment(alignment: Alignment) -> usize {
3882    let layout = Layout::new::<RcInner<()>>();
3883    layout.size() + layout.padding_needed_for(alignment)
3884}
3885
3886/// A uniquely owned [`Rc`].
3887///
3888/// This represents an `Rc` that is known to be uniquely owned -- that is, have exactly one strong
3889/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
3890/// references will fail unless the `UniqueRc` they point to has been converted into a regular `Rc`.
3891///
3892/// Because they are uniquely owned, the contents of a `UniqueRc` can be freely mutated. A common
3893/// use case is to have an object be mutable during its initialization phase but then have it become
3894/// immutable and converted to a normal `Rc`.
3895///
3896/// This can be used as a flexible way to create cyclic data structures, as in the example below.
3897///
3898/// ```
3899/// #![feature(unique_rc_arc)]
3900/// use std::rc::{Rc, Weak, UniqueRc};
3901///
3902/// struct Gadget {
3903///     #[allow(dead_code)]
3904///     me: Weak<Gadget>,
3905/// }
3906///
3907/// fn create_gadget() -> Option<Rc<Gadget>> {
3908///     let mut rc = UniqueRc::new(Gadget {
3909///         me: Weak::new(),
3910///     });
3911///     rc.me = UniqueRc::downgrade(&rc);
3912///     Some(UniqueRc::into_rc(rc))
3913/// }
3914///
3915/// create_gadget().unwrap();
3916/// ```
3917///
3918/// An advantage of using `UniqueRc` over [`Rc::new_cyclic`] to build cyclic data structures is that
3919/// [`Rc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
3920/// previous example, `UniqueRc` allows for more flexibility in the construction of cyclic data,
3921/// including fallible or async constructors.
3922#[unstable(feature = "unique_rc_arc", issue = "112566")]
3923pub struct UniqueRc<
3924    T: ?Sized,
3925    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3926> {
3927    ptr: NonNull<RcInner<T>>,
3928    // Define the ownership of `RcInner<T>` for drop-check
3929    _marker: PhantomData<RcInner<T>>,
3930    // Invariance is necessary for soundness: once other `Weak`
3931    // references exist, we already have a form of shared mutability!
3932    _marker2: PhantomData<*mut T>,
3933    alloc: A,
3934}
3935
3936// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3937// but having an explicit negative impl is nice for documentation purposes
3938// and results in nicer error messages.
3939#[unstable(feature = "unique_rc_arc", issue = "112566")]
3940impl<T: ?Sized, A: Allocator> !Send for UniqueRc<T, A> {}
3941
3942// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3943// but having an explicit negative impl is nice for documentation purposes
3944// and results in nicer error messages.
3945#[unstable(feature = "unique_rc_arc", issue = "112566")]
3946impl<T: ?Sized, A: Allocator> !Sync for UniqueRc<T, A> {}
3947
3948#[unstable(feature = "unique_rc_arc", issue = "112566")]
3949impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueRc<U, A>>
3950    for UniqueRc<T, A>
3951{
3952}
3953
3954//#[unstable(feature = "unique_rc_arc", issue = "112566")]
3955#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3956impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<UniqueRc<U>> for UniqueRc<T> {}
3957
3958#[unstable(feature = "unique_rc_arc", issue = "112566")]
3959impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for UniqueRc<T, A> {
3960    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3961        fmt::Display::fmt(&**self, f)
3962    }
3963}
3964
3965#[unstable(feature = "unique_rc_arc", issue = "112566")]
3966impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for UniqueRc<T, A> {
3967    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3968        fmt::Debug::fmt(&**self, f)
3969    }
3970}
3971
3972#[unstable(feature = "unique_rc_arc", issue = "112566")]
3973impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueRc<T, A> {
3974    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3975        fmt::Pointer::fmt(&(&raw const **self), f)
3976    }
3977}
3978
3979#[unstable(feature = "unique_rc_arc", issue = "112566")]
3980impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueRc<T, A> {
3981    fn borrow(&self) -> &T {
3982        &**self
3983    }
3984}
3985
3986#[unstable(feature = "unique_rc_arc", issue = "112566")]
3987impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueRc<T, A> {
3988    fn borrow_mut(&mut self) -> &mut T {
3989        &mut **self
3990    }
3991}
3992
3993#[unstable(feature = "unique_rc_arc", issue = "112566")]
3994impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueRc<T, A> {
3995    fn as_ref(&self) -> &T {
3996        &**self
3997    }
3998}
3999
4000#[unstable(feature = "unique_rc_arc", issue = "112566")]
4001impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueRc<T, A> {
4002    fn as_mut(&mut self) -> &mut T {
4003        &mut **self
4004    }
4005}
4006
4007#[unstable(feature = "unique_rc_arc", issue = "112566")]
4008impl<T: ?Sized, A: Allocator> Unpin for UniqueRc<T, A> {}
4009
4010#[cfg(not(no_global_oom_handling))]
4011#[unstable(feature = "unique_rc_arc", issue = "112566")]
4012impl<T> From<T> for UniqueRc<T> {
4013    #[inline(always)]
4014    fn from(value: T) -> Self {
4015        Self::new(value)
4016    }
4017}
4018
4019#[unstable(feature = "unique_rc_arc", issue = "112566")]
4020impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for UniqueRc<T, A> {
4021    /// Equality for two `UniqueRc`s.
4022    ///
4023    /// Two `UniqueRc`s are equal if their inner values are equal.
4024    ///
4025    /// # Examples
4026    ///
4027    /// ```
4028    /// #![feature(unique_rc_arc)]
4029    /// use std::rc::UniqueRc;
4030    ///
4031    /// let five = UniqueRc::new(5);
4032    ///
4033    /// assert!(five == UniqueRc::new(5));
4034    /// ```
4035    #[inline]
4036    fn eq(&self, other: &Self) -> bool {
4037        PartialEq::eq(&**self, &**other)
4038    }
4039
4040    /// Inequality for two `UniqueRc`s.
4041    ///
4042    /// Two `UniqueRc`s are not equal if their inner values are not equal.
4043    ///
4044    /// # Examples
4045    ///
4046    /// ```
4047    /// #![feature(unique_rc_arc)]
4048    /// use std::rc::UniqueRc;
4049    ///
4050    /// let five = UniqueRc::new(5);
4051    ///
4052    /// assert!(five != UniqueRc::new(6));
4053    /// ```
4054    #[inline]
4055    fn ne(&self, other: &Self) -> bool {
4056        PartialEq::ne(&**self, &**other)
4057    }
4058}
4059
4060#[unstable(feature = "unique_rc_arc", issue = "112566")]
4061impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for UniqueRc<T, A> {
4062    /// Partial comparison for two `UniqueRc`s.
4063    ///
4064    /// The two are compared by calling `partial_cmp()` on their inner values.
4065    ///
4066    /// # Examples
4067    ///
4068    /// ```
4069    /// #![feature(unique_rc_arc)]
4070    /// use std::rc::UniqueRc;
4071    /// use std::cmp::Ordering;
4072    ///
4073    /// let five = UniqueRc::new(5);
4074    ///
4075    /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueRc::new(6)));
4076    /// ```
4077    #[inline(always)]
4078    fn partial_cmp(&self, other: &UniqueRc<T, A>) -> Option<Ordering> {
4079        (**self).partial_cmp(&**other)
4080    }
4081
4082    /// Less-than comparison for two `UniqueRc`s.
4083    ///
4084    /// The two are compared by calling `<` on their inner values.
4085    ///
4086    /// # Examples
4087    ///
4088    /// ```
4089    /// #![feature(unique_rc_arc)]
4090    /// use std::rc::UniqueRc;
4091    ///
4092    /// let five = UniqueRc::new(5);
4093    ///
4094    /// assert!(five < UniqueRc::new(6));
4095    /// ```
4096    #[inline(always)]
4097    fn lt(&self, other: &UniqueRc<T, A>) -> bool {
4098        **self < **other
4099    }
4100
4101    /// 'Less than or equal to' comparison for two `UniqueRc`s.
4102    ///
4103    /// The two are compared by calling `<=` on their inner values.
4104    ///
4105    /// # Examples
4106    ///
4107    /// ```
4108    /// #![feature(unique_rc_arc)]
4109    /// use std::rc::UniqueRc;
4110    ///
4111    /// let five = UniqueRc::new(5);
4112    ///
4113    /// assert!(five <= UniqueRc::new(5));
4114    /// ```
4115    #[inline(always)]
4116    fn le(&self, other: &UniqueRc<T, A>) -> bool {
4117        **self <= **other
4118    }
4119
4120    /// Greater-than comparison for two `UniqueRc`s.
4121    ///
4122    /// The two are compared by calling `>` on their inner values.
4123    ///
4124    /// # Examples
4125    ///
4126    /// ```
4127    /// #![feature(unique_rc_arc)]
4128    /// use std::rc::UniqueRc;
4129    ///
4130    /// let five = UniqueRc::new(5);
4131    ///
4132    /// assert!(five > UniqueRc::new(4));
4133    /// ```
4134    #[inline(always)]
4135    fn gt(&self, other: &UniqueRc<T, A>) -> bool {
4136        **self > **other
4137    }
4138
4139    /// 'Greater than or equal to' comparison for two `UniqueRc`s.
4140    ///
4141    /// The two are compared by calling `>=` on their inner values.
4142    ///
4143    /// # Examples
4144    ///
4145    /// ```
4146    /// #![feature(unique_rc_arc)]
4147    /// use std::rc::UniqueRc;
4148    ///
4149    /// let five = UniqueRc::new(5);
4150    ///
4151    /// assert!(five >= UniqueRc::new(5));
4152    /// ```
4153    #[inline(always)]
4154    fn ge(&self, other: &UniqueRc<T, A>) -> bool {
4155        **self >= **other
4156    }
4157}
4158
4159#[unstable(feature = "unique_rc_arc", issue = "112566")]
4160impl<T: ?Sized + Ord, A: Allocator> Ord for UniqueRc<T, A> {
4161    /// Comparison for two `UniqueRc`s.
4162    ///
4163    /// The two are compared by calling `cmp()` on their inner values.
4164    ///
4165    /// # Examples
4166    ///
4167    /// ```
4168    /// #![feature(unique_rc_arc)]
4169    /// use std::rc::UniqueRc;
4170    /// use std::cmp::Ordering;
4171    ///
4172    /// let five = UniqueRc::new(5);
4173    ///
4174    /// assert_eq!(Ordering::Less, five.cmp(&UniqueRc::new(6)));
4175    /// ```
4176    #[inline]
4177    fn cmp(&self, other: &UniqueRc<T, A>) -> Ordering {
4178        (**self).cmp(&**other)
4179    }
4180}
4181
4182#[unstable(feature = "unique_rc_arc", issue = "112566")]
4183impl<T: ?Sized + Eq, A: Allocator> Eq for UniqueRc<T, A> {}
4184
4185#[unstable(feature = "unique_rc_arc", issue = "112566")]
4186impl<T: ?Sized + Hash, A: Allocator> Hash for UniqueRc<T, A> {
4187    fn hash<H: Hasher>(&self, state: &mut H) {
4188        (**self).hash(state);
4189    }
4190}
4191
4192// Depends on A = Global
4193impl<T> UniqueRc<T> {
4194    /// Creates a new `UniqueRc`.
4195    ///
4196    /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4197    /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4198    /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4199    /// point to the new [`Rc`].
4200    #[cfg(not(no_global_oom_handling))]
4201    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4202    pub fn new(value: T) -> Self {
4203        Self::new_in(value, Global)
4204    }
4205
4206    /// Maps the value in a `UniqueRc`, reusing the allocation if possible.
4207    ///
4208    /// `f` is called on a reference to the value in the `UniqueRc`, and the result is returned,
4209    /// also in a `UniqueRc`.
4210    ///
4211    /// Note: this is an associated function, which means that you have
4212    /// to call it as `UniqueRc::map(u, f)` instead of `u.map(f)`. This
4213    /// is so that there is no conflict with a method on the inner type.
4214    ///
4215    /// # Examples
4216    ///
4217    /// ```
4218    /// #![feature(smart_pointer_try_map)]
4219    /// #![feature(unique_rc_arc)]
4220    ///
4221    /// use std::rc::UniqueRc;
4222    ///
4223    /// let r = UniqueRc::new(7);
4224    /// let new = UniqueRc::map(r, |i| i + 7);
4225    /// assert_eq!(*new, 14);
4226    /// ```
4227    #[cfg(not(no_global_oom_handling))]
4228    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4229    pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> UniqueRc<U> {
4230        if size_of::<T>() == size_of::<U>()
4231            && align_of::<T>() == align_of::<U>()
4232            && UniqueRc::weak_count(&this) == 0
4233        {
4234            unsafe {
4235                let ptr = UniqueRc::into_raw(this);
4236                let value = ptr.read();
4237                let mut allocation = UniqueRc::from_raw(ptr.cast::<mem::MaybeUninit<U>>());
4238
4239                allocation.write(f(value));
4240                allocation.assume_init()
4241            }
4242        } else {
4243            UniqueRc::new(f(UniqueRc::unwrap(this)))
4244        }
4245    }
4246
4247    /// Attempts to map the value in a `UniqueRc`, reusing the allocation if possible.
4248    ///
4249    /// `f` is called on a reference to the value in the `UniqueRc`, and if the operation succeeds,
4250    /// the result is returned, also in a `UniqueRc`.
4251    ///
4252    /// Note: this is an associated function, which means that you have
4253    /// to call it as `UniqueRc::try_map(u, f)` instead of `u.try_map(f)`. This
4254    /// is so that there is no conflict with a method on the inner type.
4255    ///
4256    /// # Examples
4257    ///
4258    /// ```
4259    /// #![feature(smart_pointer_try_map)]
4260    /// #![feature(unique_rc_arc)]
4261    ///
4262    /// use std::rc::UniqueRc;
4263    ///
4264    /// let b = UniqueRc::new(7);
4265    /// let new = UniqueRc::try_map(b, u32::try_from).unwrap();
4266    /// assert_eq!(*new, 7);
4267    /// ```
4268    #[cfg(not(no_global_oom_handling))]
4269    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4270    pub fn try_map<R>(
4271        this: Self,
4272        f: impl FnOnce(T) -> R,
4273    ) -> <R::Residual as Residual<UniqueRc<R::Output>>>::TryType
4274    where
4275        R: Try,
4276        R::Residual: Residual<UniqueRc<R::Output>>,
4277    {
4278        if size_of::<T>() == size_of::<R::Output>()
4279            && align_of::<T>() == align_of::<R::Output>()
4280            && UniqueRc::weak_count(&this) == 0
4281        {
4282            unsafe {
4283                let ptr = UniqueRc::into_raw(this);
4284                let value = ptr.read();
4285                let mut allocation = UniqueRc::from_raw(ptr.cast::<mem::MaybeUninit<R::Output>>());
4286
4287                allocation.write(f(value)?);
4288                try { allocation.assume_init() }
4289            }
4290        } else {
4291            try { UniqueRc::new(f(UniqueRc::unwrap(this))?) }
4292        }
4293    }
4294
4295    #[cfg(not(no_global_oom_handling))]
4296    fn unwrap(this: Self) -> T {
4297        let this = ManuallyDrop::new(this);
4298        let val: T = unsafe { ptr::read(&**this) };
4299
4300        let _weak = Weak { ptr: this.ptr, alloc: Global };
4301
4302        val
4303    }
4304}
4305
4306impl<T: ?Sized> UniqueRc<T> {
4307    #[cfg(not(no_global_oom_handling))]
4308    unsafe fn from_raw(ptr: *const T) -> Self {
4309        let offset = unsafe { data_offset(ptr) };
4310
4311        // Reverse the offset to find the original RcInner.
4312        let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
4313
4314        Self {
4315            ptr: unsafe { NonNull::new_unchecked(rc_ptr) },
4316            _marker: PhantomData,
4317            _marker2: PhantomData,
4318            alloc: Global,
4319        }
4320    }
4321
4322    #[cfg(not(no_global_oom_handling))]
4323    fn into_raw(this: Self) -> *const T {
4324        let this = ManuallyDrop::new(this);
4325        Self::as_ptr(&*this)
4326    }
4327}
4328
4329impl<T, A: Allocator> UniqueRc<T, A> {
4330    /// Creates a new `UniqueRc` in the provided allocator.
4331    ///
4332    /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4333    /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4334    /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4335    /// point to the new [`Rc`].
4336    #[cfg(not(no_global_oom_handling))]
4337    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4338    pub fn new_in(value: T, alloc: A) -> Self {
4339        let (ptr, alloc) = Box::into_unique(Box::new_in(
4340            RcInner {
4341                strong: Cell::new(0),
4342                // keep one weak reference so if all the weak pointers that are created are dropped
4343                // the UniqueRc still stays valid.
4344                weak: Cell::new(1),
4345                value,
4346            },
4347            alloc,
4348        ));
4349        Self { ptr: ptr.into(), _marker: PhantomData, _marker2: PhantomData, alloc }
4350    }
4351}
4352
4353impl<T: ?Sized, A: Allocator> UniqueRc<T, A> {
4354    /// Converts the `UniqueRc` into a regular [`Rc`].
4355    ///
4356    /// This consumes the `UniqueRc` and returns a regular [`Rc`] that contains the `value` that
4357    /// is passed to `into_rc`.
4358    ///
4359    /// Any weak references created before this method is called can now be upgraded to strong
4360    /// references.
4361    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4362    pub fn into_rc(this: Self) -> Rc<T, A> {
4363        let mut this = ManuallyDrop::new(this);
4364
4365        // Move the allocator out.
4366        // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
4367        // a `ManuallyDrop`.
4368        let alloc: A = unsafe { ptr::read(&this.alloc) };
4369
4370        // SAFETY: This pointer was allocated at creation time so we know it is valid.
4371        unsafe {
4372            // Convert our weak reference into a strong reference
4373            this.ptr.as_mut().strong.set(1);
4374            Rc::from_inner_in(this.ptr, alloc)
4375        }
4376    }
4377
4378    #[cfg(not(no_global_oom_handling))]
4379    fn weak_count(this: &Self) -> usize {
4380        this.inner().weak() - 1
4381    }
4382
4383    #[cfg(not(no_global_oom_handling))]
4384    fn inner(&self) -> &RcInner<T> {
4385        // SAFETY: while this UniqueRc is alive we're guaranteed that the inner pointer is valid.
4386        unsafe { self.ptr.as_ref() }
4387    }
4388
4389    #[cfg(not(no_global_oom_handling))]
4390    fn as_ptr(this: &Self) -> *const T {
4391        let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
4392
4393        // SAFETY: This cannot go through Deref::deref or UniqueRc::inner because
4394        // this is required to retain raw/mut provenance such that e.g. `get_mut` can
4395        // write through the pointer after the Rc is recovered through `from_raw`.
4396        unsafe { &raw mut (*ptr).value }
4397    }
4398
4399    #[inline]
4400    #[cfg(not(no_global_oom_handling))]
4401    fn into_inner_with_allocator(this: Self) -> (NonNull<RcInner<T>>, A) {
4402        let this = mem::ManuallyDrop::new(this);
4403        (this.ptr, unsafe { ptr::read(&this.alloc) })
4404    }
4405
4406    #[inline]
4407    #[cfg(not(no_global_oom_handling))]
4408    unsafe fn from_inner_in(ptr: NonNull<RcInner<T>>, alloc: A) -> Self {
4409        Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
4410    }
4411}
4412
4413impl<T: ?Sized, A: Allocator + Clone> UniqueRc<T, A> {
4414    /// Creates a new weak reference to the `UniqueRc`.
4415    ///
4416    /// Attempting to upgrade this weak reference will fail before the `UniqueRc` has been converted
4417    /// to a [`Rc`] using [`UniqueRc::into_rc`].
4418    #[unstable(feature = "unique_rc_arc", issue = "112566")]
4419    pub fn downgrade(this: &Self) -> Weak<T, A> {
4420        // SAFETY: This pointer was allocated at creation time and we guarantee that we only have
4421        // one strong reference before converting to a regular Rc.
4422        unsafe {
4423            this.ptr.as_ref().inc_weak();
4424        }
4425        Weak { ptr: this.ptr, alloc: this.alloc.clone() }
4426    }
4427}
4428
4429#[cfg(not(no_global_oom_handling))]
4430impl<T, A: Allocator> UniqueRc<mem::MaybeUninit<T>, A> {
4431    unsafe fn assume_init(self) -> UniqueRc<T, A> {
4432        let (ptr, alloc) = UniqueRc::into_inner_with_allocator(self);
4433        unsafe { UniqueRc::from_inner_in(ptr.cast(), alloc) }
4434    }
4435}
4436
4437#[unstable(feature = "unique_rc_arc", issue = "112566")]
4438impl<T: ?Sized, A: Allocator> Deref for UniqueRc<T, A> {
4439    type Target = T;
4440
4441    fn deref(&self) -> &T {
4442        // SAFETY: This pointer was allocated at creation time so we know it is valid.
4443        unsafe { &self.ptr.as_ref().value }
4444    }
4445}
4446
4447#[unstable(feature = "unique_rc_arc", issue = "112566")]
4448impl<T: ?Sized, A: Allocator> DerefMut for UniqueRc<T, A> {
4449    fn deref_mut(&mut self) -> &mut T {
4450        // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
4451        // have unique ownership and therefore it's safe to make a mutable reference because
4452        // `UniqueRc` owns the only strong reference to itself.
4453        unsafe { &mut (*self.ptr.as_ptr()).value }
4454    }
4455}
4456
4457#[unstable(feature = "unique_rc_arc", issue = "112566")]
4458unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueRc<T, A> {
4459    fn drop(&mut self) {
4460        unsafe {
4461            // destroy the contained object
4462            drop_in_place(DerefMut::deref_mut(self));
4463
4464            // remove the implicit "strong weak" pointer now that we've destroyed the contents.
4465            self.ptr.as_ref().dec_weak();
4466
4467            if self.ptr.as_ref().weak() == 0 {
4468                self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
4469            }
4470        }
4471    }
4472}
4473
4474/// A unique owning pointer to a [`RcInner`] **that does not imply the contents are initialized,**
4475/// but will deallocate it (without dropping the value) when dropped.
4476///
4477/// This is a helper for [`Rc::make_mut()`] to ensure correct cleanup on panic.
4478/// It is nearly a duplicate of `UniqueRc<MaybeUninit<T>, A>` except that it allows `T: !Sized`,
4479/// which `MaybeUninit` does not.
4480struct UniqueRcUninit<T: ?Sized, A: Allocator> {
4481    ptr: NonNull<RcInner<T>>,
4482    layout_for_value: Layout,
4483    alloc: Option<A>,
4484}
4485
4486impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
4487    /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it.
4488    #[cfg(not(no_global_oom_handling))]
4489    fn new(for_value: &T, alloc: A) -> UniqueRcUninit<T, A> {
4490        let layout = Layout::for_value(for_value);
4491        let ptr = unsafe {
4492            Rc::allocate_for_layout(
4493                layout,
4494                |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4495                |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4496            )
4497        };
4498        Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }
4499    }
4500
4501    /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it,
4502    /// returning an error if allocation fails.
4503    fn try_new(for_value: &T, alloc: A) -> Result<UniqueRcUninit<T, A>, AllocError> {
4504        let layout = Layout::for_value(for_value);
4505        let ptr = unsafe {
4506            Rc::try_allocate_for_layout(
4507                layout,
4508                |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4509                |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4510            )?
4511        };
4512        Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) })
4513    }
4514
4515    /// Returns the pointer to be written into to initialize the [`Rc`].
4516    fn data_ptr(&mut self) -> *mut T {
4517        let offset = data_offset_alignment(self.layout_for_value.alignment());
4518        unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T }
4519    }
4520
4521    /// Upgrade this into a normal [`Rc`].
4522    ///
4523    /// # Safety
4524    ///
4525    /// The data must have been initialized (by writing to [`Self::data_ptr()`]).
4526    unsafe fn into_rc(self) -> Rc<T, A> {
4527        let mut this = ManuallyDrop::new(self);
4528        let ptr = this.ptr;
4529        let alloc = this.alloc.take().unwrap();
4530
4531        // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
4532        // for having initialized the data.
4533        unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }
4534    }
4535}
4536
4537impl<T: ?Sized, A: Allocator> Drop for UniqueRcUninit<T, A> {
4538    fn drop(&mut self) {
4539        // SAFETY:
4540        // * new() produced a pointer safe to deallocate.
4541        // * We own the pointer unless into_rc() was called, which forgets us.
4542        unsafe {
4543            self.alloc.take().unwrap().deallocate(
4544                self.ptr.cast(),
4545                rc_inner_layout_for_value_layout(self.layout_for_value),
4546            );
4547        }
4548    }
4549}
4550
4551#[unstable(feature = "allocator_api", issue = "32838")]
4552unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Rc<T, A> {
4553    #[inline]
4554    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4555        (**self).allocate(layout)
4556    }
4557
4558    #[inline]
4559    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4560        (**self).allocate_zeroed(layout)
4561    }
4562
4563    #[inline]
4564    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
4565        // SAFETY: the safety contract must be upheld by the caller
4566        unsafe { (**self).deallocate(ptr, layout) }
4567    }
4568
4569    #[inline]
4570    unsafe fn grow(
4571        &self,
4572        ptr: NonNull<u8>,
4573        old_layout: Layout,
4574        new_layout: Layout,
4575    ) -> Result<NonNull<[u8]>, AllocError> {
4576        // SAFETY: the safety contract must be upheld by the caller
4577        unsafe { (**self).grow(ptr, old_layout, new_layout) }
4578    }
4579
4580    #[inline]
4581    unsafe fn grow_zeroed(
4582        &self,
4583        ptr: NonNull<u8>,
4584        old_layout: Layout,
4585        new_layout: Layout,
4586    ) -> Result<NonNull<[u8]>, AllocError> {
4587        // SAFETY: the safety contract must be upheld by the caller
4588        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
4589    }
4590
4591    #[inline]
4592    unsafe fn shrink(
4593        &self,
4594        ptr: NonNull<u8>,
4595        old_layout: Layout,
4596        new_layout: Layout,
4597    ) -> Result<NonNull<[u8]>, AllocError> {
4598        // SAFETY: the safety contract must be upheld by the caller
4599        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
4600    }
4601}