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