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