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