Skip to main content

alloc/
sync.rs

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