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