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