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