1 #![stable(feature = "rust1", since = "1.0.0")]
3 //! Thread-safe reference-counting pointers.
5 //! See the [`Arc<T>`][Arc] documentation for more details.
9 use core::cmp::Ordering;
10 use core::convert::{From, TryFrom};
12 use core::hash::{Hash, Hasher};
13 use core::intrinsics::abort;
15 use core::marker::{PhantomData, Unpin, Unsize};
16 use core::mem::{self, align_of_val, size_of_val};
17 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
19 use core::ptr::{self, NonNull};
20 use core::slice::from_raw_parts_mut;
21 use core::sync::atomic;
22 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
24 use crate::alloc::{box_free, handle_alloc_error, AllocError, AllocRef, Global, Layout};
25 use crate::borrow::{Cow, ToOwned};
26 use crate::boxed::Box;
27 use crate::rc::is_dangling;
28 use crate::string::String;
34 /// A soft limit on the amount of references that may be made to an `Arc`.
36 /// Going above this limit will abort your program (although not
37 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
38 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
40 #[cfg(not(sanitize = "thread"))]
41 macro_rules! acquire {
43 atomic::fence(Acquire)
47 // ThreadSanitizer does not support memory fences. To avoid false positive
48 // reports in Arc / Weak implementation use atomic loads for synchronization
50 #[cfg(sanitize = "thread")]
51 macro_rules! acquire {
57 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
58 /// Reference Counted'.
60 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
61 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
62 /// a new `Arc` instance, which points to the same allocation on the heap as the
63 /// source `Arc`, while increasing a reference count. When the last `Arc`
64 /// pointer to a given allocation is destroyed, the value stored in that allocation (often
65 /// referred to as "inner value") is also dropped.
67 /// Shared references in Rust disallow mutation by default, and `Arc` is no
68 /// exception: you cannot generally obtain a mutable reference to something
69 /// inside an `Arc`. If you need to mutate through an `Arc`, use
70 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
75 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
76 /// counting. This means that it is thread-safe. The disadvantage is that
77 /// atomic operations are more expensive than ordinary memory accesses. If you
78 /// are not sharing reference-counted allocations between threads, consider using
79 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
80 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
81 /// However, a library might choose `Arc<T>` in order to give library consumers
84 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
85 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
86 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
87 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
88 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
89 /// data, but it doesn't add thread safety to its data. Consider
90 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
91 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
92 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
93 /// non-atomic operations.
95 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
96 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
98 /// ## Breaking cycles with `Weak`
100 /// The [`downgrade`][downgrade] method can be used to create a non-owning
101 /// [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
102 /// to an `Arc`, but this will return [`None`] if the value stored in the allocation has
103 /// already been dropped. In other words, `Weak` pointers do not keep the value
104 /// inside the allocation alive; however, they *do* keep the allocation
105 /// (the backing store for the value) alive.
107 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
108 /// [`Weak`] is used to break cycles. For example, a tree could have
109 /// strong `Arc` pointers from parent nodes to children, and [`Weak`]
110 /// pointers from children back to their parents.
112 /// # Cloning references
114 /// Creating a new reference from an existing reference-counted pointer is done using the
115 /// `Clone` trait implemented for [`Arc<T>`][Arc] and [`Weak<T>`][Weak].
118 /// use std::sync::Arc;
119 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
120 /// // The two syntaxes below are equivalent.
121 /// let a = foo.clone();
122 /// let b = Arc::clone(&foo);
123 /// // a, b, and foo are all Arcs that point to the same memory location
126 /// ## `Deref` behavior
128 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
129 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
130 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are associated
131 /// functions, called using function-like syntax:
134 /// use std::sync::Arc;
135 /// let my_arc = Arc::new(());
137 /// Arc::downgrade(&my_arc);
140 /// [`Weak<T>`][Weak] does not auto-dereference to `T`, because the inner value may have
141 /// already been dropped.
143 /// [`Rc<T>`]: crate::rc::Rc
144 /// [clone]: Clone::clone
145 /// [mutex]: ../../std/sync/struct.Mutex.html
146 /// [rwlock]: ../../std/sync/struct.RwLock.html
147 /// [atomic]: core::sync::atomic
148 /// [`Send`]: core::marker::Send
149 /// [`Sync`]: core::marker::Sync
150 /// [deref]: core::ops::Deref
151 /// [downgrade]: Arc::downgrade
152 /// [upgrade]: Weak::upgrade
153 /// [`RefCell<T>`]: core::cell::RefCell
154 /// [`std::sync`]: ../../std/sync/index.html
155 /// [`Arc::clone(&from)`]: Arc::clone
159 /// Sharing some immutable data between threads:
161 // Note that we **do not** run these tests here. The windows builders get super
162 // unhappy if a thread outlives the main thread and then exits at the same time
163 // (something deadlocks) so we just avoid this entirely by not running these
166 /// use std::sync::Arc;
169 /// let five = Arc::new(5);
172 /// let five = Arc::clone(&five);
174 /// thread::spawn(move || {
175 /// println!("{:?}", five);
180 /// Sharing a mutable [`AtomicUsize`]:
182 /// [`AtomicUsize`]: core::sync::atomic::AtomicUsize
185 /// use std::sync::Arc;
186 /// use std::sync::atomic::{AtomicUsize, Ordering};
189 /// let val = Arc::new(AtomicUsize::new(5));
192 /// let val = Arc::clone(&val);
194 /// thread::spawn(move || {
195 /// let v = val.fetch_add(1, Ordering::SeqCst);
196 /// println!("{:?}", v);
201 /// See the [`rc` documentation][rc_examples] for more examples of reference
202 /// counting in general.
204 /// [rc_examples]: crate::rc#examples
205 #[cfg_attr(not(test), rustc_diagnostic_item = "Arc")]
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub struct Arc<T: ?Sized> {
208 ptr: NonNull<ArcInner<T>>,
209 phantom: PhantomData<ArcInner<T>>,
212 #[stable(feature = "rust1", since = "1.0.0")]
213 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
214 #[stable(feature = "rust1", since = "1.0.0")]
215 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
217 #[unstable(feature = "coerce_unsized", issue = "27732")]
218 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
220 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
221 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}
223 impl<T: ?Sized> Arc<T> {
224 fn from_inner(ptr: NonNull<ArcInner<T>>) -> Self {
225 Self { ptr, phantom: PhantomData }
228 unsafe fn from_ptr(ptr: *mut ArcInner<T>) -> Self {
229 unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
233 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
234 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
235 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
237 /// Since a `Weak` reference does not count towards ownership, it will not
238 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
239 /// guarantees about the value still being present. Thus it may return [`None`]
240 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
241 /// itself (the backing store) from being deallocated.
243 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
244 /// managed by [`Arc`] without preventing its inner value from being dropped. It is also used to
245 /// prevent circular references between [`Arc`] pointers, since mutual owning references
246 /// would never allow either [`Arc`] to be dropped. For example, a tree could
247 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
248 /// pointers from children back to their parents.
250 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
252 /// [`upgrade`]: Weak::upgrade
253 #[stable(feature = "arc_weak", since = "1.4.0")]
254 pub struct Weak<T: ?Sized> {
255 // This is a `NonNull` to allow optimizing the size of this type in enums,
256 // but it is not necessarily a valid pointer.
257 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
258 // to allocate space on the heap. That's not a value a real pointer
259 // will ever have because RcBox has alignment at least 2.
260 // This is only possible when `T: Sized`; unsized `T` never dangle.
261 ptr: NonNull<ArcInner<T>>,
264 #[stable(feature = "arc_weak", since = "1.4.0")]
265 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
266 #[stable(feature = "arc_weak", since = "1.4.0")]
267 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
269 #[unstable(feature = "coerce_unsized", issue = "27732")]
270 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
271 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
272 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
274 #[stable(feature = "arc_weak", since = "1.4.0")]
275 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 // This is repr(C) to future-proof against possible field-reordering, which
282 // would interfere with otherwise safe [into|from]_raw() of transmutable
285 struct ArcInner<T: ?Sized> {
286 strong: atomic::AtomicUsize,
288 // the value usize::MAX acts as a sentinel for temporarily "locking" the
289 // ability to upgrade weak pointers or downgrade strong ones; this is used
290 // to avoid races in `make_mut` and `get_mut`.
291 weak: atomic::AtomicUsize,
296 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
297 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
300 /// Constructs a new `Arc<T>`.
305 /// use std::sync::Arc;
307 /// let five = Arc::new(5);
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn new(data: T) -> Arc<T> {
312 // Start the weak pointer count as 1 which is the weak pointer that's
313 // held by all the strong pointers (kinda), see std/rc.rs for more info
314 let x: Box<_> = box ArcInner {
315 strong: atomic::AtomicUsize::new(1),
316 weak: atomic::AtomicUsize::new(1),
319 Self::from_inner(Box::leak(x).into())
322 /// Constructs a new `Arc<T>` using a weak reference to itself. Attempting
323 /// to upgrade the weak reference before this function returns will result
324 /// in a `None` value. However, the weak reference may be cloned freely and
325 /// stored for use at a later time.
329 /// #![feature(arc_new_cyclic)]
330 /// #![allow(dead_code)]
332 /// use std::sync::{Arc, Weak};
338 /// let foo = Arc::new_cyclic(|me| Foo {
343 #[unstable(feature = "arc_new_cyclic", issue = "75861")]
344 pub fn new_cyclic(data_fn: impl FnOnce(&Weak<T>) -> T) -> Arc<T> {
345 // Construct the inner in the "uninitialized" state with a single
347 let uninit_ptr: NonNull<_> = Box::leak(box ArcInner {
348 strong: atomic::AtomicUsize::new(0),
349 weak: atomic::AtomicUsize::new(1),
350 data: mem::MaybeUninit::<T>::uninit(),
353 let init_ptr: NonNull<ArcInner<T>> = uninit_ptr.cast();
355 let weak = Weak { ptr: init_ptr };
357 // It's important we don't give up ownership of the weak pointer, or
358 // else the memory might be freed by the time `data_fn` returns. If
359 // we really wanted to pass ownership, we could create an additional
360 // weak pointer for ourselves, but this would result in additional
361 // updates to the weak reference count which might not be necessary
363 let data = data_fn(&weak);
365 // Now we can properly initialize the inner value and turn our weak
366 // reference into a strong reference.
368 let inner = init_ptr.as_ptr();
369 ptr::write(&raw mut (*inner).data, data);
371 // The above write to the data field must be visible to any threads which
372 // observe a non-zero strong count. Therefore we need at least "Release" ordering
373 // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`.
375 // "Acquire" ordering is not required. When considering the possible behaviours
376 // of `data_fn` we only need to look at what it could do with a reference to a
377 // non-upgradeable `Weak`:
378 // - It can *clone* the `Weak`, increasing the weak reference count.
379 // - It can drop those clones, decreasing the weak reference count (but never to zero).
381 // These side effects do not impact us in any way, and no other side effects are
382 // possible with safe code alone.
383 let prev_value = (*inner).strong.fetch_add(1, Release);
384 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
387 let strong = Arc::from_inner(init_ptr);
389 // Strong references should collectively own a shared weak reference,
390 // so don't run the destructor for our old weak reference.
395 /// Constructs a new `Arc` with uninitialized contents.
400 /// #![feature(new_uninit)]
401 /// #![feature(get_mut_unchecked)]
403 /// use std::sync::Arc;
405 /// let mut five = Arc::<u32>::new_uninit();
407 /// let five = unsafe {
408 /// // Deferred initialization:
409 /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
411 /// five.assume_init()
414 /// assert_eq!(*five, 5)
416 #[unstable(feature = "new_uninit", issue = "63291")]
417 pub fn new_uninit() -> Arc<mem::MaybeUninit<T>> {
419 Arc::from_ptr(Arc::allocate_for_layout(
421 |layout| Global.alloc(layout),
422 |mem| mem as *mut ArcInner<mem::MaybeUninit<T>>,
427 /// Constructs a new `Arc` with uninitialized contents, with the memory
428 /// being filled with `0` bytes.
430 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
436 /// #![feature(new_uninit)]
438 /// use std::sync::Arc;
440 /// let zero = Arc::<u32>::new_zeroed();
441 /// let zero = unsafe { zero.assume_init() };
443 /// assert_eq!(*zero, 0)
446 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
447 #[unstable(feature = "new_uninit", issue = "63291")]
448 pub fn new_zeroed() -> Arc<mem::MaybeUninit<T>> {
450 Arc::from_ptr(Arc::allocate_for_layout(
452 |layout| Global.alloc_zeroed(layout),
453 |mem| mem as *mut ArcInner<mem::MaybeUninit<T>>,
458 /// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
459 /// `data` will be pinned in memory and unable to be moved.
460 #[stable(feature = "pin", since = "1.33.0")]
461 pub fn pin(data: T) -> Pin<Arc<T>> {
462 unsafe { Pin::new_unchecked(Arc::new(data)) }
465 /// Returns the inner value, if the `Arc` has exactly one strong reference.
467 /// Otherwise, an [`Err`] is returned with the same `Arc` that was
470 /// This will succeed even if there are outstanding weak references.
475 /// use std::sync::Arc;
477 /// let x = Arc::new(3);
478 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
480 /// let x = Arc::new(4);
481 /// let _y = Arc::clone(&x);
482 /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
485 #[stable(feature = "arc_unique", since = "1.4.0")]
486 pub fn try_unwrap(this: Self) -> Result<T, Self> {
487 if this.inner().strong.compare_exchange(1, 0, Relaxed, Relaxed).is_err() {
491 acquire!(this.inner().strong);
494 let elem = ptr::read(&this.ptr.as_ref().data);
496 // Make a weak pointer to clean up the implicit strong-weak reference
497 let _weak = Weak { ptr: this.ptr };
506 /// Constructs a new atomically reference-counted slice with uninitialized contents.
511 /// #![feature(new_uninit)]
512 /// #![feature(get_mut_unchecked)]
514 /// use std::sync::Arc;
516 /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
518 /// let values = unsafe {
519 /// // Deferred initialization:
520 /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
521 /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
522 /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
524 /// values.assume_init()
527 /// assert_eq!(*values, [1, 2, 3])
529 #[unstable(feature = "new_uninit", issue = "63291")]
530 pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> {
531 unsafe { Arc::from_ptr(Arc::allocate_for_slice(len)) }
534 /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being
535 /// filled with `0` bytes.
537 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
538 /// incorrect usage of this method.
543 /// #![feature(new_uninit)]
545 /// use std::sync::Arc;
547 /// let values = Arc::<[u32]>::new_zeroed_slice(3);
548 /// let values = unsafe { values.assume_init() };
550 /// assert_eq!(*values, [0, 0, 0])
553 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
554 #[unstable(feature = "new_uninit", issue = "63291")]
555 pub fn new_zeroed_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> {
557 Arc::from_ptr(Arc::allocate_for_layout(
558 Layout::array::<T>(len).unwrap(),
559 |layout| Global.alloc_zeroed(layout),
561 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
562 as *mut ArcInner<[mem::MaybeUninit<T>]>
569 impl<T> Arc<mem::MaybeUninit<T>> {
570 /// Converts to `Arc<T>`.
574 /// As with [`MaybeUninit::assume_init`],
575 /// it is up to the caller to guarantee that the inner value
576 /// really is in an initialized state.
577 /// Calling this when the content is not yet fully initialized
578 /// causes immediate undefined behavior.
580 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
585 /// #![feature(new_uninit)]
586 /// #![feature(get_mut_unchecked)]
588 /// use std::sync::Arc;
590 /// let mut five = Arc::<u32>::new_uninit();
592 /// let five = unsafe {
593 /// // Deferred initialization:
594 /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
596 /// five.assume_init()
599 /// assert_eq!(*five, 5)
601 #[unstable(feature = "new_uninit", issue = "63291")]
603 pub unsafe fn assume_init(self) -> Arc<T> {
604 Arc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
608 impl<T> Arc<[mem::MaybeUninit<T>]> {
609 /// Converts to `Arc<[T]>`.
613 /// As with [`MaybeUninit::assume_init`],
614 /// it is up to the caller to guarantee that the inner value
615 /// really is in an initialized state.
616 /// Calling this when the content is not yet fully initialized
617 /// causes immediate undefined behavior.
619 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
624 /// #![feature(new_uninit)]
625 /// #![feature(get_mut_unchecked)]
627 /// use std::sync::Arc;
629 /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
631 /// let values = unsafe {
632 /// // Deferred initialization:
633 /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
634 /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
635 /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
637 /// values.assume_init()
640 /// assert_eq!(*values, [1, 2, 3])
642 #[unstable(feature = "new_uninit", issue = "63291")]
644 pub unsafe fn assume_init(self) -> Arc<[T]> {
645 unsafe { Arc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
649 impl<T: ?Sized> Arc<T> {
650 /// Consumes the `Arc`, returning the wrapped pointer.
652 /// To avoid a memory leak the pointer must be converted back to an `Arc` using
653 /// [`Arc::from_raw`].
658 /// use std::sync::Arc;
660 /// let x = Arc::new("hello".to_owned());
661 /// let x_ptr = Arc::into_raw(x);
662 /// assert_eq!(unsafe { &*x_ptr }, "hello");
664 #[stable(feature = "rc_raw", since = "1.17.0")]
665 pub fn into_raw(this: Self) -> *const T {
666 let ptr = Self::as_ptr(&this);
671 /// Provides a raw pointer to the data.
673 /// The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for
674 /// as long as there are strong counts in the `Arc`.
679 /// use std::sync::Arc;
681 /// let x = Arc::new("hello".to_owned());
682 /// let y = Arc::clone(&x);
683 /// let x_ptr = Arc::as_ptr(&x);
684 /// assert_eq!(x_ptr, Arc::as_ptr(&y));
685 /// assert_eq!(unsafe { &*x_ptr }, "hello");
687 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
688 pub fn as_ptr(this: &Self) -> *const T {
689 let ptr: *mut ArcInner<T> = NonNull::as_ptr(this.ptr);
691 // SAFETY: This cannot go through Deref::deref or RcBoxPtr::inner because
692 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
693 // write through the pointer after the Rc is recovered through `from_raw`.
694 unsafe { &raw const (*ptr).data }
697 /// Constructs an `Arc<T>` from a raw pointer.
699 /// The raw pointer must have been previously returned by a call to
700 /// [`Arc<U>::into_raw`][into_raw] where `U` must have the same size and
701 /// alignment as `T`. This is trivially true if `U` is `T`.
702 /// Note that if `U` is not `T` but has the same size and alignment, this is
703 /// basically like transmuting references of different types. See
704 /// [`mem::transmute`][transmute] for more information on what
705 /// restrictions apply in this case.
707 /// The user of `from_raw` has to make sure a specific value of `T` is only
710 /// This function is unsafe because improper use may lead to memory unsafety,
711 /// even if the returned `Arc<T>` is never accessed.
713 /// [into_raw]: Arc::into_raw
714 /// [transmute]: core::mem::transmute
719 /// use std::sync::Arc;
721 /// let x = Arc::new("hello".to_owned());
722 /// let x_ptr = Arc::into_raw(x);
725 /// // Convert back to an `Arc` to prevent leak.
726 /// let x = Arc::from_raw(x_ptr);
727 /// assert_eq!(&*x, "hello");
729 /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.
732 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
734 #[stable(feature = "rc_raw", since = "1.17.0")]
735 pub unsafe fn from_raw(ptr: *const T) -> Self {
737 let offset = data_offset(ptr);
739 // Reverse the offset to find the original ArcInner.
740 let fake_ptr = ptr as *mut ArcInner<T>;
741 let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
743 Self::from_ptr(arc_ptr)
747 /// Creates a new [`Weak`] pointer to this allocation.
752 /// use std::sync::Arc;
754 /// let five = Arc::new(5);
756 /// let weak_five = Arc::downgrade(&five);
758 #[stable(feature = "arc_weak", since = "1.4.0")]
759 pub fn downgrade(this: &Self) -> Weak<T> {
760 // This Relaxed is OK because we're checking the value in the CAS
762 let mut cur = this.inner().weak.load(Relaxed);
765 // check if the weak counter is currently "locked"; if so, spin.
766 if cur == usize::MAX {
767 cur = this.inner().weak.load(Relaxed);
771 // NOTE: this code currently ignores the possibility of overflow
772 // into usize::MAX; in general both Rc and Arc need to be adjusted
773 // to deal with overflow.
775 // Unlike with Clone(), we need this to be an Acquire read to
776 // synchronize with the write coming from `is_unique`, so that the
777 // events prior to that write happen before this read.
778 match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
780 // Make sure we do not create a dangling Weak
781 debug_assert!(!is_dangling(this.ptr));
782 return Weak { ptr: this.ptr };
784 Err(old) => cur = old,
789 /// Gets the number of [`Weak`] pointers to this allocation.
793 /// This method by itself is safe, but using it correctly requires extra care.
794 /// Another thread can change the weak count at any time,
795 /// including potentially between calling this method and acting on the result.
800 /// use std::sync::Arc;
802 /// let five = Arc::new(5);
803 /// let _weak_five = Arc::downgrade(&five);
805 /// // This assertion is deterministic because we haven't shared
806 /// // the `Arc` or `Weak` between threads.
807 /// assert_eq!(1, Arc::weak_count(&five));
810 #[stable(feature = "arc_counts", since = "1.15.0")]
811 pub fn weak_count(this: &Self) -> usize {
812 let cnt = this.inner().weak.load(SeqCst);
813 // If the weak count is currently locked, the value of the
814 // count was 0 just before taking the lock.
815 if cnt == usize::MAX { 0 } else { cnt - 1 }
818 /// Gets the number of strong (`Arc`) pointers to this allocation.
822 /// This method by itself is safe, but using it correctly requires extra care.
823 /// Another thread can change the strong count at any time,
824 /// including potentially between calling this method and acting on the result.
829 /// use std::sync::Arc;
831 /// let five = Arc::new(5);
832 /// let _also_five = Arc::clone(&five);
834 /// // This assertion is deterministic because we haven't shared
835 /// // the `Arc` between threads.
836 /// assert_eq!(2, Arc::strong_count(&five));
839 #[stable(feature = "arc_counts", since = "1.15.0")]
840 pub fn strong_count(this: &Self) -> usize {
841 this.inner().strong.load(SeqCst)
844 /// Increments the strong reference count on the `Arc<T>` associated with the
845 /// provided pointer by one.
849 /// The pointer must have been obtained through `Arc::into_raw`, and the
850 /// associated `Arc` instance must be valid (i.e. the strong count must be at
851 /// least 1) for the duration of this method.
856 /// #![feature(arc_mutate_strong_count)]
858 /// use std::sync::Arc;
860 /// let five = Arc::new(5);
863 /// let ptr = Arc::into_raw(five);
864 /// Arc::incr_strong_count(ptr);
866 /// // This assertion is deterministic because we haven't shared
867 /// // the `Arc` between threads.
868 /// let five = Arc::from_raw(ptr);
869 /// assert_eq!(2, Arc::strong_count(&five));
873 #[unstable(feature = "arc_mutate_strong_count", issue = "71983")]
874 pub unsafe fn incr_strong_count(ptr: *const T) {
875 // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
876 let arc = unsafe { mem::ManuallyDrop::new(Arc::<T>::from_raw(ptr)) };
877 // Now increase refcount, but don't drop new refcount either
878 let _arc_clone: mem::ManuallyDrop<_> = arc.clone();
881 /// Decrements the strong reference count on the `Arc<T>` associated with the
882 /// provided pointer by one.
886 /// The pointer must have been obtained through `Arc::into_raw`, and the
887 /// associated `Arc` instance must be valid (i.e. the strong count must be at
888 /// least 1) when invoking this method. This method can be used to release the final
889 /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been
895 /// #![feature(arc_mutate_strong_count)]
897 /// use std::sync::Arc;
899 /// let five = Arc::new(5);
902 /// let ptr = Arc::into_raw(five);
903 /// Arc::incr_strong_count(ptr);
905 /// // Those assertions are deterministic because we haven't shared
906 /// // the `Arc` between threads.
907 /// let five = Arc::from_raw(ptr);
908 /// assert_eq!(2, Arc::strong_count(&five));
909 /// Arc::decr_strong_count(ptr);
910 /// assert_eq!(1, Arc::strong_count(&five));
914 #[unstable(feature = "arc_mutate_strong_count", issue = "71983")]
915 pub unsafe fn decr_strong_count(ptr: *const T) {
916 unsafe { mem::drop(Arc::from_raw(ptr)) };
920 fn inner(&self) -> &ArcInner<T> {
921 // This unsafety is ok because while this arc is alive we're guaranteed
922 // that the inner pointer is valid. Furthermore, we know that the
923 // `ArcInner` structure itself is `Sync` because the inner data is
924 // `Sync` as well, so we're ok loaning out an immutable pointer to these
926 unsafe { self.ptr.as_ref() }
929 // Non-inlined part of `drop`.
931 unsafe fn drop_slow(&mut self) {
932 // Destroy the data at this time, even though we may not free the box
933 // allocation itself (there may still be weak pointers lying around).
934 unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) };
936 // Drop the weak ref collectively held by all strong references
937 drop(Weak { ptr: self.ptr });
941 #[stable(feature = "ptr_eq", since = "1.17.0")]
942 /// Returns `true` if the two `Arc`s point to the same allocation
943 /// (in a vein similar to [`ptr::eq`]).
948 /// use std::sync::Arc;
950 /// let five = Arc::new(5);
951 /// let same_five = Arc::clone(&five);
952 /// let other_five = Arc::new(5);
954 /// assert!(Arc::ptr_eq(&five, &same_five));
955 /// assert!(!Arc::ptr_eq(&five, &other_five));
958 /// [`ptr::eq`]: core::ptr::eq
959 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
960 this.ptr.as_ptr() == other.ptr.as_ptr()
964 impl<T: ?Sized> Arc<T> {
965 /// Allocates an `ArcInner<T>` with sufficient space for
966 /// a possibly-unsized inner value where the value has the layout provided.
968 /// The function `mem_to_arcinner` is called with the data pointer
969 /// and must return back a (potentially fat)-pointer for the `ArcInner<T>`.
970 unsafe fn allocate_for_layout(
971 value_layout: Layout,
972 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
973 mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner<T>,
974 ) -> *mut ArcInner<T> {
975 // Calculate layout using the given value layout.
976 // Previously, layout was calculated on the expression
977 // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
978 // reference (see #54908).
979 let layout = Layout::new::<ArcInner<()>>().extend(value_layout).unwrap().0.pad_to_align();
981 let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout));
983 // Initialize the ArcInner
984 let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr());
985 debug_assert_eq!(unsafe { Layout::for_value(&*inner) }, layout);
988 ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
989 ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
995 /// Allocates an `ArcInner<T>` with sufficient space for an unsized inner value.
996 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
997 // Allocate for the `ArcInner<T>` using the given value.
999 Self::allocate_for_layout(
1000 Layout::for_value(&*ptr),
1001 |layout| Global.alloc(layout),
1002 |mem| set_data_ptr(ptr as *mut T, mem) as *mut ArcInner<T>,
1007 fn from_box(v: Box<T>) -> Arc<T> {
1009 let box_unique = Box::into_unique(v);
1010 let bptr = box_unique.as_ptr();
1012 let value_size = size_of_val(&*bptr);
1013 let ptr = Self::allocate_for_ptr(bptr);
1015 // Copy value as bytes
1016 ptr::copy_nonoverlapping(
1017 bptr as *const T as *const u8,
1018 &mut (*ptr).data as *mut _ as *mut u8,
1022 // Free the allocation without dropping its contents
1023 box_free(box_unique);
1031 /// Allocates an `ArcInner<[T]>` with the given length.
1032 unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> {
1034 Self::allocate_for_layout(
1035 Layout::array::<T>(len).unwrap(),
1036 |layout| Global.alloc(layout),
1037 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut ArcInner<[T]>,
1043 /// Sets the data pointer of a `?Sized` raw pointer.
1045 /// For a slice/trait object, this sets the `data` field and leaves the rest
1046 /// unchanged. For a sized raw pointer, this simply sets the pointer.
1047 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
1049 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
1055 /// Copy elements from slice into newly allocated Arc<\[T\]>
1057 /// Unsafe because the caller must either take ownership or bind `T: Copy`.
1058 unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
1060 let ptr = Self::allocate_for_slice(v.len());
1062 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).data as *mut [T] as *mut T, v.len());
1068 /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size.
1070 /// Behavior is undefined should the size be wrong.
1071 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Arc<[T]> {
1072 // Panic guard while cloning T elements.
1073 // In the event of a panic, elements that have been written
1074 // into the new ArcInner will be dropped, then the memory freed.
1082 impl<T> Drop for Guard<T> {
1083 fn drop(&mut self) {
1085 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1086 ptr::drop_in_place(slice);
1088 Global.dealloc(self.mem, self.layout);
1094 let ptr = Self::allocate_for_slice(len);
1096 let mem = ptr as *mut _ as *mut u8;
1097 let layout = Layout::for_value(&*ptr);
1099 // Pointer to first element
1100 let elems = &mut (*ptr).data as *mut [T] as *mut T;
1102 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1104 for (i, item) in iter.enumerate() {
1105 ptr::write(elems.add(i), item);
1109 // All clear. Forget the guard so it doesn't free the new ArcInner.
1117 /// Specialization trait used for `From<&[T]>`.
1118 trait ArcFromSlice<T> {
1119 fn from_slice(slice: &[T]) -> Self;
1122 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
1124 default fn from_slice(v: &[T]) -> Self {
1125 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1129 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
1131 fn from_slice(v: &[T]) -> Self {
1132 unsafe { Arc::copy_from_slice(v) }
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<T: ?Sized> Clone for Arc<T> {
1138 /// Makes a clone of the `Arc` pointer.
1140 /// This creates another pointer to the same allocation, increasing the
1141 /// strong reference count.
1146 /// use std::sync::Arc;
1148 /// let five = Arc::new(5);
1150 /// let _ = Arc::clone(&five);
1153 fn clone(&self) -> Arc<T> {
1154 // Using a relaxed ordering is alright here, as knowledge of the
1155 // original reference prevents other threads from erroneously deleting
1158 // As explained in the [Boost documentation][1], Increasing the
1159 // reference counter can always be done with memory_order_relaxed: New
1160 // references to an object can only be formed from an existing
1161 // reference, and passing an existing reference from one thread to
1162 // another must already provide any required synchronization.
1164 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1165 let old_size = self.inner().strong.fetch_add(1, Relaxed);
1167 // However we need to guard against massive refcounts in case someone
1168 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
1169 // and users will use-after free. We racily saturate to `isize::MAX` on
1170 // the assumption that there aren't ~2 billion threads incrementing
1171 // the reference count at once. This branch will never be taken in
1172 // any realistic program.
1174 // We abort because such a program is incredibly degenerate, and we
1175 // don't care to support it.
1176 if old_size > MAX_REFCOUNT {
1180 Self::from_inner(self.ptr)
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<T: ?Sized> Deref for Arc<T> {
1189 fn deref(&self) -> &T {
1194 #[unstable(feature = "receiver_trait", issue = "none")]
1195 impl<T: ?Sized> Receiver for Arc<T> {}
1197 impl<T: Clone> Arc<T> {
1198 /// Makes a mutable reference into the given `Arc`.
1200 /// If there are other `Arc` or [`Weak`] pointers to the same allocation,
1201 /// then `make_mut` will create a new allocation and invoke [`clone`][clone] on the inner value
1202 /// to ensure unique ownership. This is also referred to as clone-on-write.
1204 /// Note that this differs from the behavior of [`Rc::make_mut`] which disassociates
1205 /// any remaining `Weak` pointers.
1207 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
1209 /// [clone]: Clone::clone
1210 /// [get_mut]: Arc::get_mut
1211 /// [`Rc::make_mut`]: super::rc::Rc::make_mut
1216 /// use std::sync::Arc;
1218 /// let mut data = Arc::new(5);
1220 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
1221 /// let mut other_data = Arc::clone(&data); // Won't clone inner data
1222 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
1223 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
1224 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
1226 /// // Now `data` and `other_data` point to different allocations.
1227 /// assert_eq!(*data, 8);
1228 /// assert_eq!(*other_data, 12);
1231 #[stable(feature = "arc_unique", since = "1.4.0")]
1232 pub fn make_mut(this: &mut Self) -> &mut T {
1233 // Note that we hold both a strong reference and a weak reference.
1234 // Thus, releasing our strong reference only will not, by itself, cause
1235 // the memory to be deallocated.
1237 // Use Acquire to ensure that we see any writes to `weak` that happen
1238 // before release writes (i.e., decrements) to `strong`. Since we hold a
1239 // weak count, there's no chance the ArcInner itself could be
1241 if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
1242 // Another strong pointer exists; clone
1243 *this = Arc::new((**this).clone());
1244 } else if this.inner().weak.load(Relaxed) != 1 {
1245 // Relaxed suffices in the above because this is fundamentally an
1246 // optimization: we are always racing with weak pointers being
1247 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
1249 // We removed the last strong ref, but there are additional weak
1250 // refs remaining. We'll move the contents to a new Arc, and
1251 // invalidate the other weak refs.
1253 // Note that it is not possible for the read of `weak` to yield
1254 // usize::MAX (i.e., locked), since the weak count can only be
1255 // locked by a thread with a strong reference.
1257 // Materialize our own implicit weak pointer, so that it can clean
1258 // up the ArcInner as needed.
1259 let weak = Weak { ptr: this.ptr };
1261 // mark the data itself as already deallocated
1263 // there is no data race in the implicit write caused by `read`
1264 // here (due to zeroing) because data is no longer accessed by
1265 // other threads (due to there being no more strong refs at this
1267 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
1268 mem::swap(this, &mut swap);
1272 // We were the sole reference of either kind; bump back up the
1273 // strong ref count.
1274 this.inner().strong.store(1, Release);
1277 // As with `get_mut()`, the unsafety is ok because our reference was
1278 // either unique to begin with, or became one upon cloning the contents.
1279 unsafe { Self::get_mut_unchecked(this) }
1283 impl<T: ?Sized> Arc<T> {
1284 /// Returns a mutable reference into the given `Arc`, if there are
1285 /// no other `Arc` or [`Weak`] pointers to the same allocation.
1287 /// Returns [`None`] otherwise, because it is not safe to
1288 /// mutate a shared value.
1290 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1291 /// the inner value when there are other pointers.
1293 /// [make_mut]: Arc::make_mut
1294 /// [clone]: Clone::clone
1299 /// use std::sync::Arc;
1301 /// let mut x = Arc::new(3);
1302 /// *Arc::get_mut(&mut x).unwrap() = 4;
1303 /// assert_eq!(*x, 4);
1305 /// let _y = Arc::clone(&x);
1306 /// assert!(Arc::get_mut(&mut x).is_none());
1309 #[stable(feature = "arc_unique", since = "1.4.0")]
1310 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1311 if this.is_unique() {
1312 // This unsafety is ok because we're guaranteed that the pointer
1313 // returned is the *only* pointer that will ever be returned to T. Our
1314 // reference count is guaranteed to be 1 at this point, and we required
1315 // the Arc itself to be `mut`, so we're returning the only possible
1316 // reference to the inner data.
1317 unsafe { Some(Arc::get_mut_unchecked(this)) }
1323 /// Returns a mutable reference into the given `Arc`,
1324 /// without any check.
1326 /// See also [`get_mut`], which is safe and does appropriate checks.
1328 /// [`get_mut`]: Arc::get_mut
1332 /// Any other `Arc` or [`Weak`] pointers to the same allocation must not be dereferenced
1333 /// for the duration of the returned borrow.
1334 /// This is trivially the case if no such pointers exist,
1335 /// for example immediately after `Arc::new`.
1340 /// #![feature(get_mut_unchecked)]
1342 /// use std::sync::Arc;
1344 /// let mut x = Arc::new(String::new());
1346 /// Arc::get_mut_unchecked(&mut x).push_str("foo")
1348 /// assert_eq!(*x, "foo");
1351 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1352 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1353 // We are careful to *not* create a reference covering the "count" fields, as
1354 // this would alias with concurrent access to the reference counts (e.g. by `Weak`).
1355 unsafe { &mut (*this.ptr.as_ptr()).data }
1358 /// Determine whether this is the unique reference (including weak refs) to
1359 /// the underlying data.
1361 /// Note that this requires locking the weak ref count.
1362 fn is_unique(&mut self) -> bool {
1363 // lock the weak pointer count if we appear to be the sole weak pointer
1366 // The acquire label here ensures a happens-before relationship with any
1367 // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
1368 // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded
1369 // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
1370 if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
1371 // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
1372 // counter in `drop` -- the only access that happens when any but the last reference
1373 // is being dropped.
1374 let unique = self.inner().strong.load(Acquire) == 1;
1376 // The release write here synchronizes with a read in `downgrade`,
1377 // effectively preventing the above read of `strong` from happening
1379 self.inner().weak.store(1, Release); // release the lock
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
1389 /// Drops the `Arc`.
1391 /// This will decrement the strong reference count. If the strong reference
1392 /// count reaches zero then the only other references (if any) are
1393 /// [`Weak`], so we `drop` the inner value.
1398 /// use std::sync::Arc;
1402 /// impl Drop for Foo {
1403 /// fn drop(&mut self) {
1404 /// println!("dropped!");
1408 /// let foo = Arc::new(Foo);
1409 /// let foo2 = Arc::clone(&foo);
1411 /// drop(foo); // Doesn't print anything
1412 /// drop(foo2); // Prints "dropped!"
1415 fn drop(&mut self) {
1416 // Because `fetch_sub` is already atomic, we do not need to synchronize
1417 // with other threads unless we are going to delete the object. This
1418 // same logic applies to the below `fetch_sub` to the `weak` count.
1419 if self.inner().strong.fetch_sub(1, Release) != 1 {
1423 // This fence is needed to prevent reordering of use of the data and
1424 // deletion of the data. Because it is marked `Release`, the decreasing
1425 // of the reference count synchronizes with this `Acquire` fence. This
1426 // means that use of the data happens before decreasing the reference
1427 // count, which happens before this fence, which happens before the
1428 // deletion of the data.
1430 // As explained in the [Boost documentation][1],
1432 // > It is important to enforce any possible access to the object in one
1433 // > thread (through an existing reference) to *happen before* deleting
1434 // > the object in a different thread. This is achieved by a "release"
1435 // > operation after dropping a reference (any access to the object
1436 // > through this reference must obviously happened before), and an
1437 // > "acquire" operation before deleting the object.
1439 // In particular, while the contents of an Arc are usually immutable, it's
1440 // possible to have interior writes to something like a Mutex<T>. Since a
1441 // Mutex is not acquired when it is deleted, we can't rely on its
1442 // synchronization logic to make writes in thread A visible to a destructor
1443 // running in thread B.
1445 // Also note that the Acquire fence here could probably be replaced with an
1446 // Acquire load, which could improve performance in highly-contended
1447 // situations. See [2].
1449 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1450 // [2]: (https://github.com/rust-lang/rust/pull/41714)
1451 acquire!(self.inner().strong);
1459 impl Arc<dyn Any + Send + Sync> {
1461 #[stable(feature = "rc_downcast", since = "1.29.0")]
1462 /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1467 /// use std::any::Any;
1468 /// use std::sync::Arc;
1470 /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1471 /// if let Ok(string) = value.downcast::<String>() {
1472 /// println!("String ({}): {}", string.len(), string);
1476 /// let my_string = "Hello World".to_string();
1477 /// print_if_string(Arc::new(my_string));
1478 /// print_if_string(Arc::new(0i8));
1480 pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1482 T: Any + Send + Sync + 'static,
1484 if (*self).is::<T>() {
1485 let ptr = self.ptr.cast::<ArcInner<T>>();
1487 Ok(Arc::from_inner(ptr))
1495 /// Constructs a new `Weak<T>`, without allocating any memory.
1496 /// Calling [`upgrade`] on the return value always gives [`None`].
1498 /// [`upgrade`]: Weak::upgrade
1503 /// use std::sync::Weak;
1505 /// let empty: Weak<i64> = Weak::new();
1506 /// assert!(empty.upgrade().is_none());
1508 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1509 pub fn new() -> Weak<T> {
1510 Weak { ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0") }
1514 /// Helper type to allow accessing the reference counts without
1515 /// making any assertions about the data field.
1516 struct WeakInner<'a> {
1517 weak: &'a atomic::AtomicUsize,
1518 strong: &'a atomic::AtomicUsize,
1521 impl<T: ?Sized> Weak<T> {
1522 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1524 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
1525 /// unaligned or even [`null`] otherwise.
1530 /// use std::sync::Arc;
1533 /// let strong = Arc::new("hello".to_owned());
1534 /// let weak = Arc::downgrade(&strong);
1535 /// // Both point to the same object
1536 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
1537 /// // The strong here keeps it alive, so we can still access the object.
1538 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
1541 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
1542 /// // undefined behaviour.
1543 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
1546 /// [`null`]: core::ptr::null
1547 #[stable(feature = "weak_into_raw", since = "1.45.0")]
1548 pub fn as_ptr(&self) -> *const T {
1549 let ptr: *mut ArcInner<T> = NonNull::as_ptr(self.ptr);
1551 // SAFETY: we must offset the pointer manually, and said pointer may be
1552 // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call,
1553 // because we know that a pointer to unsized T was derived from a real
1554 // unsized T, as dangling weaks are only created for sized T. wrapping_offset
1555 // is used so that we can use the same code path for the non-dangling
1556 // unsized case and the potentially dangling sized case.
1558 let offset = data_offset(ptr as *mut T);
1559 set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset))
1563 /// Consumes the `Weak<T>` and turns it into a raw pointer.
1565 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
1566 /// one weak reference (the weak count is not modified by this operation). It can be turned
1567 /// back into the `Weak<T>` with [`from_raw`].
1569 /// The same restrictions of accessing the target of the pointer as with
1570 /// [`as_ptr`] apply.
1575 /// use std::sync::{Arc, Weak};
1577 /// let strong = Arc::new("hello".to_owned());
1578 /// let weak = Arc::downgrade(&strong);
1579 /// let raw = weak.into_raw();
1581 /// assert_eq!(1, Arc::weak_count(&strong));
1582 /// assert_eq!("hello", unsafe { &*raw });
1584 /// drop(unsafe { Weak::from_raw(raw) });
1585 /// assert_eq!(0, Arc::weak_count(&strong));
1588 /// [`from_raw`]: Weak::from_raw
1589 /// [`as_ptr`]: Weak::as_ptr
1590 #[stable(feature = "weak_into_raw", since = "1.45.0")]
1591 pub fn into_raw(self) -> *const T {
1592 let result = self.as_ptr();
1597 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1599 /// This can be used to safely get a strong reference (by calling [`upgrade`]
1600 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1602 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
1603 /// as these don't own anything; the method still works on them).
1607 /// The pointer must have originated from the [`into_raw`] and must still own its potential
1610 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
1611 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
1612 /// count is not modified by this operation) and therefore it must be paired with a previous
1613 /// call to [`into_raw`].
1617 /// use std::sync::{Arc, Weak};
1619 /// let strong = Arc::new("hello".to_owned());
1621 /// let raw_1 = Arc::downgrade(&strong).into_raw();
1622 /// let raw_2 = Arc::downgrade(&strong).into_raw();
1624 /// assert_eq!(2, Arc::weak_count(&strong));
1626 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1627 /// assert_eq!(1, Arc::weak_count(&strong));
1631 /// // Decrement the last weak count.
1632 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1635 /// [`new`]: Weak::new
1636 /// [`into_raw`]: Weak::into_raw
1637 /// [`upgrade`]: Weak::upgrade
1638 /// [`forget`]: std::mem::forget
1639 #[stable(feature = "weak_into_raw", since = "1.45.0")]
1640 pub unsafe fn from_raw(ptr: *const T) -> Self {
1641 // SAFETY: data_offset is safe to call, because this pointer originates from a Weak.
1642 // See Weak::as_ptr for context on how the input pointer is derived.
1643 let offset = unsafe { data_offset(ptr) };
1645 // Reverse the offset to find the original ArcInner.
1646 // SAFETY: we use wrapping_offset here because the pointer may be dangling (but only if T: Sized)
1648 set_data_ptr(ptr as *mut ArcInner<T>, (ptr as *mut u8).wrapping_offset(-offset))
1651 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
1652 unsafe { Weak { ptr: NonNull::new_unchecked(ptr) } }
1655 /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying
1656 /// dropping of the inner value if successful.
1658 /// Returns [`None`] if the inner value has since been dropped.
1663 /// use std::sync::Arc;
1665 /// let five = Arc::new(5);
1667 /// let weak_five = Arc::downgrade(&five);
1669 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1670 /// assert!(strong_five.is_some());
1672 /// // Destroy all strong pointers.
1673 /// drop(strong_five);
1676 /// assert!(weak_five.upgrade().is_none());
1678 #[stable(feature = "arc_weak", since = "1.4.0")]
1679 pub fn upgrade(&self) -> Option<Arc<T>> {
1680 // We use a CAS loop to increment the strong count instead of a
1681 // fetch_add as this function should never take the reference count
1682 // from zero to one.
1683 let inner = self.inner()?;
1685 // Relaxed load because any write of 0 that we can observe
1686 // leaves the field in a permanently zero state (so a
1687 // "stale" read of 0 is fine), and any other value is
1688 // confirmed via the CAS below.
1689 let mut n = inner.strong.load(Relaxed);
1696 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1697 if n > MAX_REFCOUNT {
1701 // Relaxed is fine for the failure case because we don't have any expectations about the new state.
1702 // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner
1703 // value can be initialized after `Weak` references have already been created. In that case, we
1704 // expect to observe the fully initialized value.
1705 match inner.strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed) {
1706 Ok(_) => return Some(Arc::from_inner(self.ptr)), // null checked above
1707 Err(old) => n = old,
1712 /// Gets the number of strong (`Arc`) pointers pointing to this allocation.
1714 /// If `self` was created using [`Weak::new`], this will return 0.
1715 #[stable(feature = "weak_counts", since = "1.41.0")]
1716 pub fn strong_count(&self) -> usize {
1717 if let Some(inner) = self.inner() { inner.strong.load(SeqCst) } else { 0 }
1720 /// Gets an approximation of the number of `Weak` pointers pointing to this
1723 /// If `self` was created using [`Weak::new`], or if there are no remaining
1724 /// strong pointers, this will return 0.
1728 /// Due to implementation details, the returned value can be off by 1 in
1729 /// either direction when other threads are manipulating any `Arc`s or
1730 /// `Weak`s pointing to the same allocation.
1731 #[stable(feature = "weak_counts", since = "1.41.0")]
1732 pub fn weak_count(&self) -> usize {
1735 let weak = inner.weak.load(SeqCst);
1736 let strong = inner.strong.load(SeqCst);
1740 // Since we observed that there was at least one strong pointer
1741 // after reading the weak count, we know that the implicit weak
1742 // reference (present whenever any strong references are alive)
1743 // was still around when we observed the weak count, and can
1744 // therefore safely subtract it.
1751 /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
1752 /// (i.e., when this `Weak` was created by `Weak::new`).
1754 fn inner(&self) -> Option<WeakInner<'_>> {
1755 if is_dangling(self.ptr) {
1758 // We are careful to *not* create a reference covering the "data" field, as
1759 // the field may be mutated concurrently (for example, if the last `Arc`
1760 // is dropped, the data field will be dropped in-place).
1762 let ptr = self.ptr.as_ptr();
1763 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
1768 /// Returns `true` if the two `Weak`s point to the same allocation (similar to
1769 /// [`ptr::eq`]), or if both don't point to any allocation
1770 /// (because they were created with `Weak::new()`).
1774 /// Since this compares pointers it means that `Weak::new()` will equal each
1775 /// other, even though they don't point to any allocation.
1780 /// use std::sync::Arc;
1782 /// let first_rc = Arc::new(5);
1783 /// let first = Arc::downgrade(&first_rc);
1784 /// let second = Arc::downgrade(&first_rc);
1786 /// assert!(first.ptr_eq(&second));
1788 /// let third_rc = Arc::new(5);
1789 /// let third = Arc::downgrade(&third_rc);
1791 /// assert!(!first.ptr_eq(&third));
1794 /// Comparing `Weak::new`.
1797 /// use std::sync::{Arc, Weak};
1799 /// let first = Weak::new();
1800 /// let second = Weak::new();
1801 /// assert!(first.ptr_eq(&second));
1803 /// let third_rc = Arc::new(());
1804 /// let third = Arc::downgrade(&third_rc);
1805 /// assert!(!first.ptr_eq(&third));
1808 /// [`ptr::eq`]: core::ptr::eq
1810 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1811 pub fn ptr_eq(&self, other: &Self) -> bool {
1812 self.ptr.as_ptr() == other.ptr.as_ptr()
1816 #[stable(feature = "arc_weak", since = "1.4.0")]
1817 impl<T: ?Sized> Clone for Weak<T> {
1818 /// Makes a clone of the `Weak` pointer that points to the same allocation.
1823 /// use std::sync::{Arc, Weak};
1825 /// let weak_five = Arc::downgrade(&Arc::new(5));
1827 /// let _ = Weak::clone(&weak_five);
1830 fn clone(&self) -> Weak<T> {
1831 let inner = if let Some(inner) = self.inner() {
1834 return Weak { ptr: self.ptr };
1836 // See comments in Arc::clone() for why this is relaxed. This can use a
1837 // fetch_add (ignoring the lock) because the weak count is only locked
1838 // where are *no other* weak pointers in existence. (So we can't be
1839 // running this code in that case).
1840 let old_size = inner.weak.fetch_add(1, Relaxed);
1842 // See comments in Arc::clone() for why we do this (for mem::forget).
1843 if old_size > MAX_REFCOUNT {
1847 Weak { ptr: self.ptr }
1851 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1852 impl<T> Default for Weak<T> {
1853 /// Constructs a new `Weak<T>`, without allocating memory.
1854 /// Calling [`upgrade`] on the return value always
1857 /// [`upgrade`]: Weak::upgrade
1862 /// use std::sync::Weak;
1864 /// let empty: Weak<i64> = Default::default();
1865 /// assert!(empty.upgrade().is_none());
1867 fn default() -> Weak<T> {
1872 #[stable(feature = "arc_weak", since = "1.4.0")]
1873 impl<T: ?Sized> Drop for Weak<T> {
1874 /// Drops the `Weak` pointer.
1879 /// use std::sync::{Arc, Weak};
1883 /// impl Drop for Foo {
1884 /// fn drop(&mut self) {
1885 /// println!("dropped!");
1889 /// let foo = Arc::new(Foo);
1890 /// let weak_foo = Arc::downgrade(&foo);
1891 /// let other_weak_foo = Weak::clone(&weak_foo);
1893 /// drop(weak_foo); // Doesn't print anything
1894 /// drop(foo); // Prints "dropped!"
1896 /// assert!(other_weak_foo.upgrade().is_none());
1898 fn drop(&mut self) {
1899 // If we find out that we were the last weak pointer, then its time to
1900 // deallocate the data entirely. See the discussion in Arc::drop() about
1901 // the memory orderings
1903 // It's not necessary to check for the locked state here, because the
1904 // weak count can only be locked if there was precisely one weak ref,
1905 // meaning that drop could only subsequently run ON that remaining weak
1906 // ref, which can only happen after the lock is released.
1907 let inner = if let Some(inner) = self.inner() { inner } else { return };
1909 if inner.weak.fetch_sub(1, Release) == 1 {
1910 acquire!(inner.weak);
1911 unsafe { Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())) }
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 trait ArcEqIdent<T: ?Sized + PartialEq> {
1918 fn eq(&self, other: &Arc<T>) -> bool;
1919 fn ne(&self, other: &Arc<T>) -> bool;
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1925 default fn eq(&self, other: &Arc<T>) -> bool {
1929 default fn ne(&self, other: &Arc<T>) -> bool {
1934 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1935 /// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
1936 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1937 /// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
1938 /// the same value, than two `&T`s.
1940 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl<T: ?Sized + crate::rc::MarkerEq> ArcEqIdent<T> for Arc<T> {
1944 fn eq(&self, other: &Arc<T>) -> bool {
1945 Arc::ptr_eq(self, other) || **self == **other
1949 fn ne(&self, other: &Arc<T>) -> bool {
1950 !Arc::ptr_eq(self, other) && **self != **other
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1956 /// Equality for two `Arc`s.
1958 /// Two `Arc`s are equal if their inner values are equal, even if they are
1959 /// stored in different allocation.
1961 /// If `T` also implements `Eq` (implying reflexivity of equality),
1962 /// two `Arc`s that point to the same allocation are always equal.
1967 /// use std::sync::Arc;
1969 /// let five = Arc::new(5);
1971 /// assert!(five == Arc::new(5));
1974 fn eq(&self, other: &Arc<T>) -> bool {
1975 ArcEqIdent::eq(self, other)
1978 /// Inequality for two `Arc`s.
1980 /// Two `Arc`s are unequal if their inner values are unequal.
1982 /// If `T` also implements `Eq` (implying reflexivity of equality),
1983 /// two `Arc`s that point to the same value are never unequal.
1988 /// use std::sync::Arc;
1990 /// let five = Arc::new(5);
1992 /// assert!(five != Arc::new(6));
1995 fn ne(&self, other: &Arc<T>) -> bool {
1996 ArcEqIdent::ne(self, other)
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
2002 /// Partial comparison for two `Arc`s.
2004 /// The two are compared by calling `partial_cmp()` on their inner values.
2009 /// use std::sync::Arc;
2010 /// use std::cmp::Ordering;
2012 /// let five = Arc::new(5);
2014 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
2016 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
2017 (**self).partial_cmp(&**other)
2020 /// Less-than comparison for two `Arc`s.
2022 /// The two are compared by calling `<` on their inner values.
2027 /// use std::sync::Arc;
2029 /// let five = Arc::new(5);
2031 /// assert!(five < Arc::new(6));
2033 fn lt(&self, other: &Arc<T>) -> bool {
2034 *(*self) < *(*other)
2037 /// 'Less than or equal to' comparison for two `Arc`s.
2039 /// The two are compared by calling `<=` on their inner values.
2044 /// use std::sync::Arc;
2046 /// let five = Arc::new(5);
2048 /// assert!(five <= Arc::new(5));
2050 fn le(&self, other: &Arc<T>) -> bool {
2051 *(*self) <= *(*other)
2054 /// Greater-than comparison for two `Arc`s.
2056 /// The two are compared by calling `>` on their inner values.
2061 /// use std::sync::Arc;
2063 /// let five = Arc::new(5);
2065 /// assert!(five > Arc::new(4));
2067 fn gt(&self, other: &Arc<T>) -> bool {
2068 *(*self) > *(*other)
2071 /// 'Greater than or equal to' comparison for two `Arc`s.
2073 /// The two are compared by calling `>=` on their inner values.
2078 /// use std::sync::Arc;
2080 /// let five = Arc::new(5);
2082 /// assert!(five >= Arc::new(5));
2084 fn ge(&self, other: &Arc<T>) -> bool {
2085 *(*self) >= *(*other)
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 impl<T: ?Sized + Ord> Ord for Arc<T> {
2090 /// Comparison for two `Arc`s.
2092 /// The two are compared by calling `cmp()` on their inner values.
2097 /// use std::sync::Arc;
2098 /// use std::cmp::Ordering;
2100 /// let five = Arc::new(5);
2102 /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
2104 fn cmp(&self, other: &Arc<T>) -> Ordering {
2105 (**self).cmp(&**other)
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<T: ?Sized + Eq> Eq for Arc<T> {}
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
2113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114 fmt::Display::fmt(&**self, f)
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
2120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2121 fmt::Debug::fmt(&**self, f)
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl<T: ?Sized> fmt::Pointer for Arc<T> {
2127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2128 fmt::Pointer::fmt(&(&**self as *const T), f)
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl<T: Default> Default for Arc<T> {
2134 /// Creates a new `Arc<T>`, with the `Default` value for `T`.
2139 /// use std::sync::Arc;
2141 /// let x: Arc<i32> = Default::default();
2142 /// assert_eq!(*x, 0);
2144 fn default() -> Arc<T> {
2145 Arc::new(Default::default())
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl<T: ?Sized + Hash> Hash for Arc<T> {
2151 fn hash<H: Hasher>(&self, state: &mut H) {
2152 (**self).hash(state)
2156 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
2157 impl<T> From<T> for Arc<T> {
2158 fn from(t: T) -> Self {
2163 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2164 impl<T: Clone> From<&[T]> for Arc<[T]> {
2166 fn from(v: &[T]) -> Arc<[T]> {
2167 <Self as ArcFromSlice<T>>::from_slice(v)
2171 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2172 impl From<&str> for Arc<str> {
2174 fn from(v: &str) -> Arc<str> {
2175 let arc = Arc::<[u8]>::from(v.as_bytes());
2176 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
2180 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2181 impl From<String> for Arc<str> {
2183 fn from(v: String) -> Arc<str> {
2188 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2189 impl<T: ?Sized> From<Box<T>> for Arc<T> {
2191 fn from(v: Box<T>) -> Arc<T> {
2196 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2197 impl<T> From<Vec<T>> for Arc<[T]> {
2199 fn from(mut v: Vec<T>) -> Arc<[T]> {
2201 let arc = Arc::copy_from_slice(&v);
2203 // Allow the Vec to free its memory, but not destroy its contents
2211 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2212 impl<'a, B> From<Cow<'a, B>> for Arc<B>
2214 B: ToOwned + ?Sized,
2215 Arc<B>: From<&'a B> + From<B::Owned>,
2218 fn from(cow: Cow<'a, B>) -> Arc<B> {
2220 Cow::Borrowed(s) => Arc::from(s),
2221 Cow::Owned(s) => Arc::from(s),
2226 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2227 impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> {
2228 type Error = Arc<[T]>;
2230 fn try_from(boxed_slice: Arc<[T]>) -> Result<Self, Self::Error> {
2231 if boxed_slice.len() == N {
2232 Ok(unsafe { Arc::from_raw(Arc::into_raw(boxed_slice) as *mut [T; N]) })
2239 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2240 impl<T> iter::FromIterator<T> for Arc<[T]> {
2241 /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
2243 /// # Performance characteristics
2245 /// ## The general case
2247 /// In the general case, collecting into `Arc<[T]>` is done by first
2248 /// collecting into a `Vec<T>`. That is, when writing the following:
2251 /// # use std::sync::Arc;
2252 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2253 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2256 /// this behaves as if we wrote:
2259 /// # use std::sync::Arc;
2260 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2261 /// .collect::<Vec<_>>() // The first set of allocations happens here.
2262 /// .into(); // A second allocation for `Arc<[T]>` happens here.
2263 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2266 /// This will allocate as many times as needed for constructing the `Vec<T>`
2267 /// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
2269 /// ## Iterators of known length
2271 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2272 /// a single allocation will be made for the `Arc<[T]>`. For example:
2275 /// # use std::sync::Arc;
2276 /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2277 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2279 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
2280 ToArcSlice::to_arc_slice(iter.into_iter())
2284 /// Specialization trait used for collecting into `Arc<[T]>`.
2285 trait ToArcSlice<T>: Iterator<Item = T> + Sized {
2286 fn to_arc_slice(self) -> Arc<[T]>;
2289 impl<T, I: Iterator<Item = T>> ToArcSlice<T> for I {
2290 default fn to_arc_slice(self) -> Arc<[T]> {
2291 self.collect::<Vec<T>>().into()
2295 impl<T, I: iter::TrustedLen<Item = T>> ToArcSlice<T> for I {
2296 fn to_arc_slice(self) -> Arc<[T]> {
2297 // This is the case for a `TrustedLen` iterator.
2298 let (low, high) = self.size_hint();
2299 if let Some(high) = high {
2303 "TrustedLen iterator's size hint is not exact: {:?}",
2308 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2309 Arc::from_iter_exact(self, low)
2312 // Fall back to normal implementation.
2313 self.collect::<Vec<T>>().into()
2318 #[stable(feature = "rust1", since = "1.0.0")]
2319 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2320 fn borrow(&self) -> &T {
2325 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2326 impl<T: ?Sized> AsRef<T> for Arc<T> {
2327 fn as_ref(&self) -> &T {
2332 #[stable(feature = "pin", since = "1.33.0")]
2333 impl<T: ?Sized> Unpin for Arc<T> {}
2335 /// Get the offset within an `ArcInner` for
2336 /// a payload of type described by a pointer.
2340 /// This has the same safety requirements as `align_of_val_raw`. In effect:
2342 /// - This function is safe for any argument if `T` is sized, and
2343 /// - if `T` is unsized, the pointer must have appropriate pointer metadata
2344 /// acquired from the real instance that you are getting this offset for.
2345 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2346 // Align the unsized value to the end of the `ArcInner`.
2347 // Because it is `?Sized`, it will always be the last field in memory.
2348 // Note: This is a detail of the current implementation of the compiler,
2349 // and is not a guaranteed language detail. Do not rely on it outside of std.
2350 unsafe { data_offset_align(align_of_val(&*ptr)) }
2354 fn data_offset_align(align: usize) -> isize {
2355 let layout = Layout::new::<ArcInner<()>>();
2356 (layout.size() + layout.padding_needed_for(align)) as isize