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