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