Skip to main content

alloc/
sync.rs

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