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