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