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