Skip to main content

alloc/
sync.rs

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