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