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