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