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 #[lint::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 #[lint::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::addr_eq`]. This function ignores the metadata of wide 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 /// #![feature(arc_is_unique)]
2882 ///
2883 /// use std::sync::Arc;
2884 ///
2885 /// let x = Arc::new(3);
2886 /// assert!(Arc::is_unique(&x));
2887 ///
2888 /// let y = Arc::clone(&x);
2889 /// assert!(!Arc::is_unique(&x));
2890 /// drop(y);
2891 ///
2892 /// // Weak references also count, because they could be upgraded at any time.
2893 /// let z = Arc::downgrade(&x);
2894 /// assert!(!Arc::is_unique(&x));
2895 /// ```
2896 ///
2897 /// # Pointer invalidation
2898 ///
2899 /// This function will always return the same value as `Arc::get_mut(arc).is_some()`. However,
2900 /// unlike that operation it does not produce any mutable references to the underlying data,
2901 /// meaning no pointers to the data inside the `Arc` are invalidated by the call. Thus, the
2902 /// following code is valid:
2903 ///
2904 /// ```
2905 /// #![feature(arc_is_unique)]
2906 ///
2907 /// use std::sync::Arc;
2908 ///
2909 /// let arc = Arc::new(5);
2910 /// let pointer: *const i32 = &*arc;
2911 /// assert!(Arc::is_unique(&arc));
2912 /// assert_eq!(unsafe { *pointer }, 5);
2913 /// ```
2914 ///
2915 /// The following changes would make the example unsound:
2916 ///
2917 /// - Using `Arc::get_mut` to create a mutable reference while also accessing the value
2918 /// through `pointer`.
2919 /// - Dropping `arc` before dereferencing `pointer`, leaving it dangling.
2920 ///
2921 /// # Atomic orderings
2922 ///
2923 /// Concurrent drops to other `Arc` pointers to the same allocation will synchronize with this
2924 /// call - that is, this call performs an `Acquire` operation on the underlying strong and weak
2925 /// ref counts. This ensures that calling `get_mut_unchecked` is safe.
2926 ///
2927 /// Note that this operation requires locking the weak ref count, so concurrent calls to
2928 /// `downgrade` may spin-loop for a short period of time.
2929 ///
2930 /// [`get_mut_unchecked`]: Self::get_mut_unchecked
2931 #[inline]
2932 #[unstable(feature = "arc_is_unique", issue = "138938")]
2933 pub fn is_unique(this: &Self) -> bool {
2934 // lock the weak pointer count if we appear to be the sole weak pointer
2935 // holder.
2936 //
2937 // The acquire label here ensures a happens-before relationship with any
2938 // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
2939 // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded
2940 // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
2941 if this.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
2942 // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
2943 // counter in `drop` -- the only access that happens when any but the last reference
2944 // is being dropped.
2945 let unique = this.inner().strong.load(Acquire) == 1;
2946
2947 // The release write here synchronizes with a read in `downgrade`,
2948 // effectively preventing the above read of `strong` from happening
2949 // after the write.
2950 this.inner().weak.store(1, Release); // release the lock
2951 unique
2952 } else {
2953 false
2954 }
2955 }
2956}
2957
2958#[stable(feature = "rust1", since = "1.0.0")]
2959unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc<T, A> {
2960 /// Drops the `Arc`.
2961 ///
2962 /// This will decrement the strong reference count. If the strong reference
2963 /// count reaches zero then the only other references (if any) are
2964 /// [`Weak`], so we `drop` the inner value.
2965 ///
2966 /// # Examples
2967 ///
2968 /// ```
2969 /// use std::sync::Arc;
2970 ///
2971 /// struct Foo;
2972 ///
2973 /// impl Drop for Foo {
2974 /// fn drop(&mut self) {
2975 /// println!("dropped!");
2976 /// }
2977 /// }
2978 ///
2979 /// let foo = Arc::new(Foo);
2980 /// let foo2 = Arc::clone(&foo);
2981 ///
2982 /// drop(foo); // Doesn't print anything
2983 /// drop(foo2); // Prints "dropped!"
2984 /// ```
2985 #[inline]
2986 fn drop(&mut self) {
2987 // Because `fetch_sub` is already atomic, we do not need to synchronize
2988 // with other threads unless we are going to delete the object. This
2989 // same logic applies to the below `fetch_sub` to the `weak` count.
2990 if self.inner().strong.fetch_sub(1, Release) != 1 {
2991 return;
2992 }
2993
2994 // This fence is needed to prevent reordering of use of the data and
2995 // deletion of the data. Because it is marked `Release`, the decreasing
2996 // of the reference count synchronizes with this `Acquire` fence. This
2997 // means that use of the data happens before decreasing the reference
2998 // count, which happens before this fence, which happens before the
2999 // deletion of the data.
3000 //
3001 // As explained in the [Boost documentation][1],
3002 //
3003 // > It is important to enforce any possible access to the object in one
3004 // > thread (through an existing reference) to *happen before* deleting
3005 // > the object in a different thread. This is achieved by a "release"
3006 // > operation after dropping a reference (any access to the object
3007 // > through this reference must obviously happened before), and an
3008 // > "acquire" operation before deleting the object.
3009 //
3010 // In particular, while the contents of an Arc are usually immutable, it's
3011 // possible to have interior writes to something like a Mutex<T>. Since a
3012 // Mutex is not acquired when it is deleted, we can't rely on its
3013 // synchronization logic to make writes in thread A visible to a destructor
3014 // running in thread B.
3015 //
3016 // Also note that the Acquire fence here could probably be replaced with an
3017 // Acquire load, which could improve performance in highly-contended
3018 // situations. See [2].
3019 //
3020 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
3021 // [2]: (https://github.com/rust-lang/rust/pull/41714)
3022 acquire!(self.inner().strong);
3023
3024 // Make sure we aren't trying to "drop" the shared static for empty slices
3025 // used by Default::default.
3026 debug_assert!(
3027 !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner),
3028 "Arcs backed by a static should never reach a strong count of 0. \
3029 Likely decrement_strong_count or from_raw were called too many times.",
3030 );
3031
3032 // ignore-tidy-undocumented-unsafe
3033 unsafe {
3034 self.drop_slow();
3035 }
3036 }
3037}
3038
3039impl<A: Allocator> Arc<dyn Any + Send + Sync, A> {
3040 /// Attempts to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
3041 ///
3042 /// # Examples
3043 ///
3044 /// ```
3045 /// use std::any::Any;
3046 /// use std::sync::Arc;
3047 ///
3048 /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
3049 /// if let Ok(string) = value.downcast::<String>() {
3050 /// println!("String ({}): {}", string.len(), string);
3051 /// }
3052 /// }
3053 ///
3054 /// let my_string = "Hello World".to_string();
3055 /// print_if_string(Arc::new(my_string));
3056 /// print_if_string(Arc::new(0i8));
3057 /// ```
3058 #[inline]
3059 #[stable(feature = "rc_downcast", since = "1.29.0")]
3060 pub fn downcast<T>(self) -> Result<Arc<T, A>, Self>
3061 where
3062 T: Any,
3063 {
3064 if (*self).is::<T>() {
3065 // SAFETY: Check ensures the typecast is okay.
3066 unsafe {
3067 let (ptr, alloc) = Arc::into_inner_with_allocator(self);
3068 Ok(Arc::from_inner_in(ptr.cast(), alloc))
3069 }
3070 } else {
3071 Err(self)
3072 }
3073 }
3074
3075 /// Downcasts the `Arc<dyn Any + Send + Sync>` to a concrete type.
3076 ///
3077 /// For a safe alternative see [`downcast`].
3078 ///
3079 /// # Examples
3080 ///
3081 /// ```
3082 /// #![feature(downcast_unchecked)]
3083 ///
3084 /// use std::any::Any;
3085 /// use std::sync::Arc;
3086 ///
3087 /// let x: Arc<dyn Any + Send + Sync> = Arc::new(1_usize);
3088 ///
3089 /// unsafe {
3090 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
3091 /// }
3092 /// ```
3093 ///
3094 /// # Safety
3095 ///
3096 /// The contained value must be of type `T`. Calling this method
3097 /// with the incorrect type is *undefined behavior*.
3098 ///
3099 ///
3100 /// [`downcast`]: Self::downcast
3101 #[inline]
3102 #[unstable(feature = "downcast_unchecked", issue = "90850")]
3103 pub unsafe fn downcast_unchecked<T>(self) -> Arc<T, A>
3104 where
3105 T: Any,
3106 {
3107 // SAFETY: Upheld by caller.
3108 unsafe {
3109 let (ptr, alloc) = Arc::into_inner_with_allocator(self);
3110 Arc::from_inner_in(ptr.cast(), alloc)
3111 }
3112 }
3113}
3114
3115impl<T> Weak<T> {
3116 /// Constructs a new `Weak<T>`, without allocating any memory.
3117 /// Calling [`upgrade`] on the return value always gives [`None`].
3118 ///
3119 /// [`upgrade`]: Weak::upgrade
3120 ///
3121 /// # Examples
3122 ///
3123 /// ```
3124 /// use std::sync::Weak;
3125 ///
3126 /// let empty: Weak<i64> = Weak::new();
3127 /// assert!(empty.upgrade().is_none());
3128 /// ```
3129 #[inline]
3130 #[stable(feature = "downgraded_weak", since = "1.10.0")]
3131 #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")]
3132 #[must_use]
3133 pub const fn new() -> Weak<T> {
3134 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global }
3135 }
3136}
3137
3138impl<T, A: Allocator> Weak<T, A> {
3139 /// Constructs a new `Weak<T, A>`, without allocating any memory, technically in the provided
3140 /// allocator.
3141 /// Calling [`upgrade`] on the return value always gives [`None`].
3142 ///
3143 /// [`upgrade`]: Weak::upgrade
3144 ///
3145 /// # Examples
3146 ///
3147 /// ```
3148 /// #![feature(allocator_ext)]
3149 ///
3150 /// use std::sync::Weak;
3151 /// use std::alloc::System;
3152 ///
3153 /// let empty: Weak<i64, _> = Weak::new_in(System);
3154 /// assert!(empty.upgrade().is_none());
3155 /// ```
3156 #[inline]
3157 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3158 pub fn new_in(alloc: A) -> Weak<T, A> {
3159 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc }
3160 }
3161}
3162
3163/// Helper type to allow accessing the reference counts without
3164/// making any assertions about the data field.
3165struct WeakInner<'a> {
3166 weak: &'a Atomic<usize>,
3167 strong: &'a Atomic<usize>,
3168}
3169
3170impl<T: ?Sized> Weak<T> {
3171 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3172 ///
3173 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3174 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3175 ///
3176 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3177 /// as these don't own anything; the method still works on them).
3178 ///
3179 /// # Safety
3180 ///
3181 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3182 /// weak reference, and must point to a block of memory allocated by global allocator.
3183 ///
3184 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3185 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3186 /// count is not modified by this operation) and therefore it must be paired with a previous
3187 /// call to [`into_raw`].
3188 /// # Examples
3189 ///
3190 /// ```
3191 /// use std::sync::{Arc, Weak};
3192 ///
3193 /// let strong = Arc::new("hello".to_owned());
3194 ///
3195 /// let raw_1 = Arc::downgrade(&strong).into_raw();
3196 /// let raw_2 = Arc::downgrade(&strong).into_raw();
3197 ///
3198 /// assert_eq!(2, Arc::weak_count(&strong));
3199 ///
3200 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3201 /// assert_eq!(1, Arc::weak_count(&strong));
3202 ///
3203 /// drop(strong);
3204 ///
3205 /// // Decrement the last weak count.
3206 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3207 /// ```
3208 ///
3209 /// [`new`]: Weak::new
3210 /// [`into_raw`]: Weak::into_raw
3211 /// [`upgrade`]: Weak::upgrade
3212 #[inline]
3213 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3214 pub unsafe fn from_raw(ptr: *const T) -> Self {
3215 // SAFETY: Upheld by caller.
3216 unsafe { Weak::from_raw_in(ptr, Global) }
3217 }
3218
3219 /// Consumes the `Weak<T>` and turns it into a raw pointer.
3220 ///
3221 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3222 /// one weak reference (the weak count is not modified by this operation). It can be turned
3223 /// back into the `Weak<T>` with [`from_raw`].
3224 ///
3225 /// The same restrictions of accessing the target of the pointer as with
3226 /// [`as_ptr`] apply.
3227 ///
3228 /// # Examples
3229 ///
3230 /// ```
3231 /// use std::sync::{Arc, Weak};
3232 ///
3233 /// let strong = Arc::new("hello".to_owned());
3234 /// let weak = Arc::downgrade(&strong);
3235 /// let raw = weak.into_raw();
3236 ///
3237 /// assert_eq!(1, Arc::weak_count(&strong));
3238 /// assert_eq!("hello", unsafe { &*raw });
3239 ///
3240 /// drop(unsafe { Weak::from_raw(raw) });
3241 /// assert_eq!(0, Arc::weak_count(&strong));
3242 /// ```
3243 ///
3244 /// [`from_raw`]: Weak::from_raw
3245 /// [`as_ptr`]: Weak::as_ptr
3246 #[must_use = "losing the pointer will leak memory"]
3247 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3248 pub fn into_raw(self) -> *const T {
3249 ManuallyDrop::new(self).as_ptr()
3250 }
3251}
3252
3253impl<T: ?Sized, A: Allocator> Weak<T, A> {
3254 /// Returns a reference to the underlying allocator.
3255 #[inline]
3256 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3257 pub fn allocator(&self) -> &A {
3258 &self.alloc
3259 }
3260
3261 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
3262 ///
3263 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
3264 /// unaligned or even [`null`] otherwise.
3265 ///
3266 /// # Examples
3267 ///
3268 /// ```
3269 /// use std::sync::Arc;
3270 /// use std::ptr;
3271 ///
3272 /// let strong = Arc::new("hello".to_owned());
3273 /// let weak = Arc::downgrade(&strong);
3274 /// // Both point to the same object
3275 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
3276 /// // The strong here keeps it alive, so we can still access the object.
3277 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
3278 ///
3279 /// drop(strong);
3280 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
3281 /// // undefined behavior.
3282 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
3283 /// ```
3284 ///
3285 /// [`null`]: core::ptr::null "ptr::null"
3286 #[must_use]
3287 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3288 pub fn as_ptr(&self) -> *const T {
3289 let ptr: *mut ArcInner<T> = NonNull::as_ptr(self.ptr);
3290
3291 if is_dangling(ptr) {
3292 // If the pointer is dangling, we return the sentinel directly. This cannot be
3293 // a valid payload address, as the payload is at least as aligned as ArcInner (usize).
3294 ptr as *const T
3295 } else {
3296 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
3297 // The payload may be dropped at this point, and we have to maintain provenance,
3298 // so use raw pointer manipulation.
3299 unsafe { &raw mut (*ptr).data }
3300 }
3301 }
3302
3303 /// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
3304 ///
3305 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3306 /// one weak reference (the weak count is not modified by this operation). It can be turned
3307 /// back into the `Weak<T>` with [`from_raw_in`].
3308 ///
3309 /// The same restrictions of accessing the target of the pointer as with
3310 /// [`as_ptr`] apply.
3311 ///
3312 /// # Examples
3313 ///
3314 /// ```
3315 /// #![feature(allocator_ext)]
3316 /// use std::sync::{Arc, Weak};
3317 /// use std::alloc::System;
3318 ///
3319 /// let strong = Arc::new_in("hello".to_owned(), System);
3320 /// let weak = Arc::downgrade(&strong);
3321 /// let (raw, alloc) = weak.into_raw_with_allocator();
3322 ///
3323 /// assert_eq!(1, Arc::weak_count(&strong));
3324 /// assert_eq!("hello", unsafe { &*raw });
3325 ///
3326 /// drop(unsafe { Weak::from_raw_in(raw, alloc) });
3327 /// assert_eq!(0, Arc::weak_count(&strong));
3328 /// ```
3329 ///
3330 /// [`from_raw_in`]: Weak::from_raw_in
3331 /// [`as_ptr`]: Weak::as_ptr
3332 #[must_use = "losing the pointer will leak memory"]
3333 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3334 pub fn into_raw_with_allocator(self) -> (*const T, A) {
3335 let this = mem::ManuallyDrop::new(self);
3336 let result = this.as_ptr();
3337 // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped
3338 let alloc = unsafe { ptr::read(&this.alloc) };
3339 (result, alloc)
3340 }
3341
3342 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>` in the provided
3343 /// allocator.
3344 ///
3345 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3346 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3347 ///
3348 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3349 /// as these don't own anything; the method still works on them).
3350 ///
3351 /// # Safety
3352 ///
3353 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3354 /// weak reference, and must point to a block of memory allocated by `alloc`.
3355 ///
3356 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3357 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3358 /// count is not modified by this operation) and therefore it must be paired with a previous
3359 /// call to [`into_raw`].
3360 /// # Examples
3361 ///
3362 /// ```
3363 /// use std::sync::{Arc, Weak};
3364 ///
3365 /// let strong = Arc::new("hello".to_owned());
3366 ///
3367 /// let raw_1 = Arc::downgrade(&strong).into_raw();
3368 /// let raw_2 = Arc::downgrade(&strong).into_raw();
3369 ///
3370 /// assert_eq!(2, Arc::weak_count(&strong));
3371 ///
3372 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3373 /// assert_eq!(1, Arc::weak_count(&strong));
3374 ///
3375 /// drop(strong);
3376 ///
3377 /// // Decrement the last weak count.
3378 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3379 /// ```
3380 ///
3381 /// [`new`]: Weak::new
3382 /// [`into_raw`]: Weak::into_raw
3383 /// [`upgrade`]: Weak::upgrade
3384 #[inline]
3385 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3386 pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
3387 // See Weak::as_ptr for context on how the input pointer is derived.
3388
3389 let ptr = if is_dangling(ptr) {
3390 // This is a dangling Weak.
3391 ptr as *mut ArcInner<T>
3392 } else {
3393 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
3394 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
3395 let offset = unsafe { data_offset(ptr) };
3396 // Thus, we reverse the offset to get the whole ArcInner.
3397 // SAFETY: the pointer originated from a Weak, so this offset is safe.
3398 unsafe { ptr.byte_sub(offset) as *mut ArcInner<T> }
3399 };
3400
3401 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
3402 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc }
3403 }
3404}
3405
3406impl<T: ?Sized, A: Allocator> Weak<T, A> {
3407 /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying
3408 /// dropping of the inner value if successful.
3409 ///
3410 /// Returns [`None`] in the following cases:
3411 ///
3412 /// 1. The inner value has since been dropped or moved out.
3413 ///
3414 /// 2. This `Weak` does not point to an allocation.
3415 ///
3416 /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade.
3417 ///
3418 /// # Examples
3419 ///
3420 /// ```
3421 /// use std::sync::Arc;
3422 ///
3423 /// let five = Arc::new(5);
3424 ///
3425 /// let weak_five = Arc::downgrade(&five);
3426 ///
3427 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
3428 /// assert!(strong_five.is_some());
3429 ///
3430 /// // Destroy all strong pointers.
3431 /// drop(strong_five);
3432 /// drop(five);
3433 ///
3434 /// assert!(weak_five.upgrade().is_none());
3435 /// ```
3436 #[must_use = "this returns a new `Arc`, \
3437 without modifying the original weak pointer"]
3438 #[stable(feature = "arc_weak", since = "1.4.0")]
3439 pub fn upgrade(&self) -> Option<Arc<T, A>>
3440 where
3441 A: AllocatorClone,
3442 {
3443 #[inline]
3444 fn checked_increment(n: usize) -> Option<usize> {
3445 // Any write of 0 we can observe leaves the field in permanently zero state.
3446 if n == 0 {
3447 return None;
3448 }
3449 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
3450 if n > MAX_REFCOUNT {
3451 panic_arc_overflow();
3452 }
3453 Some(n + 1)
3454 }
3455
3456 // We use a CAS loop to increment the strong count instead of a
3457 // fetch_add as this function should never take the reference count
3458 // from zero to one.
3459 //
3460 // Relaxed is fine for the failure case because we don't have any expectations about the new state.
3461 // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner
3462 // value can be initialized after `Weak` references have already been created. In that case, we
3463 // expect to observe the fully initialized value.
3464 if self.inner()?.strong.try_update(Acquire, Relaxed, checked_increment).is_ok() {
3465 // SAFETY: pointer is not null, verified in checked_increment
3466 unsafe { Some(Arc::from_inner_in(self.ptr, self.alloc.clone())) }
3467 } else {
3468 None
3469 }
3470 }
3471
3472 /// Gets the number of strong (`Arc`) pointers pointing to this allocation.
3473 ///
3474 /// If `self` was created using [`Weak::new`], this will return 0.
3475 #[must_use]
3476 #[stable(feature = "weak_counts", since = "1.41.0")]
3477 pub fn strong_count(&self) -> usize {
3478 if let Some(inner) = self.inner() { inner.strong.load(Relaxed) } else { 0 }
3479 }
3480
3481 /// Gets an approximation of the number of `Weak` pointers pointing to this
3482 /// allocation.
3483 ///
3484 /// If `self` was created using [`Weak::new`], or if there are no remaining
3485 /// strong pointers, this will return 0.
3486 ///
3487 /// # Accuracy
3488 ///
3489 /// Due to implementation details, the returned value can be off by 1 in
3490 /// either direction when other threads are manipulating any `Arc`s or
3491 /// `Weak`s pointing to the same allocation.
3492 #[must_use]
3493 #[stable(feature = "weak_counts", since = "1.41.0")]
3494 pub fn weak_count(&self) -> usize {
3495 if let Some(inner) = self.inner() {
3496 let weak = inner.weak.load(Acquire);
3497 let strong = inner.strong.load(Relaxed);
3498 if strong == 0 {
3499 0
3500 } else {
3501 // Since we observed that there was at least one strong pointer
3502 // after reading the weak count, we know that the implicit weak
3503 // reference (present whenever any strong references are alive)
3504 // was still around when we observed the weak count, and can
3505 // therefore safely subtract it.
3506 weak - 1
3507 }
3508 } else {
3509 0
3510 }
3511 }
3512
3513 /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
3514 /// (i.e., when this `Weak` was created by `Weak::new`).
3515 #[inline]
3516 fn inner(&self) -> Option<WeakInner<'_>> {
3517 let ptr = self.ptr.as_ptr();
3518 if is_dangling(ptr) {
3519 None
3520 } else {
3521 // We are careful to *not* create a reference covering the "data" field, as
3522 // the field may be mutated concurrently (for example, if the last `Arc`
3523 // is dropped, the data field will be dropped in-place).
3524 // ignore-tidy-undocumented-unsafe
3525 Some(unsafe { WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } })
3526 }
3527 }
3528
3529 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::addr_eq`], or if
3530 /// both don't point to any allocation (because they were created with `Weak::new()`). However,
3531 /// this function ignores the metadata of wide pointers.
3532 ///
3533 /// # Notes
3534 ///
3535 /// Since this compares pointers it means that `Weak::new()` will equal each
3536 /// other, even though they don't point to any allocation.
3537 ///
3538 /// # Examples
3539 ///
3540 /// ```
3541 /// use std::sync::Arc;
3542 ///
3543 /// let first_rc = Arc::new(5);
3544 /// let first = Arc::downgrade(&first_rc);
3545 /// let second = Arc::downgrade(&first_rc);
3546 ///
3547 /// assert!(first.ptr_eq(&second));
3548 ///
3549 /// let third_rc = Arc::new(5);
3550 /// let third = Arc::downgrade(&third_rc);
3551 ///
3552 /// assert!(!first.ptr_eq(&third));
3553 /// ```
3554 ///
3555 /// Comparing `Weak::new`.
3556 ///
3557 /// ```
3558 /// use std::sync::{Arc, Weak};
3559 ///
3560 /// let first = Weak::new();
3561 /// let second = Weak::new();
3562 /// assert!(first.ptr_eq(&second));
3563 ///
3564 /// let third_rc = Arc::new(());
3565 /// let third = Arc::downgrade(&third_rc);
3566 /// assert!(!first.ptr_eq(&third));
3567 /// ```
3568 ///
3569 /// [`ptr::eq`]: core::ptr::eq "ptr::eq"
3570 #[inline]
3571 #[must_use]
3572 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
3573 pub fn ptr_eq(&self, other: &Self) -> bool {
3574 ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr())
3575 }
3576}
3577
3578#[stable(feature = "arc_weak", since = "1.4.0")]
3579impl<T: ?Sized, A: AllocatorClone> Clone for Weak<T, A> {
3580 /// Makes a clone of the `Weak` pointer that points to the same allocation.
3581 ///
3582 /// # Examples
3583 ///
3584 /// ```
3585 /// use std::sync::{Arc, Weak};
3586 ///
3587 /// let weak_five = Arc::downgrade(&Arc::new(5));
3588 ///
3589 /// let _ = Weak::clone(&weak_five);
3590 /// ```
3591 #[inline]
3592 fn clone(&self) -> Weak<T, A> {
3593 if let Some(inner) = self.inner() {
3594 // See comments in Arc::clone() for why this is relaxed. This can use a
3595 // fetch_add (ignoring the lock) because the weak count is only locked
3596 // where are *no other* weak pointers in existence. (So we can't be
3597 // running this code in that case).
3598 let old_size = inner.weak.fetch_add(1, Relaxed);
3599
3600 // See comments in Arc::clone() for why we do this (for mem::forget).
3601 if old_size > MAX_REFCOUNT {
3602 intrinsics::abort_immediate();
3603 }
3604 }
3605
3606 Weak { ptr: self.ptr, alloc: self.alloc.clone() }
3607 }
3608}
3609
3610#[unstable(feature = "ergonomic_clones", issue = "132290")]
3611impl<T: ?Sized, A: AllocatorClone> UseCloned for Weak<T, A> {}
3612
3613#[stable(feature = "downgraded_weak", since = "1.10.0")]
3614impl<T> Default for Weak<T> {
3615 /// Constructs a new `Weak<T>`, without allocating memory.
3616 /// Calling [`upgrade`] on the return value always
3617 /// gives [`None`].
3618 ///
3619 /// [`upgrade`]: Weak::upgrade
3620 ///
3621 /// # Examples
3622 ///
3623 /// ```
3624 /// use std::sync::Weak;
3625 ///
3626 /// let empty: Weak<i64> = Default::default();
3627 /// assert!(empty.upgrade().is_none());
3628 /// ```
3629 fn default() -> Weak<T> {
3630 Weak::new()
3631 }
3632}
3633
3634#[stable(feature = "arc_weak", since = "1.4.0")]
3635unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak<T, A> {
3636 /// Drops the `Weak` pointer.
3637 ///
3638 /// # Examples
3639 ///
3640 /// ```
3641 /// use std::sync::{Arc, Weak};
3642 ///
3643 /// struct Foo;
3644 ///
3645 /// impl Drop for Foo {
3646 /// fn drop(&mut self) {
3647 /// println!("dropped!");
3648 /// }
3649 /// }
3650 ///
3651 /// let foo = Arc::new(Foo);
3652 /// let weak_foo = Arc::downgrade(&foo);
3653 /// let other_weak_foo = Weak::clone(&weak_foo);
3654 ///
3655 /// drop(weak_foo); // Doesn't print anything
3656 /// drop(foo); // Prints "dropped!"
3657 ///
3658 /// assert!(other_weak_foo.upgrade().is_none());
3659 /// ```
3660 fn drop(&mut self) {
3661 // If we find out that we were the last weak pointer, then its time to
3662 // deallocate the data entirely. See the discussion in Arc::drop() about
3663 // the memory orderings
3664 //
3665 // It's not necessary to check for the locked state here, because the
3666 // weak count can only be locked if there was precisely one weak ref,
3667 // meaning that drop could only subsequently run ON that remaining weak
3668 // ref, which can only happen after the lock is released.
3669 let inner = if let Some(inner) = self.inner() { inner } else { return };
3670
3671 if inner.weak.fetch_sub(1, Release) == 1 {
3672 acquire!(inner.weak);
3673
3674 // Make sure we aren't trying to "deallocate" the shared static for empty slices
3675 // used by Default::default.
3676 debug_assert!(
3677 !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner),
3678 "Arc/Weaks backed by a static should never be deallocated. \
3679 Likely decrement_strong_count or from_raw were called too many times.",
3680 );
3681
3682 // ignore-tidy-undocumented-unsafe
3683 unsafe {
3684 self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()))
3685 }
3686 }
3687 }
3688}
3689
3690#[stable(feature = "rust1", since = "1.0.0")]
3691trait ArcEqIdent<T: ?Sized + PartialEq, A: Allocator> {
3692 fn eq(&self, other: &Arc<T, A>) -> bool;
3693 fn ne(&self, other: &Arc<T, A>) -> bool;
3694}
3695
3696#[stable(feature = "rust1", since = "1.0.0")]
3697impl<T: ?Sized + PartialEq, A: Allocator> ArcEqIdent<T, A> for Arc<T, A> {
3698 #[inline]
3699 default fn eq(&self, other: &Arc<T, A>) -> bool {
3700 **self == **other
3701 }
3702 #[inline]
3703 default fn ne(&self, other: &Arc<T, A>) -> bool {
3704 **self != **other
3705 }
3706}
3707
3708/// We're doing this specialization here, and not as a more general optimization on `&T`, because it
3709/// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
3710/// store large values, that are slow to clone, but also heavy to check for equality, causing this
3711/// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
3712/// the same value, than two `&T`s.
3713///
3714/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
3715#[stable(feature = "rust1", since = "1.0.0")]
3716impl<T: ?Sized + crate::rc::MarkerEq, A: Allocator> ArcEqIdent<T, A> for Arc<T, A> {
3717 #[inline]
3718 fn eq(&self, other: &Arc<T, A>) -> bool {
3719 ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other
3720 }
3721
3722 #[inline]
3723 fn ne(&self, other: &Arc<T, A>) -> bool {
3724 !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other
3725 }
3726}
3727
3728#[stable(feature = "rust1", since = "1.0.0")]
3729impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Arc<T, A> {
3730 /// Equality for two `Arc`s.
3731 ///
3732 /// Two `Arc`s are equal if their inner values are equal, even if they are
3733 /// stored in different allocation.
3734 ///
3735 /// If `T` also implements `Eq` (implying reflexivity of equality),
3736 /// two `Arc`s that point to the same allocation are always equal.
3737 ///
3738 /// # Examples
3739 ///
3740 /// ```
3741 /// use std::sync::Arc;
3742 ///
3743 /// let five = Arc::new(5);
3744 ///
3745 /// assert!(five == Arc::new(5));
3746 /// ```
3747 #[inline]
3748 fn eq(&self, other: &Arc<T, A>) -> bool {
3749 ArcEqIdent::eq(self, other)
3750 }
3751
3752 /// Inequality for two `Arc`s.
3753 ///
3754 /// Two `Arc`s are not equal if their inner values are not equal.
3755 ///
3756 /// If `T` also implements `Eq` (implying reflexivity of equality),
3757 /// two `Arc`s that point to the same value are always equal.
3758 ///
3759 /// # Examples
3760 ///
3761 /// ```
3762 /// use std::sync::Arc;
3763 ///
3764 /// let five = Arc::new(5);
3765 ///
3766 /// assert!(five != Arc::new(6));
3767 /// ```
3768 #[inline]
3769 fn ne(&self, other: &Arc<T, A>) -> bool {
3770 ArcEqIdent::ne(self, other)
3771 }
3772}
3773
3774#[stable(feature = "rust1", since = "1.0.0")]
3775impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Arc<T, A> {
3776 /// Partial comparison for two `Arc`s.
3777 ///
3778 /// The two are compared by calling `partial_cmp()` on their inner values.
3779 ///
3780 /// # Examples
3781 ///
3782 /// ```
3783 /// use std::sync::Arc;
3784 /// use std::cmp::Ordering;
3785 ///
3786 /// let five = Arc::new(5);
3787 ///
3788 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
3789 /// ```
3790 fn partial_cmp(&self, other: &Arc<T, A>) -> Option<Ordering> {
3791 (**self).partial_cmp(&**other)
3792 }
3793
3794 /// Less-than comparison for two `Arc`s.
3795 ///
3796 /// The two are compared by calling `<` on their inner values.
3797 ///
3798 /// # Examples
3799 ///
3800 /// ```
3801 /// use std::sync::Arc;
3802 ///
3803 /// let five = Arc::new(5);
3804 ///
3805 /// assert!(five < Arc::new(6));
3806 /// ```
3807 fn lt(&self, other: &Arc<T, A>) -> bool {
3808 *(*self) < *(*other)
3809 }
3810
3811 /// 'Less than or equal to' comparison for two `Arc`s.
3812 ///
3813 /// The two are compared by calling `<=` on their inner values.
3814 ///
3815 /// # Examples
3816 ///
3817 /// ```
3818 /// use std::sync::Arc;
3819 ///
3820 /// let five = Arc::new(5);
3821 ///
3822 /// assert!(five <= Arc::new(5));
3823 /// ```
3824 fn le(&self, other: &Arc<T, A>) -> bool {
3825 *(*self) <= *(*other)
3826 }
3827
3828 /// Greater-than comparison for two `Arc`s.
3829 ///
3830 /// The two are compared by calling `>` on their inner values.
3831 ///
3832 /// # Examples
3833 ///
3834 /// ```
3835 /// use std::sync::Arc;
3836 ///
3837 /// let five = Arc::new(5);
3838 ///
3839 /// assert!(five > Arc::new(4));
3840 /// ```
3841 fn gt(&self, other: &Arc<T, A>) -> bool {
3842 *(*self) > *(*other)
3843 }
3844
3845 /// 'Greater than or equal to' comparison for two `Arc`s.
3846 ///
3847 /// The two are compared by calling `>=` on their inner values.
3848 ///
3849 /// # Examples
3850 ///
3851 /// ```
3852 /// use std::sync::Arc;
3853 ///
3854 /// let five = Arc::new(5);
3855 ///
3856 /// assert!(five >= Arc::new(5));
3857 /// ```
3858 fn ge(&self, other: &Arc<T, A>) -> bool {
3859 *(*self) >= *(*other)
3860 }
3861}
3862#[stable(feature = "rust1", since = "1.0.0")]
3863impl<T: ?Sized + Ord, A: Allocator> Ord for Arc<T, A> {
3864 /// Comparison for two `Arc`s.
3865 ///
3866 /// The two are compared by calling `cmp()` on their inner values.
3867 ///
3868 /// # Examples
3869 ///
3870 /// ```
3871 /// use std::sync::Arc;
3872 /// use std::cmp::Ordering;
3873 ///
3874 /// let five = Arc::new(5);
3875 ///
3876 /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
3877 /// ```
3878 fn cmp(&self, other: &Arc<T, A>) -> Ordering {
3879 (**self).cmp(&**other)
3880 }
3881}
3882#[stable(feature = "rust1", since = "1.0.0")]
3883impl<T: ?Sized + Eq, A: Allocator> Eq for Arc<T, A> {}
3884
3885#[stable(feature = "rust1", since = "1.0.0")]
3886impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for Arc<T, A> {
3887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3888 fmt::Display::fmt(&**self, f)
3889 }
3890}
3891
3892#[stable(feature = "rust1", since = "1.0.0")]
3893impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Arc<T, A> {
3894 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3895 fmt::Debug::fmt(&**self, f)
3896 }
3897}
3898
3899#[stable(feature = "rust1", since = "1.0.0")]
3900impl<T: ?Sized, A: Allocator> fmt::Pointer for Arc<T, A> {
3901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3902 fmt::Pointer::fmt(&(&raw const **self), f)
3903 }
3904}
3905
3906#[cfg(not(no_global_oom_handling))]
3907#[stable(feature = "rust1", since = "1.0.0")]
3908impl<T: Default> Default for Arc<T> {
3909 /// Creates a new `Arc<T>`, with the `Default` value for `T`.
3910 ///
3911 /// # Examples
3912 ///
3913 /// ```
3914 /// use std::sync::Arc;
3915 ///
3916 /// let x: Arc<i32> = Default::default();
3917 /// assert_eq!(*x, 0);
3918 /// ```
3919 fn default() -> Arc<T> {
3920 // ignore-tidy-undocumented-unsafe
3921 unsafe {
3922 Self::from_inner(Box::into_non_null(Box::write(
3923 Box::new_uninit(),
3924 ArcInner {
3925 strong: atomic::AtomicUsize::new(1),
3926 weak: atomic::AtomicUsize::new(1),
3927 data: T::default(),
3928 },
3929 )))
3930 }
3931 }
3932}
3933
3934/// Struct to hold the static `ArcInner` used for empty `Arc<str/CStr/[T]>` as
3935/// returned by `Default::default`.
3936///
3937/// Layout notes:
3938/// * `repr(align(16))` so we can use it for `[T]` with `align_of::<T>() <= 16`.
3939/// * `repr(C)` so `inner` is at offset 0 (and thus guaranteed to actually be aligned to 16).
3940/// * `[u8; 1]` (to be initialized with 0) so it can be used for `Arc<CStr>`.
3941#[repr(C, align(16))]
3942struct SliceArcInnerForStatic {
3943 inner: ArcInner<[u8; 1]>,
3944}
3945#[cfg(not(no_global_oom_handling))]
3946const MAX_STATIC_INNER_SLICE_ALIGNMENT: usize = 16;
3947
3948static STATIC_INNER_SLICE: SliceArcInnerForStatic = SliceArcInnerForStatic {
3949 inner: ArcInner {
3950 strong: atomic::AtomicUsize::new(1),
3951 weak: atomic::AtomicUsize::new(1),
3952 data: [0],
3953 },
3954};
3955
3956#[cfg(not(no_global_oom_handling))]
3957#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
3958impl Default for Arc<str> {
3959 /// Creates an empty str inside an Arc
3960 ///
3961 /// This may or may not share an allocation with other Arcs.
3962 #[inline]
3963 fn default() -> Self {
3964 let arc: Arc<[u8]> = Default::default();
3965 debug_assert!(core::str::from_utf8(&arc).is_ok());
3966 let (ptr, alloc) = Arc::into_inner_with_allocator(arc);
3967 // ignore-tidy-undocumented-unsafe
3968 unsafe { Arc::from_ptr_in(ptr.as_ptr() as *mut ArcInner<str>, alloc) }
3969 }
3970}
3971
3972#[cfg(not(no_global_oom_handling))]
3973#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
3974impl Default for Arc<core::ffi::CStr> {
3975 /// Creates an empty CStr inside an Arc
3976 ///
3977 /// This may or may not share an allocation with other Arcs.
3978 #[inline]
3979 fn default() -> Self {
3980 use core::ffi::CStr;
3981 let inner: NonNull<ArcInner<[u8]>> = NonNull::from(&STATIC_INNER_SLICE.inner);
3982 let inner: NonNull<ArcInner<CStr>> =
3983 NonNull::new(inner.as_ptr() as *mut ArcInner<CStr>).unwrap();
3984 // `this` semantically is the Arc "owned" by the static, so make sure not to drop it.
3985 let this: mem::ManuallyDrop<Arc<CStr>> =
3986 // ignore-tidy-undocumented-unsafe
3987 unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) };
3988 (*this).clone()
3989 }
3990}
3991
3992#[cfg(not(no_global_oom_handling))]
3993#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
3994impl<T> Default for Arc<[T]> {
3995 /// Creates an empty `[T]` inside an Arc
3996 ///
3997 /// This may or may not share an allocation with other Arcs.
3998 #[inline]
3999 fn default() -> Self {
4000 if align_of::<T>() <= MAX_STATIC_INNER_SLICE_ALIGNMENT {
4001 // We take a reference to the whole struct instead of the ArcInner<[u8; 1]> inside it so
4002 // we don't shrink the range of bytes the ptr is allowed to access under Stacked Borrows.
4003 // (Miri complains on 32-bit targets with Arc<[Align16]> otherwise.)
4004 // (Note that NonNull::from(&STATIC_INNER_SLICE.inner) is fine under Tree Borrows.)
4005 let inner: NonNull<SliceArcInnerForStatic> = NonNull::from(&STATIC_INNER_SLICE);
4006 let inner: NonNull<ArcInner<[T; 0]>> = inner.cast();
4007 // `this` semantically is the Arc "owned" by the static, so make sure not to drop it.
4008 let this: mem::ManuallyDrop<Arc<[T; 0]>> =
4009 // ignore-tidy-undocumented-unsafe
4010 unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) };
4011 return (*this).clone();
4012 }
4013
4014 // If T's alignment is too large for the static, make a new unique allocation.
4015 let arr: [T; 0] = [];
4016 Arc::from(arr)
4017 }
4018}
4019
4020#[cfg(not(no_global_oom_handling))]
4021#[stable(feature = "pin_default_impls", since = "1.91.0")]
4022impl<T> Default for Pin<Arc<T>>
4023where
4024 T: ?Sized,
4025 Arc<T>: Default,
4026{
4027 #[inline]
4028 fn default() -> Self {
4029 // SAFETY: We own and create the pinned pointer.
4030 unsafe { Pin::new_unchecked(Arc::<T>::default()) }
4031 }
4032}
4033
4034#[stable(feature = "rust1", since = "1.0.0")]
4035impl<T: ?Sized + Hash, A: Allocator> Hash for Arc<T, A> {
4036 fn hash<H: Hasher>(&self, state: &mut H) {
4037 (**self).hash(state)
4038 }
4039}
4040
4041#[cfg(not(no_global_oom_handling))]
4042#[stable(feature = "from_for_ptrs", since = "1.6.0")]
4043impl<T> From<T> for Arc<T> {
4044 /// Converts a `T` into an `Arc<T>`
4045 ///
4046 /// The conversion moves the value into a
4047 /// newly allocated `Arc`. It is equivalent to
4048 /// calling `Arc::new(t)`.
4049 ///
4050 /// # Example
4051 /// ```rust
4052 /// # use std::sync::Arc;
4053 /// let x = 5;
4054 /// let arc = Arc::new(5);
4055 ///
4056 /// assert_eq!(Arc::from(x), arc);
4057 /// ```
4058 fn from(t: T) -> Self {
4059 Arc::new(t)
4060 }
4061}
4062
4063#[cfg(not(no_global_oom_handling))]
4064#[stable(feature = "shared_from_array", since = "1.74.0")]
4065impl<T, const N: usize> From<[T; N]> for Arc<[T]> {
4066 /// Converts a [`[T; N]`](prim@array) into an `Arc<[T]>`.
4067 ///
4068 /// The conversion moves the array into a newly allocated `Arc`.
4069 ///
4070 /// # Example
4071 ///
4072 /// ```
4073 /// # use std::sync::Arc;
4074 /// let original: [i32; 3] = [1, 2, 3];
4075 /// let shared: Arc<[i32]> = Arc::from(original);
4076 /// assert_eq!(&[1, 2, 3], &shared[..]);
4077 /// ```
4078 #[inline]
4079 fn from(v: [T; N]) -> Arc<[T]> {
4080 Arc::<[T; N]>::from(v)
4081 }
4082}
4083
4084#[cfg(not(no_global_oom_handling))]
4085#[stable(feature = "shared_from_slice", since = "1.21.0")]
4086impl<T: Clone> From<&[T]> for Arc<[T]> {
4087 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
4088 ///
4089 /// # Example
4090 ///
4091 /// ```
4092 /// # use std::sync::Arc;
4093 /// let original: &[i32] = &[1, 2, 3];
4094 /// let shared: Arc<[i32]> = Arc::from(original);
4095 /// assert_eq!(&[1, 2, 3], &shared[..]);
4096 /// ```
4097 #[inline]
4098 fn from(v: &[T]) -> Arc<[T]> {
4099 <Self as ArcFromSlice<T>>::from_slice(v)
4100 }
4101}
4102
4103#[cfg(not(no_global_oom_handling))]
4104#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
4105impl<T: Clone> From<&mut [T]> for Arc<[T]> {
4106 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
4107 ///
4108 /// # Example
4109 ///
4110 /// ```
4111 /// # use std::sync::Arc;
4112 /// let mut original = [1, 2, 3];
4113 /// let original: &mut [i32] = &mut original;
4114 /// let shared: Arc<[i32]> = Arc::from(original);
4115 /// assert_eq!(&[1, 2, 3], &shared[..]);
4116 /// ```
4117 #[inline]
4118 fn from(v: &mut [T]) -> Arc<[T]> {
4119 Arc::from(&*v)
4120 }
4121}
4122
4123#[cfg(not(no_global_oom_handling))]
4124#[stable(feature = "shared_from_slice", since = "1.21.0")]
4125impl From<&str> for Arc<str> {
4126 /// Allocates a reference-counted `str` and copies `v` into it.
4127 ///
4128 /// # Example
4129 ///
4130 /// ```
4131 /// # use std::sync::Arc;
4132 /// let shared: Arc<str> = Arc::from("eggplant");
4133 /// assert_eq!("eggplant", &shared[..]);
4134 /// ```
4135 #[inline]
4136 fn from(v: &str) -> Arc<str> {
4137 let arc = Arc::<[u8]>::from(v.as_bytes());
4138 // ignore-tidy-undocumented-unsafe
4139 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
4140 }
4141}
4142
4143#[cfg(not(no_global_oom_handling))]
4144#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
4145impl From<&mut str> for Arc<str> {
4146 /// Allocates a reference-counted `str` and copies `v` into it.
4147 ///
4148 /// # Example
4149 ///
4150 /// ```
4151 /// # use std::sync::Arc;
4152 /// let mut original = String::from("eggplant");
4153 /// let original: &mut str = &mut original;
4154 /// let shared: Arc<str> = Arc::from(original);
4155 /// assert_eq!("eggplant", &shared[..]);
4156 /// ```
4157 #[inline]
4158 fn from(v: &mut str) -> Arc<str> {
4159 Arc::from(&*v)
4160 }
4161}
4162
4163#[cfg(not(no_global_oom_handling))]
4164#[stable(feature = "shared_from_slice", since = "1.21.0")]
4165impl From<String> for Arc<str> {
4166 /// Allocates a reference-counted `str` and copies `v` into it.
4167 ///
4168 /// # Example
4169 ///
4170 /// ```
4171 /// # use std::sync::Arc;
4172 /// let unique: String = "eggplant".to_owned();
4173 /// let shared: Arc<str> = Arc::from(unique);
4174 /// assert_eq!("eggplant", &shared[..]);
4175 /// ```
4176 #[inline]
4177 fn from(v: String) -> Arc<str> {
4178 Arc::from(&v[..])
4179 }
4180}
4181
4182#[cfg(not(no_global_oom_handling))]
4183#[stable(feature = "shared_from_slice", since = "1.21.0")]
4184impl<T: ?Sized, A: AllocatorNightly> From<Box<T, A>> for Arc<T, A> {
4185 /// Move a boxed object to a new, reference-counted allocation.
4186 ///
4187 /// # Example
4188 ///
4189 /// ```
4190 /// # use std::sync::Arc;
4191 /// let unique: Box<str> = Box::from("eggplant");
4192 /// let shared: Arc<str> = Arc::from(unique);
4193 /// assert_eq!("eggplant", &shared[..]);
4194 /// ```
4195 #[inline]
4196 fn from(v: Box<T, A>) -> Arc<T, A> {
4197 Arc::from_box_in(v)
4198 }
4199}
4200
4201#[cfg(not(no_global_oom_handling))]
4202#[stable(feature = "shared_from_slice", since = "1.21.0")]
4203impl<T, A: AllocatorNightly> From<Vec<T, A>> for Arc<[T], A> {
4204 /// Allocates a reference-counted slice and moves `v`'s items into it.
4205 ///
4206 /// # Example
4207 ///
4208 /// ```
4209 /// # use std::sync::Arc;
4210 /// let unique: Vec<i32> = vec![1, 2, 3];
4211 /// let shared: Arc<[i32]> = Arc::from(unique);
4212 /// assert_eq!(&[1, 2, 3], &shared[..]);
4213 /// ```
4214 #[inline]
4215 fn from(v: Vec<T, A>) -> Arc<[T], A> {
4216 // ignore-tidy-undocumented-unsafe
4217 unsafe {
4218 let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator();
4219
4220 let rc_ptr = Self::allocate_for_slice_in(len, &alloc);
4221 ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len);
4222
4223 // Create a `Vec<T, &A>` with length 0, to deallocate the buffer
4224 // without dropping its contents or the allocator
4225 let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc);
4226
4227 Self::from_ptr_in(rc_ptr, alloc)
4228 }
4229 }
4230}
4231
4232#[stable(feature = "shared_from_cow", since = "1.45.0")]
4233impl<'a, B> From<Cow<'a, B>> for Arc<B>
4234where
4235 B: ToOwned + ?Sized,
4236 Arc<B>: From<&'a B> + From<B::Owned>,
4237{
4238 /// Creates an atomically reference-counted pointer from a clone-on-write
4239 /// pointer by copying its content.
4240 ///
4241 /// # Example
4242 ///
4243 /// ```rust
4244 /// # use std::sync::Arc;
4245 /// # use std::borrow::Cow;
4246 /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
4247 /// let shared: Arc<str> = Arc::from(cow);
4248 /// assert_eq!("eggplant", &shared[..]);
4249 /// ```
4250 #[inline]
4251 fn from(cow: Cow<'a, B>) -> Arc<B> {
4252 match cow {
4253 Cow::Borrowed(s) => Arc::from(s),
4254 Cow::Owned(s) => Arc::from(s),
4255 }
4256 }
4257}
4258
4259#[stable(feature = "shared_from_str", since = "1.62.0")]
4260impl From<Arc<str>> for Arc<[u8]> {
4261 /// Converts an atomically reference-counted string slice into a byte slice.
4262 ///
4263 /// # Example
4264 ///
4265 /// ```
4266 /// # use std::sync::Arc;
4267 /// let string: Arc<str> = Arc::from("eggplant");
4268 /// let bytes: Arc<[u8]> = Arc::from(string);
4269 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
4270 /// ```
4271 #[inline]
4272 fn from(rc: Arc<str>) -> Self {
4273 // SAFETY: `str` has the same layout as `[u8]`.
4274 unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) }
4275 }
4276}
4277
4278#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
4279impl<T, A: Allocator, const N: usize> TryFrom<Arc<[T], A>> for Arc<[T; N], A> {
4280 type Error = Arc<[T], A>;
4281
4282 fn try_from(boxed_slice: Arc<[T], A>) -> Result<Self, Self::Error> {
4283 if boxed_slice.len() == N {
4284 let (ptr, alloc) = Arc::into_inner_with_allocator(boxed_slice);
4285 // ignore-tidy-undocumented-unsafe
4286 Ok(unsafe { Arc::from_inner_in(ptr.cast(), alloc) })
4287 } else {
4288 Err(boxed_slice)
4289 }
4290 }
4291}
4292
4293#[cfg(not(no_global_oom_handling))]
4294#[stable(feature = "shared_from_iter", since = "1.37.0")]
4295impl<T> FromIterator<T> for Arc<[T]> {
4296 /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
4297 ///
4298 /// # Performance characteristics
4299 ///
4300 /// ## The general case
4301 ///
4302 /// In the general case, collecting into `Arc<[T]>` is done by first
4303 /// collecting into a `Vec<T>`. That is, when writing the following:
4304 ///
4305 /// ```rust
4306 /// # use std::sync::Arc;
4307 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
4308 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
4309 /// ```
4310 ///
4311 /// this behaves as if we wrote:
4312 ///
4313 /// ```rust
4314 /// # use std::sync::Arc;
4315 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
4316 /// .collect::<Vec<_>>() // The first set of allocations happens here.
4317 /// .into(); // A second allocation for `Arc<[T]>` happens here.
4318 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
4319 /// ```
4320 ///
4321 /// This will allocate as many times as needed for constructing the `Vec<T>`
4322 /// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
4323 ///
4324 /// ## Iterators of known length
4325 ///
4326 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
4327 /// a single allocation will be made for the `Arc<[T]>`. For example:
4328 ///
4329 /// ```rust
4330 /// # use std::sync::Arc;
4331 /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
4332 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
4333 /// ```
4334 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
4335 ToArcSlice::to_arc_slice(iter.into_iter())
4336 }
4337}
4338
4339#[cfg(not(no_global_oom_handling))]
4340/// Specialization trait used for collecting into `Arc<[T]>`.
4341trait ToArcSlice<T>: Iterator<Item = T> + Sized {
4342 fn to_arc_slice(self) -> Arc<[T]>;
4343}
4344
4345#[cfg(not(no_global_oom_handling))]
4346impl<T, I: Iterator<Item = T>> ToArcSlice<T> for I {
4347 default fn to_arc_slice(self) -> Arc<[T]> {
4348 self.collect::<Vec<T>>().into()
4349 }
4350}
4351
4352#[cfg(not(no_global_oom_handling))]
4353impl<T, I: iter::TrustedLen<Item = T>> ToArcSlice<T> for I {
4354 fn to_arc_slice(self) -> Arc<[T]> {
4355 // This is the case for a `TrustedLen` iterator.
4356 let (low, high) = self.size_hint();
4357 if let Some(high) = high {
4358 debug_assert_eq!(
4359 low,
4360 high,
4361 "TrustedLen iterator's size hint is not exact: {:?}",
4362 (low, high)
4363 );
4364
4365 // SAFETY: We need to ensure that the iterator has an exact length and we have.
4366 unsafe { Arc::from_iter_exact(self, low) }
4367 } else {
4368 // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
4369 // length exceeding `usize::MAX`.
4370 // The default implementation would collect into a vec which would panic.
4371 // Thus we panic here immediately without invoking `Vec` code.
4372 panic!("capacity overflow");
4373 }
4374 }
4375}
4376
4377#[stable(feature = "rust1", since = "1.0.0")]
4378impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Arc<T, A> {
4379 fn borrow(&self) -> &T {
4380 self
4381 }
4382}
4383
4384#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
4385impl<T: ?Sized, A: Allocator> AsRef<T> for Arc<T, A> {
4386 fn as_ref(&self) -> &T {
4387 self
4388 }
4389}
4390
4391#[stable(feature = "pin", since = "1.33.0")]
4392impl<T: ?Sized, A: Allocator> Unpin for Arc<T, A> {}
4393
4394/// Gets the offset within an `ArcInner` for the payload behind a pointer.
4395///
4396/// # Safety
4397///
4398/// The pointer must point to (and have valid metadata for) a previously
4399/// valid instance of T, but the T is allowed to be dropped.
4400unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
4401 // Align the unsized value to the end of the ArcInner.
4402 // Because ArcInner is repr(C), it will always be the last field in memory.
4403 // SAFETY: since the only unsized types possible are slices, trait objects,
4404 // and extern types, the input safety requirement is currently enough to
4405 // satisfy the requirements of Alignment::of_val_raw; this is an implementation
4406 // detail of the language that must not be relied upon outside of std.
4407 unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) }
4408}
4409
4410#[inline]
4411fn data_offset_alignment(alignment: Alignment) -> usize {
4412 let layout = Layout::new::<ArcInner<()>>();
4413 layout.size() + layout.padding_needed_for(alignment)
4414}
4415
4416/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,**
4417/// but will deallocate it (without dropping the value) when dropped.
4418///
4419/// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic.
4420struct UniqueArcUninit<T: ?Sized, A: Allocator> {
4421 ptr: NonNull<ArcInner<T>>,
4422 layout_for_value: Layout,
4423 alloc: Option<A>,
4424}
4425
4426impl<T: ?Sized, A: Allocator> UniqueArcUninit<T, A> {
4427 /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it.
4428 #[cfg(not(no_global_oom_handling))]
4429 fn new(for_value: &T, alloc: A) -> UniqueArcUninit<T, A> {
4430 let layout = Layout::for_value(for_value);
4431 // ignore-tidy-undocumented-unsafe
4432 let ptr = unsafe {
4433 Arc::allocate_for_layout(
4434 layout,
4435 |layout_for_arcinner| alloc.allocate(layout_for_arcinner),
4436 |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner<T>),
4437 )
4438 };
4439 Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }
4440 }
4441
4442 /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it,
4443 /// returning an error if allocation fails.
4444 fn try_new(for_value: &T, alloc: A) -> Result<UniqueArcUninit<T, A>, AllocError> {
4445 let layout = Layout::for_value(for_value);
4446 // ignore-tidy-undocumented-unsafe
4447 let ptr = unsafe {
4448 Arc::try_allocate_for_layout(
4449 layout,
4450 |layout_for_arcinner| alloc.allocate(layout_for_arcinner),
4451 |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner<T>),
4452 )?
4453 };
4454 Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) })
4455 }
4456
4457 /// Returns the pointer to be written into to initialize the [`Arc`].
4458 fn data_ptr(&mut self) -> *mut T {
4459 let offset = data_offset_alignment(self.layout_for_value.alignment());
4460 // ignore-tidy-undocumented-unsafe
4461 unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T }
4462 }
4463
4464 /// Upgrade this into a normal [`Arc`].
4465 ///
4466 /// # Safety
4467 ///
4468 /// The data must have been initialized (by writing to [`Self::data_ptr()`]).
4469 unsafe fn into_arc(self) -> Arc<T, A> {
4470 let mut this = ManuallyDrop::new(self);
4471 let ptr = this.ptr.as_ptr();
4472 let alloc = this.alloc.take().unwrap();
4473
4474 // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible
4475 // for having initialized the data.
4476 unsafe { Arc::from_ptr_in(ptr, alloc) }
4477 }
4478}
4479
4480impl<T: ?Sized, A: Allocator> Drop for UniqueArcUninit<T, A> {
4481 fn drop(&mut self) {
4482 // SAFETY:
4483 // * new() produced a pointer safe to deallocate.
4484 // * We own the pointer unless into_arc() was called, which forgets us.
4485 unsafe {
4486 self.alloc.take().unwrap().deallocate(
4487 self.ptr.cast(),
4488 arcinner_layout_for_value_layout(self.layout_for_value),
4489 );
4490 }
4491 }
4492}
4493
4494#[stable(feature = "arc_error", since = "1.52.0")]
4495impl<T: core::error::Error + ?Sized> core::error::Error for Arc<T> {
4496 #[allow(deprecated)]
4497 fn cause(&self) -> Option<&dyn core::error::Error> {
4498 core::error::Error::cause(&**self)
4499 }
4500
4501 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
4502 core::error::Error::source(&**self)
4503 }
4504
4505 fn provide<'a>(&'a self, req: &mut core::error::Request<'a>) {
4506 core::error::Error::provide(&**self, req);
4507 }
4508}
4509
4510/// A uniquely owned [`Arc`].
4511///
4512/// This represents an `Arc` that is known to be uniquely owned -- that is, have exactly one strong
4513/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
4514/// references will fail unless the `UniqueArc` they point to has been converted into a regular `Arc`.
4515///
4516/// Because it is uniquely owned, the contents of a `UniqueArc` can be freely mutated. A common
4517/// use case is to have an object be mutable during its initialization phase but then have it become
4518/// immutable and converted to a normal `Arc`.
4519///
4520/// This can be used as a flexible way to create cyclic data structures, as in the example below.
4521///
4522/// ```
4523/// #![feature(unique_rc_arc)]
4524/// use std::sync::{Arc, Weak, UniqueArc};
4525///
4526/// struct Gadget {
4527/// me: Weak<Gadget>,
4528/// }
4529///
4530/// fn create_gadget() -> Option<Arc<Gadget>> {
4531/// let mut rc = UniqueArc::new(Gadget {
4532/// me: Weak::new(),
4533/// });
4534/// rc.me = UniqueArc::downgrade(&rc);
4535/// Some(UniqueArc::into_arc(rc))
4536/// }
4537///
4538/// create_gadget().unwrap();
4539/// ```
4540///
4541/// An advantage of using `UniqueArc` over [`Arc::new_cyclic`] to build cyclic data structures is that
4542/// [`Arc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
4543/// previous example, `UniqueArc` allows for more flexibility in the construction of cyclic data,
4544/// including fallible or async constructors.
4545#[unstable(feature = "unique_rc_arc", issue = "112566")]
4546pub struct UniqueArc<
4547 T: ?Sized,
4548 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
4549> {
4550 ptr: NonNull<ArcInner<T>>,
4551 // Define the ownership of `ArcInner<T>` for drop-check
4552 _marker: PhantomData<ArcInner<T>>,
4553 // Invariance is necessary for soundness: once other `Weak`
4554 // references exist, we already have a form of shared mutability!
4555 _marker2: PhantomData<*mut T>,
4556 alloc: A,
4557}
4558
4559#[unstable(feature = "unique_rc_arc", issue = "112566")]
4560unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Send + Sync> Send for UniqueArc<T, A> {}
4561
4562#[unstable(feature = "unique_rc_arc", issue = "112566")]
4563unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Send + Sync> Sync for UniqueArc<T, A> {}
4564
4565#[unstable(feature = "unique_rc_arc", issue = "112566")]
4566// #[unstable(feature = "coerce_unsized", issue = "18598")]
4567impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueArc<U, A>>
4568 for UniqueArc<T, A>
4569{
4570}
4571
4572//#[unstable(feature = "unique_rc_arc", issue = "112566")]
4573#[unstable(feature = "dispatch_from_dyn", issue = "none")]
4574impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<UniqueArc<U>> for UniqueArc<T> {}
4575
4576#[unstable(feature = "unique_rc_arc", issue = "112566")]
4577impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for UniqueArc<T, A> {
4578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4579 fmt::Display::fmt(&**self, f)
4580 }
4581}
4582
4583#[unstable(feature = "unique_rc_arc", issue = "112566")]
4584impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for UniqueArc<T, A> {
4585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4586 fmt::Debug::fmt(&**self, f)
4587 }
4588}
4589
4590#[unstable(feature = "unique_rc_arc", issue = "112566")]
4591impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueArc<T, A> {
4592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4593 fmt::Pointer::fmt(&(&raw const **self), f)
4594 }
4595}
4596
4597#[unstable(feature = "unique_rc_arc", issue = "112566")]
4598impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueArc<T, A> {
4599 fn borrow(&self) -> &T {
4600 self
4601 }
4602}
4603
4604#[unstable(feature = "unique_rc_arc", issue = "112566")]
4605impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueArc<T, A> {
4606 fn borrow_mut(&mut self) -> &mut T {
4607 self
4608 }
4609}
4610
4611#[unstable(feature = "unique_rc_arc", issue = "112566")]
4612impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueArc<T, A> {
4613 fn as_ref(&self) -> &T {
4614 self
4615 }
4616}
4617
4618#[unstable(feature = "unique_rc_arc", issue = "112566")]
4619impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueArc<T, A> {
4620 fn as_mut(&mut self) -> &mut T {
4621 self
4622 }
4623}
4624
4625#[cfg(not(no_global_oom_handling))]
4626#[unstable(feature = "unique_rc_arc", issue = "112566")]
4627impl<T> From<T> for UniqueArc<T> {
4628 #[inline(always)]
4629 fn from(value: T) -> Self {
4630 Self::new(value)
4631 }
4632}
4633
4634#[unstable(feature = "unique_rc_arc", issue = "112566")]
4635impl<T: ?Sized, A: Allocator> Unpin for UniqueArc<T, A> {}
4636
4637#[unstable(feature = "unique_rc_arc", issue = "112566")]
4638impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for UniqueArc<T, A> {
4639 /// Equality for two `UniqueArc`s.
4640 ///
4641 /// Two `UniqueArc`s are equal if their inner values are equal.
4642 ///
4643 /// # Examples
4644 ///
4645 /// ```
4646 /// #![feature(unique_rc_arc)]
4647 /// use std::sync::UniqueArc;
4648 ///
4649 /// let five = UniqueArc::new(5);
4650 ///
4651 /// assert!(five == UniqueArc::new(5));
4652 /// ```
4653 #[inline]
4654 fn eq(&self, other: &Self) -> bool {
4655 PartialEq::eq(&**self, &**other)
4656 }
4657}
4658
4659#[unstable(feature = "unique_rc_arc", issue = "112566")]
4660impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for UniqueArc<T, A> {
4661 /// Partial comparison for two `UniqueArc`s.
4662 ///
4663 /// The two are compared by calling `partial_cmp()` on their inner values.
4664 ///
4665 /// # Examples
4666 ///
4667 /// ```
4668 /// #![feature(unique_rc_arc)]
4669 /// use std::sync::UniqueArc;
4670 /// use std::cmp::Ordering;
4671 ///
4672 /// let five = UniqueArc::new(5);
4673 ///
4674 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueArc::new(6)));
4675 /// ```
4676 #[inline(always)]
4677 fn partial_cmp(&self, other: &UniqueArc<T, A>) -> Option<Ordering> {
4678 (**self).partial_cmp(&**other)
4679 }
4680
4681 /// Less-than comparison for two `UniqueArc`s.
4682 ///
4683 /// The two are compared by calling `<` on their inner values.
4684 ///
4685 /// # Examples
4686 ///
4687 /// ```
4688 /// #![feature(unique_rc_arc)]
4689 /// use std::sync::UniqueArc;
4690 ///
4691 /// let five = UniqueArc::new(5);
4692 ///
4693 /// assert!(five < UniqueArc::new(6));
4694 /// ```
4695 #[inline(always)]
4696 fn lt(&self, other: &UniqueArc<T, A>) -> bool {
4697 **self < **other
4698 }
4699
4700 /// 'Less than or equal to' comparison for two `UniqueArc`s.
4701 ///
4702 /// The two are compared by calling `<=` on their inner values.
4703 ///
4704 /// # Examples
4705 ///
4706 /// ```
4707 /// #![feature(unique_rc_arc)]
4708 /// use std::sync::UniqueArc;
4709 ///
4710 /// let five = UniqueArc::new(5);
4711 ///
4712 /// assert!(five <= UniqueArc::new(5));
4713 /// ```
4714 #[inline(always)]
4715 fn le(&self, other: &UniqueArc<T, A>) -> bool {
4716 **self <= **other
4717 }
4718
4719 /// Greater-than comparison for two `UniqueArc`s.
4720 ///
4721 /// The two are compared by calling `>` on their inner values.
4722 ///
4723 /// # Examples
4724 ///
4725 /// ```
4726 /// #![feature(unique_rc_arc)]
4727 /// use std::sync::UniqueArc;
4728 ///
4729 /// let five = UniqueArc::new(5);
4730 ///
4731 /// assert!(five > UniqueArc::new(4));
4732 /// ```
4733 #[inline(always)]
4734 fn gt(&self, other: &UniqueArc<T, A>) -> bool {
4735 **self > **other
4736 }
4737
4738 /// 'Greater than or equal to' comparison for two `UniqueArc`s.
4739 ///
4740 /// The two are compared by calling `>=` on their inner values.
4741 ///
4742 /// # Examples
4743 ///
4744 /// ```
4745 /// #![feature(unique_rc_arc)]
4746 /// use std::sync::UniqueArc;
4747 ///
4748 /// let five = UniqueArc::new(5);
4749 ///
4750 /// assert!(five >= UniqueArc::new(5));
4751 /// ```
4752 #[inline(always)]
4753 fn ge(&self, other: &UniqueArc<T, A>) -> bool {
4754 **self >= **other
4755 }
4756}
4757
4758#[unstable(feature = "unique_rc_arc", issue = "112566")]
4759impl<T: ?Sized + Ord, A: Allocator> Ord for UniqueArc<T, A> {
4760 /// Comparison for two `UniqueArc`s.
4761 ///
4762 /// The two are compared by calling `cmp()` on their inner values.
4763 ///
4764 /// # Examples
4765 ///
4766 /// ```
4767 /// #![feature(unique_rc_arc)]
4768 /// use std::sync::UniqueArc;
4769 /// use std::cmp::Ordering;
4770 ///
4771 /// let five = UniqueArc::new(5);
4772 ///
4773 /// assert_eq!(Ordering::Less, five.cmp(&UniqueArc::new(6)));
4774 /// ```
4775 #[inline]
4776 fn cmp(&self, other: &UniqueArc<T, A>) -> Ordering {
4777 (**self).cmp(&**other)
4778 }
4779}
4780
4781#[unstable(feature = "unique_rc_arc", issue = "112566")]
4782impl<T: ?Sized + Eq, A: Allocator> Eq for UniqueArc<T, A> {}
4783
4784#[unstable(feature = "unique_rc_arc", issue = "112566")]
4785impl<T: ?Sized + Hash, A: Allocator> Hash for UniqueArc<T, A> {
4786 fn hash<H: Hasher>(&self, state: &mut H) {
4787 (**self).hash(state);
4788 }
4789}
4790
4791impl<T> UniqueArc<T, Global> {
4792 /// Creates a new `UniqueArc`.
4793 ///
4794 /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading
4795 /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`].
4796 /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will
4797 /// point to the new [`Arc`].
4798 #[cfg(not(no_global_oom_handling))]
4799 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4800 #[must_use]
4801 pub fn new(value: T) -> Self {
4802 Self::new_in(value, Global)
4803 }
4804
4805 /// Like [`new`](Self::new), but returns an error if the allocation
4806 /// fails, instead of calling [`handle_alloc_error`].
4807 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4808 pub fn try_new(value: T) -> Result<Self, AllocError> {
4809 Self::try_new_in(value, Global)
4810 }
4811}
4812
4813impl<T, A: Allocator> UniqueArc<T, A> {
4814 /// Creates a new `UniqueArc` in the provided allocator.
4815 ///
4816 /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading
4817 /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`].
4818 /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will
4819 /// point to the new [`Arc`].
4820 #[cfg(not(no_global_oom_handling))]
4821 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4822 // #[unstable(feature = "allocator_api", issue = "163177")]
4823 #[must_use]
4824 pub fn new_in(data: T, alloc: A) -> Self {
4825 let (ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in(
4826 ArcInner {
4827 strong: atomic::AtomicUsize::new(0),
4828 // keep one weak reference so if all the weak pointers that are created are dropped
4829 // the UniqueArc still stays valid.
4830 weak: atomic::AtomicUsize::new(1),
4831 data,
4832 },
4833 alloc,
4834 ));
4835 Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
4836 }
4837
4838 /// Like [`new_in`](Self::new_in), but returns an error if the allocation
4839 /// fails, instead of calling [`handle_alloc_error`].
4840 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4841 // #[unstable(feature = "allocator_api", issue = "163177")]
4842 pub fn try_new_in(data: T, alloc: A) -> Result<Self, AllocError> {
4843 let (ptr, alloc) = Box::into_non_null_with_allocator(Box::try_new_in(
4844 ArcInner {
4845 strong: atomic::AtomicUsize::new(0),
4846 // keep one weak reference so if all the weak pointers that are created are dropped
4847 // the UniqueArc still stays valid.
4848 weak: atomic::AtomicUsize::new(1),
4849 data,
4850 },
4851 alloc,
4852 )?);
4853 Ok(Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc })
4854 }
4855
4856 /// Consumes the `UniqueArc`, returning its wrapped value and allocator.
4857 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4858 // #[unstable(feature = "allocator_api", issue = "163177")]
4859 #[must_use]
4860 pub fn unwrap_with_allocator(this: Self) -> (T, A) {
4861 let inner_ptr = this.ptr;
4862 let (data_ptr, alloc) = Self::into_raw_with_allocator(this);
4863
4864 // SAFETY: Conceptually moves out of the `UniqueRc`.
4865 // We do not use the data inside ever again.
4866 let val = unsafe { data_ptr.read() };
4867
4868 // Drop the strong-weak ref
4869 drop(Weak { ptr: inner_ptr, alloc: &alloc });
4870
4871 (val, alloc)
4872 }
4873
4874 /// Consumes the `UniqueArc`, returning its wrapped value.
4875 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4876 #[must_use]
4877 pub fn unwrap(this: Self) -> T {
4878 Self::unwrap_with_allocator(this).0
4879 }
4880
4881 /// Maps the value in a `UniqueArc`, reusing the allocation if possible.
4882 ///
4883 /// `f` is called on a reference to the value in the `UniqueArc`, and the result is returned,
4884 /// also in a `UniqueArc`.
4885 ///
4886 /// Note: this is an associated function, which means that you have
4887 /// to call it as `UniqueArc::map(u, f)` instead of `u.map(f)`. This
4888 /// is so that there is no conflict with a method on the inner type.
4889 ///
4890 /// # Examples
4891 ///
4892 /// ```
4893 /// #![feature(unique_rc_arc)]
4894 ///
4895 /// use std::sync::UniqueArc;
4896 ///
4897 /// let r = UniqueArc::new(7);
4898 /// let new = UniqueArc::map(r, |i| i + 7);
4899 /// assert_eq!(*new, 14);
4900 /// ```
4901 #[cfg(not(no_global_oom_handling))]
4902 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4903 pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> UniqueArc<U, A> {
4904 if size_of::<T>() == size_of::<U>()
4905 && align_of::<T>() == align_of::<U>()
4906 && UniqueArc::weak_count(&this) == 0
4907 {
4908 // ignore-tidy-undocumented-unsafe
4909 unsafe {
4910 let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this);
4911 let value = ptr.read();
4912 let allocation =
4913 UniqueArc::from_raw_with_allocator(ptr.cast::<mem::MaybeUninit<U>>(), alloc);
4914
4915 UniqueArc::write(allocation, f(value))
4916 }
4917 } else {
4918 let (val, alloc) = UniqueArc::unwrap_with_allocator(this);
4919 UniqueArc::new_in(f(val), alloc)
4920 }
4921 }
4922
4923 /// Attempts to map the value in a `UniqueArc`, reusing the allocation if possible.
4924 ///
4925 /// `f` is called on a reference to the value in the `UniqueArc`, and if the operation succeeds,
4926 /// the result is returned, also in a `UniqueArc`.
4927 ///
4928 /// Note: this is an associated function, which means that you have
4929 /// to call it as `UniqueArc::try_map(u, f)` instead of `u.try_map(f)`. This
4930 /// is so that there is no conflict with a method on the inner type.
4931 ///
4932 /// # Examples
4933 ///
4934 /// ```
4935 /// #![feature(smart_pointer_try_map)]
4936 /// #![feature(unique_rc_arc)]
4937 ///
4938 /// use std::sync::UniqueArc;
4939 ///
4940 /// let b = UniqueArc::new(7);
4941 /// let new = UniqueArc::try_map(b, u32::try_from).unwrap();
4942 /// assert_eq!(*new, 7);
4943 /// ```
4944 #[cfg(not(no_global_oom_handling))]
4945 #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4946 pub fn try_map<R>(
4947 this: Self,
4948 f: impl FnOnce(T) -> R,
4949 ) -> <R::Residual as Residual<UniqueArc<R::Output, A>>>::TryType
4950 where
4951 R: Try,
4952 R::Residual: Residual<UniqueArc<R::Output, A>>,
4953 {
4954 if size_of::<T>() == size_of::<R::Output>()
4955 && align_of::<T>() == align_of::<R::Output>()
4956 && UniqueArc::weak_count(&this) == 0
4957 {
4958 // ignore-tidy-undocumented-unsafe
4959 unsafe {
4960 let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this);
4961 let value = ptr.read();
4962 let allocation = UniqueArc::from_raw_with_allocator(
4963 ptr.cast::<mem::MaybeUninit<R::Output>>(),
4964 alloc,
4965 );
4966
4967 try { UniqueArc::write(allocation, f(value)?) }
4968 }
4969 } else {
4970 let (val, alloc) = UniqueArc::unwrap_with_allocator(this);
4971 try { UniqueArc::new_in(f(val)?, alloc) }
4972 }
4973 }
4974}
4975
4976impl<T: ?Sized, A: Allocator> UniqueArc<T, A> {
4977 #[cfg(not(no_global_oom_handling))]
4978 unsafe fn from_raw_with_allocator(ptr: *const T, alloc: A) -> Self {
4979 // SAFETY: Upheld by caller.
4980 let offset = unsafe { data_offset(ptr) };
4981
4982 // Reverse the offset to find the original ArcInner.
4983 // SAFETY: Upheld by caller.
4984 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner<T> };
4985
4986 Self {
4987 // SAFETY: Upheld by caller.
4988 ptr: unsafe { NonNull::new_unchecked(rc_ptr) },
4989 _marker: PhantomData,
4990 _marker2: PhantomData,
4991 alloc,
4992 }
4993 }
4994
4995 fn into_raw_with_allocator(this: Self) -> (*const T, A) {
4996 let this = ManuallyDrop::new(this);
4997 // SAFETY: The copy of the allocator stored in `this` is forgotten
4998 (Self::as_ptr(&*this), unsafe { ptr::read(&this.alloc) })
4999 }
5000
5001 /// Converts the `UniqueArc` into a regular [`Arc`].
5002 ///
5003 /// This consumes the `UniqueArc` and returns a regular [`Arc`] that contains the `value` that
5004 /// is passed to `into_arc`.
5005 ///
5006 /// Any weak references created before this method is called can now be upgraded to strong
5007 /// references.
5008 #[unstable(feature = "unique_rc_arc", issue = "112566")]
5009 #[must_use]
5010 pub fn into_arc(this: Self) -> Arc<T, A> {
5011 let this = ManuallyDrop::new(this);
5012
5013 // Move the allocator out.
5014 // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
5015 // a `ManuallyDrop`.
5016 let alloc: A = unsafe { ptr::read(&this.alloc) };
5017
5018 // SAFETY: This pointer was allocated at creation time so we know it is valid.
5019 unsafe {
5020 // Convert our weak reference into a strong reference
5021 (*this.ptr.as_ptr()).strong.store(1, Release);
5022 Arc::from_inner_in(this.ptr, alloc)
5023 }
5024 }
5025
5026 #[cfg(not(no_global_oom_handling))]
5027 fn weak_count(this: &Self) -> usize {
5028 this.inner().weak.load(Acquire) - 1
5029 }
5030
5031 #[cfg(not(no_global_oom_handling))]
5032 fn inner(&self) -> &ArcInner<T> {
5033 // SAFETY: while this UniqueArc is alive we're guaranteed that the inner pointer is valid.
5034 unsafe { self.ptr.as_ref() }
5035 }
5036
5037 fn as_ptr(this: &Self) -> *const T {
5038 let ptr: *mut ArcInner<T> = NonNull::as_ptr(this.ptr);
5039
5040 // SAFETY: This cannot go through Deref::deref or UniqueArc::inner because
5041 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
5042 // write through the pointer after the Rc is recovered through `from_raw`.
5043 unsafe { &raw mut (*ptr).data }
5044 }
5045
5046 #[inline]
5047 fn into_inner_with_allocator(this: Self) -> (NonNull<ArcInner<T>>, A) {
5048 let this = mem::ManuallyDrop::new(this);
5049 // SAFETY: Pointer is valid for reads and only read once.
5050 (this.ptr, unsafe { ptr::read(&this.alloc) })
5051 }
5052
5053 #[inline]
5054 unsafe fn from_inner_in(ptr: NonNull<ArcInner<T>>, alloc: A) -> Self {
5055 Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
5056 }
5057}
5058
5059impl<T: ?Sized, A: AllocatorClone> UniqueArc<T, A> {
5060 /// Creates a new weak reference to the `UniqueArc`.
5061 ///
5062 /// Attempting to upgrade this weak reference will fail before the `UniqueArc` has been converted
5063 /// to a [`Arc`] using [`UniqueArc::into_arc`].
5064 #[unstable(feature = "unique_rc_arc", issue = "112566")]
5065 #[must_use]
5066 pub fn downgrade(this: &Self) -> Weak<T, A> {
5067 // Using a relaxed ordering is alright here, as knowledge of the
5068 // original reference prevents other threads from erroneously deleting
5069 // the object or converting the object to a normal `Arc<T, A>`.
5070 //
5071 // Note that we don't need to test if the weak counter is locked because there
5072 // are no such operations like `Arc::get_mut` or `Arc::make_mut` that will lock
5073 // the weak counter.
5074 //
5075 // SAFETY: This pointer was allocated at creation time so we know it is valid.
5076 let old_size = unsafe { (*this.ptr.as_ptr()).weak.fetch_add(1, Relaxed) };
5077
5078 // See comments in Arc::clone() for why we do this (for mem::forget).
5079 if old_size > MAX_REFCOUNT {
5080 intrinsics::abort_immediate();
5081 }
5082
5083 Weak { ptr: this.ptr, alloc: this.alloc.clone() }
5084 }
5085}
5086
5087impl<T, A: Allocator> UniqueArc<mem::MaybeUninit<T>, A> {
5088 /// Writes the value and converts to `UniqueArc<T, A>`.
5089 ///
5090 /// This method converts similarly to [`assume_init`](Self::assume_init) but
5091 /// writes `value` into it before conversion, thus guaranteeing safety.
5092 #[unstable(feature = "unique_rc_arc", issue = "112566")]
5093 #[must_use]
5094 pub fn write(mut this: Self, value: T) -> UniqueArc<T, A> {
5095 // SAFETY: Writing initialises the wrapped value.
5096 unsafe {
5097 this.write(value);
5098 this.assume_init()
5099 }
5100 }
5101
5102 /// Converts to `UniqueArc<T, A>`.
5103 ///
5104 /// # Safety
5105 ///
5106 /// As with [`MaybeUninit::assume_init`],
5107 /// it is up to the caller to guarantee that the value
5108 /// really is in an initialized state.
5109 /// Calling this when the content is not yet fully initialized
5110 /// causes immediate undefined behavior.
5111 ///
5112 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
5113 #[unstable(feature = "unique_rc_arc", issue = "112566")]
5114 #[must_use]
5115 pub unsafe fn assume_init(self) -> UniqueArc<T, A> {
5116 let (ptr, alloc) = UniqueArc::into_inner_with_allocator(self);
5117 // SAFETY: Upheld by caller.
5118 unsafe { UniqueArc::from_inner_in(ptr.cast(), alloc) }
5119 }
5120}
5121
5122#[unstable(feature = "unique_rc_arc", issue = "112566")]
5123impl<T: ?Sized, A: Allocator> Deref for UniqueArc<T, A> {
5124 type Target = T;
5125
5126 fn deref(&self) -> &T {
5127 // SAFETY: This pointer was allocated at creation time so we know it is valid.
5128 unsafe { &self.ptr.as_ref().data }
5129 }
5130}
5131
5132// #[unstable(feature = "unique_rc_arc", issue = "112566")]
5133#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
5134unsafe impl<T: ?Sized, A: StaticAllocator> PinSafePointer for UniqueArc<T, A> {}
5135
5136#[unstable(feature = "unique_rc_arc", issue = "112566")]
5137impl<T: ?Sized, A: Allocator> DerefMut for UniqueArc<T, A> {
5138 fn deref_mut(&mut self) -> &mut T {
5139 // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
5140 // have unique ownership and therefore it's safe to make a mutable reference because
5141 // `UniqueArc` owns the only strong reference to itself.
5142 // We also need to be careful to only create a mutable reference to the `data` field,
5143 // as a mutable reference to the entire `ArcInner` would assert uniqueness over the
5144 // ref count fields too, invalidating any attempt by `Weak`s to access the ref count.
5145 unsafe { &mut (*self.ptr.as_ptr()).data }
5146 }
5147}
5148
5149#[unstable(feature = "unique_rc_arc", issue = "112566")]
5150// #[unstable(feature = "deref_pure_trait", issue = "87121")]
5151unsafe impl<T: ?Sized, A: Allocator> DerefPure for UniqueArc<T, A> {}
5152
5153#[unstable(feature = "unique_rc_arc", issue = "112566")]
5154unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueArc<T, A> {
5155 fn drop(&mut self) {
5156 // See `Arc::drop_slow` which drops an `Arc` with a strong count of 0.
5157 // SAFETY: This pointer was allocated at creation time so we know it is valid.
5158 let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };
5159
5160 // ignore-tidy-undocumented-unsafe
5161 unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) };
5162 }
5163}
5164
5165#[stable(feature = "allocator_api", since = "1.100.0")]
5166unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Arc<T, A> {
5167 #[inline]
5168 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
5169 (**self).allocate(layout)
5170 }
5171
5172 #[inline]
5173 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
5174 (**self).allocate_zeroed(layout)
5175 }
5176
5177 #[inline]
5178 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
5179 // SAFETY: the safety contract must be upheld by the caller
5180 unsafe { (**self).deallocate(ptr, layout) }
5181 }
5182
5183 #[inline]
5184 unsafe fn grow(
5185 &self,
5186 ptr: NonNull<u8>,
5187 old_layout: Layout,
5188 new_layout: Layout,
5189 ) -> Result<NonNull<[u8]>, AllocError> {
5190 // SAFETY: the safety contract must be upheld by the caller
5191 unsafe { (**self).grow(ptr, old_layout, new_layout) }
5192 }
5193
5194 #[inline]
5195 unsafe fn grow_zeroed(
5196 &self,
5197 ptr: NonNull<u8>,
5198 old_layout: Layout,
5199 new_layout: Layout,
5200 ) -> Result<NonNull<[u8]>, AllocError> {
5201 // SAFETY: the safety contract must be upheld by the caller
5202 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
5203 }
5204
5205 #[inline]
5206 unsafe fn shrink(
5207 &self,
5208 ptr: NonNull<u8>,
5209 old_layout: Layout,
5210 new_layout: Layout,
5211 ) -> Result<NonNull<[u8]>, AllocError> {
5212 // SAFETY: the safety contract must be upheld by the caller
5213 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
5214 }
5215}
5216
5217/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`.
5218#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
5219#[unstable_feature_bound(allocator_ext)]
5220impl<T: ?Sized + Allocator, A: Allocator> AllocatorNightly for Arc<T, A> {}
5221
5222#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
5223unsafe impl<T: Allocator + ?Sized, A: AllocatorClone> AllocatorClone for Arc<T, A> {}