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