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