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