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