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