Skip to main content

alloc/
rc.rs

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