Skip to main content

alloc/
sync.rs

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