1 #![stable(feature = "rust1", since = "1.0.0")]
3 //! Thread-safe reference-counting pointers.
5 //! See the [`Arc<T>`][arc] documentation for more details.
7 //! [arc]: struct.Arc.html
10 use core::sync::atomic;
11 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
14 use core::cmp::{self, Ordering};
16 use core::intrinsics::abort;
17 use core::mem::{self, align_of, align_of_val, size_of_val};
18 use core::ops::{Deref, Receiver, CoerceUnsized, DispatchFromDyn};
20 use core::ptr::{self, NonNull};
21 use core::marker::{Unpin, Unsize, PhantomData};
22 use core::hash::{Hash, Hasher};
23 use core::{isize, usize};
24 use core::convert::From;
25 use core::slice::{self, from_raw_parts_mut};
27 use crate::alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
28 use crate::boxed::Box;
29 use crate::rc::is_dangling;
30 use crate::string::String;
36 /// A soft limit on the amount of references that may be made to an `Arc`.
38 /// Going above this limit will abort your program (although not
39 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
40 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
42 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
43 /// Reference Counted'.
45 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
46 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
47 /// a new `Arc` instance, which points to the same value on the heap as the
48 /// source `Arc`, while increasing a reference count. When the last `Arc`
49 /// pointer to a given value is destroyed, the pointed-to value is also
52 /// Shared references in Rust disallow mutation by default, and `Arc` is no
53 /// exception: you cannot generally obtain a mutable reference to something
54 /// inside an `Arc`. If you need to mutate through an `Arc`, use
55 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
60 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
61 /// counting. This means that it is thread-safe. The disadvantage is that
62 /// atomic operations are more expensive than ordinary memory accesses. If you
63 /// are not sharing reference-counted values between threads, consider using
64 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
65 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
66 /// However, a library might choose `Arc<T>` in order to give library consumers
69 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
70 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
71 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
72 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
73 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
74 /// data, but it doesn't add thread safety to its data. Consider
75 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
76 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
77 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
78 /// non-atomic operations.
80 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
81 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
83 /// ## Breaking cycles with `Weak`
85 /// The [`downgrade`][downgrade] method can be used to create a non-owning
86 /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d
87 /// to an `Arc`, but this will return [`None`] if the value has already been
90 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
91 /// [`Weak`][weak] is used to break cycles. For example, a tree could have
92 /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak]
93 /// pointers from children back to their parents.
95 /// # Cloning references
97 /// Creating a new reference from an existing reference counted pointer is done using the
98 /// `Clone` trait implemented for [`Arc<T>`][arc] and [`Weak<T>`][weak].
101 /// use std::sync::Arc;
102 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
103 /// // The two syntaxes below are equivalent.
104 /// let a = foo.clone();
105 /// let b = Arc::clone(&foo);
106 /// // a, b, and foo are all Arcs that point to the same memory location
109 /// ## `Deref` behavior
111 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
112 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
113 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are associated
114 /// functions, called using function-like syntax:
117 /// use std::sync::Arc;
118 /// let my_arc = Arc::new(());
120 /// Arc::downgrade(&my_arc);
123 /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have
124 /// already been destroyed.
126 /// [arc]: struct.Arc.html
127 /// [weak]: struct.Weak.html
128 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
129 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
130 /// [mutex]: ../../std/sync/struct.Mutex.html
131 /// [rwlock]: ../../std/sync/struct.RwLock.html
132 /// [atomic]: ../../std/sync/atomic/index.html
133 /// [`Send`]: ../../std/marker/trait.Send.html
134 /// [`Sync`]: ../../std/marker/trait.Sync.html
135 /// [deref]: ../../std/ops/trait.Deref.html
136 /// [downgrade]: struct.Arc.html#method.downgrade
137 /// [upgrade]: struct.Weak.html#method.upgrade
138 /// [`None`]: ../../std/option/enum.Option.html#variant.None
139 /// [`RefCell<T>`]: ../../std/cell/struct.RefCell.html
140 /// [`std::sync`]: ../../std/sync/index.html
141 /// [`Arc::clone(&from)`]: #method.clone
145 /// Sharing some immutable data between threads:
147 // Note that we **do not** run these tests here. The windows builders get super
148 // unhappy if a thread outlives the main thread and then exits at the same time
149 // (something deadlocks) so we just avoid this entirely by not running these
152 /// use std::sync::Arc;
155 /// let five = Arc::new(5);
158 /// let five = Arc::clone(&five);
160 /// thread::spawn(move || {
161 /// println!("{:?}", five);
166 /// Sharing a mutable [`AtomicUsize`]:
168 /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html
171 /// use std::sync::Arc;
172 /// use std::sync::atomic::{AtomicUsize, Ordering};
175 /// let val = Arc::new(AtomicUsize::new(5));
178 /// let val = Arc::clone(&val);
180 /// thread::spawn(move || {
181 /// let v = val.fetch_add(1, Ordering::SeqCst);
182 /// println!("{:?}", v);
187 /// See the [`rc` documentation][rc_examples] for more examples of reference
188 /// counting in general.
190 /// [rc_examples]: ../../std/rc/index.html#examples
191 #[cfg_attr(not(test), lang = "arc")]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub struct Arc<T: ?Sized> {
194 ptr: NonNull<ArcInner<T>>,
195 phantom: PhantomData<T>,
198 #[stable(feature = "rust1", since = "1.0.0")]
199 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
203 #[unstable(feature = "coerce_unsized", issue = "27732")]
204 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
206 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
207 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}
209 impl<T: ?Sized> Arc<T> {
210 fn from_inner(ptr: NonNull<ArcInner<T>>) -> Self {
213 phantom: PhantomData,
217 unsafe fn from_ptr(ptr: *mut ArcInner<T>) -> Self {
218 Self::from_inner(NonNull::new_unchecked(ptr))
222 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
223 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
224 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
226 /// Since a `Weak` reference does not count towards ownership, it will not
227 /// prevent the inner value from being dropped, and `Weak` itself makes no
228 /// guarantees about the value still being present and may return [`None`]
229 /// when [`upgrade`]d.
231 /// A `Weak` pointer is useful for keeping a temporary reference to the value
232 /// within [`Arc`] without extending its lifetime. It is also used to prevent
233 /// circular references between [`Arc`] pointers, since mutual owning references
234 /// would never allow either [`Arc`] to be dropped. For example, a tree could
235 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
236 /// pointers from children back to their parents.
238 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
240 /// [`Arc`]: struct.Arc.html
241 /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade
242 /// [`upgrade`]: struct.Weak.html#method.upgrade
243 /// [`Option`]: ../../std/option/enum.Option.html
244 /// [`None`]: ../../std/option/enum.Option.html#variant.None
245 #[stable(feature = "arc_weak", since = "1.4.0")]
246 pub struct Weak<T: ?Sized> {
247 // This is a `NonNull` to allow optimizing the size of this type in enums,
248 // but it is not necessarily a valid pointer.
249 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
250 // to allocate space on the heap. That's not a value a real pointer
251 // will ever have because RcBox has alignment at least 2.
252 ptr: NonNull<ArcInner<T>>,
255 #[stable(feature = "arc_weak", since = "1.4.0")]
256 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
257 #[stable(feature = "arc_weak", since = "1.4.0")]
258 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
260 #[unstable(feature = "coerce_unsized", issue = "27732")]
261 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
262 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
263 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
265 #[stable(feature = "arc_weak", since = "1.4.0")]
266 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 struct ArcInner<T: ?Sized> {
273 strong: atomic::AtomicUsize,
275 // the value usize::MAX acts as a sentinel for temporarily "locking" the
276 // ability to upgrade weak pointers or downgrade strong ones; this is used
277 // to avoid races in `make_mut` and `get_mut`.
278 weak: atomic::AtomicUsize,
283 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
284 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
287 /// Constructs a new `Arc<T>`.
292 /// use std::sync::Arc;
294 /// let five = Arc::new(5);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn new(data: T) -> Arc<T> {
299 // Start the weak pointer count as 1 which is the weak pointer that's
300 // held by all the strong pointers (kinda), see std/rc.rs for more info
301 let x: Box<_> = box ArcInner {
302 strong: atomic::AtomicUsize::new(1),
303 weak: atomic::AtomicUsize::new(1),
306 Self::from_inner(Box::into_raw_non_null(x))
309 /// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
310 /// `data` will be pinned in memory and unable to be moved.
311 #[stable(feature = "pin", since = "1.33.0")]
312 pub fn pin(data: T) -> Pin<Arc<T>> {
313 unsafe { Pin::new_unchecked(Arc::new(data)) }
316 /// Returns the contained value, if the `Arc` has exactly one strong reference.
318 /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was
321 /// This will succeed even if there are outstanding weak references.
323 /// [result]: ../../std/result/enum.Result.html
328 /// use std::sync::Arc;
330 /// let x = Arc::new(3);
331 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
333 /// let x = Arc::new(4);
334 /// let _y = Arc::clone(&x);
335 /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
338 #[stable(feature = "arc_unique", since = "1.4.0")]
339 pub fn try_unwrap(this: Self) -> Result<T, Self> {
340 // See `drop` for why all these atomics are like this
341 if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() {
345 atomic::fence(Acquire);
348 let elem = ptr::read(&this.ptr.as_ref().data);
350 // Make a weak pointer to clean up the implicit strong-weak reference
351 let _weak = Weak { ptr: this.ptr };
359 impl<T: ?Sized> Arc<T> {
360 /// Consumes the `Arc`, returning the wrapped pointer.
362 /// To avoid a memory leak the pointer must be converted back to an `Arc` using
363 /// [`Arc::from_raw`][from_raw].
365 /// [from_raw]: struct.Arc.html#method.from_raw
370 /// use std::sync::Arc;
372 /// let x = Arc::new("hello".to_owned());
373 /// let x_ptr = Arc::into_raw(x);
374 /// assert_eq!(unsafe { &*x_ptr }, "hello");
376 #[stable(feature = "rc_raw", since = "1.17.0")]
377 pub fn into_raw(this: Self) -> *const T {
378 let ptr: *const T = &*this;
383 /// Constructs an `Arc` from a raw pointer.
385 /// The raw pointer must have been previously returned by a call to a
386 /// [`Arc::into_raw`][into_raw].
388 /// This function is unsafe because improper use may lead to memory problems. For example, a
389 /// double-free may occur if the function is called twice on the same raw pointer.
391 /// [into_raw]: struct.Arc.html#method.into_raw
396 /// use std::sync::Arc;
398 /// let x = Arc::new("hello".to_owned());
399 /// let x_ptr = Arc::into_raw(x);
402 /// // Convert back to an `Arc` to prevent leak.
403 /// let x = Arc::from_raw(x_ptr);
404 /// assert_eq!(&*x, "hello");
406 /// // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe.
409 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
411 #[stable(feature = "rc_raw", since = "1.17.0")]
412 pub unsafe fn from_raw(ptr: *const T) -> Self {
413 let offset = data_offset(ptr);
415 // Reverse the offset to find the original ArcInner.
416 let fake_ptr = ptr as *mut ArcInner<T>;
417 let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
419 Self::from_ptr(arc_ptr)
422 /// Consumes the `Arc`, returning the wrapped pointer as `NonNull<T>`.
427 /// #![feature(rc_into_raw_non_null)]
429 /// use std::sync::Arc;
431 /// let x = Arc::new("hello".to_owned());
432 /// let ptr = Arc::into_raw_non_null(x);
433 /// let deref = unsafe { ptr.as_ref() };
434 /// assert_eq!(deref, "hello");
436 #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
438 pub fn into_raw_non_null(this: Self) -> NonNull<T> {
439 // safe because Arc guarantees its pointer is non-null
440 unsafe { NonNull::new_unchecked(Arc::into_raw(this) as *mut _) }
443 /// Creates a new [`Weak`][weak] pointer to this value.
445 /// [weak]: struct.Weak.html
450 /// use std::sync::Arc;
452 /// let five = Arc::new(5);
454 /// let weak_five = Arc::downgrade(&five);
456 #[stable(feature = "arc_weak", since = "1.4.0")]
457 pub fn downgrade(this: &Self) -> Weak<T> {
458 // This Relaxed is OK because we're checking the value in the CAS
460 let mut cur = this.inner().weak.load(Relaxed);
463 // check if the weak counter is currently "locked"; if so, spin.
464 if cur == usize::MAX {
465 cur = this.inner().weak.load(Relaxed);
469 // NOTE: this code currently ignores the possibility of overflow
470 // into usize::MAX; in general both Rc and Arc need to be adjusted
471 // to deal with overflow.
473 // Unlike with Clone(), we need this to be an Acquire read to
474 // synchronize with the write coming from `is_unique`, so that the
475 // events prior to that write happen before this read.
476 match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
478 // Make sure we do not create a dangling Weak
479 debug_assert!(!is_dangling(this.ptr));
480 return Weak { ptr: this.ptr };
482 Err(old) => cur = old,
487 /// Gets the number of [`Weak`][weak] pointers to this value.
489 /// [weak]: struct.Weak.html
493 /// This method by itself is safe, but using it correctly requires extra care.
494 /// Another thread can change the weak count at any time,
495 /// including potentially between calling this method and acting on the result.
500 /// use std::sync::Arc;
502 /// let five = Arc::new(5);
503 /// let _weak_five = Arc::downgrade(&five);
505 /// // This assertion is deterministic because we haven't shared
506 /// // the `Arc` or `Weak` between threads.
507 /// assert_eq!(1, Arc::weak_count(&five));
510 #[stable(feature = "arc_counts", since = "1.15.0")]
511 pub fn weak_count(this: &Self) -> usize {
512 let cnt = this.inner().weak.load(SeqCst);
513 // If the weak count is currently locked, the value of the
514 // count was 0 just before taking the lock.
515 if cnt == usize::MAX { 0 } else { cnt - 1 }
518 /// Gets the number of strong (`Arc`) pointers to this value.
522 /// This method by itself is safe, but using it correctly requires extra care.
523 /// Another thread can change the strong count at any time,
524 /// including potentially between calling this method and acting on the result.
529 /// use std::sync::Arc;
531 /// let five = Arc::new(5);
532 /// let _also_five = Arc::clone(&five);
534 /// // This assertion is deterministic because we haven't shared
535 /// // the `Arc` between threads.
536 /// assert_eq!(2, Arc::strong_count(&five));
539 #[stable(feature = "arc_counts", since = "1.15.0")]
540 pub fn strong_count(this: &Self) -> usize {
541 this.inner().strong.load(SeqCst)
545 fn inner(&self) -> &ArcInner<T> {
546 // This unsafety is ok because while this arc is alive we're guaranteed
547 // that the inner pointer is valid. Furthermore, we know that the
548 // `ArcInner` structure itself is `Sync` because the inner data is
549 // `Sync` as well, so we're ok loaning out an immutable pointer to these
551 unsafe { self.ptr.as_ref() }
554 // Non-inlined part of `drop`.
556 unsafe fn drop_slow(&mut self) {
557 // Destroy the data at this time, even though we may not free the box
558 // allocation itself (there may still be weak pointers lying around).
559 ptr::drop_in_place(&mut self.ptr.as_mut().data);
561 if self.inner().weak.fetch_sub(1, Release) == 1 {
562 atomic::fence(Acquire);
563 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
568 #[stable(feature = "ptr_eq", since = "1.17.0")]
569 /// Returns `true` if the two `Arc`s point to the same value (not
570 /// just values that compare as equal).
575 /// use std::sync::Arc;
577 /// let five = Arc::new(5);
578 /// let same_five = Arc::clone(&five);
579 /// let other_five = Arc::new(5);
581 /// assert!(Arc::ptr_eq(&five, &same_five));
582 /// assert!(!Arc::ptr_eq(&five, &other_five));
584 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
585 this.ptr.as_ptr() == other.ptr.as_ptr()
589 impl<T: ?Sized> Arc<T> {
590 /// Allocates an `ArcInner<T>` with sufficient space for
591 /// an unsized value where the value has the layout provided.
593 /// The function `mem_to_arcinner` is called with the data pointer
594 /// and must return back a (potentially fat)-pointer for the `ArcInner<T>`.
595 unsafe fn allocate_for_unsized(
596 value_layout: Layout,
597 mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner<T>
598 ) -> *mut ArcInner<T> {
599 // Calculate layout using the given value layout.
600 // Previously, layout was calculated on the expression
601 // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
602 // reference (see #54908).
603 let layout = Layout::new::<ArcInner<()>>()
604 .extend(value_layout).unwrap().0
605 .pad_to_align().unwrap();
607 let mem = Global.alloc(layout)
608 .unwrap_or_else(|_| handle_alloc_error(layout));
610 // Initialize the ArcInner
611 let inner = mem_to_arcinner(mem.as_ptr());
612 debug_assert_eq!(Layout::for_value(&*inner), layout);
614 ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
615 ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
620 /// Allocates an `ArcInner<T>` with sufficient space for an unsized value.
621 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
622 // Allocate for the `ArcInner<T>` using the given value.
623 Self::allocate_for_unsized(
624 Layout::for_value(&*ptr),
625 |mem| set_data_ptr(ptr as *mut T, mem) as *mut ArcInner<T>,
629 fn from_box(v: Box<T>) -> Arc<T> {
631 let box_unique = Box::into_unique(v);
632 let bptr = box_unique.as_ptr();
634 let value_size = size_of_val(&*bptr);
635 let ptr = Self::allocate_for_ptr(bptr);
637 // Copy value as bytes
638 ptr::copy_nonoverlapping(
639 bptr as *const T as *const u8,
640 &mut (*ptr).data as *mut _ as *mut u8,
643 // Free the allocation without dropping its contents
644 box_free(box_unique);
652 /// Allocates an `ArcInner<[T]>` with the given length.
653 unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> {
654 Self::allocate_for_unsized(
655 Layout::array::<T>(len).unwrap(),
656 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut ArcInner<[T]>,
661 /// Sets the data pointer of a `?Sized` raw pointer.
663 /// For a slice/trait object, this sets the `data` field and leaves the rest
664 /// unchanged. For a sized raw pointer, this simply sets the pointer.
665 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
666 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
671 /// Copy elements from slice into newly allocated Arc<[T]>
673 /// Unsafe because the caller must either take ownership or bind `T: Copy`.
674 unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
675 let ptr = Self::allocate_for_slice(v.len());
677 ptr::copy_nonoverlapping(
679 &mut (*ptr).data as *mut [T] as *mut T,
685 /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size.
687 /// Behavior is undefined should the size be wrong.
688 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Arc<[T]> {
689 // Panic guard while cloning T elements.
690 // In the event of a panic, elements that have been written
691 // into the new ArcInner will be dropped, then the memory freed.
699 impl<T> Drop for Guard<T> {
702 let slice = from_raw_parts_mut(self.elems, self.n_elems);
703 ptr::drop_in_place(slice);
705 Global.dealloc(self.mem.cast(), self.layout);
710 let ptr = Self::allocate_for_slice(len);
712 let mem = ptr as *mut _ as *mut u8;
713 let layout = Layout::for_value(&*ptr);
715 // Pointer to first element
716 let elems = &mut (*ptr).data as *mut [T] as *mut T;
718 let mut guard = Guard {
719 mem: NonNull::new_unchecked(mem),
725 for (i, item) in iter.enumerate() {
726 ptr::write(elems.add(i), item);
730 // All clear. Forget the guard so it doesn't free the new ArcInner.
737 /// Specialization trait used for `From<&[T]>`.
738 trait ArcFromSlice<T> {
739 fn from_slice(slice: &[T]) -> Self;
742 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
744 default fn from_slice(v: &[T]) -> Self {
746 Self::from_iter_exact(v.iter().cloned(), v.len())
751 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
753 fn from_slice(v: &[T]) -> Self {
754 unsafe { Arc::copy_from_slice(v) }
758 #[stable(feature = "rust1", since = "1.0.0")]
759 impl<T: ?Sized> Clone for Arc<T> {
760 /// Makes a clone of the `Arc` pointer.
762 /// This creates another pointer to the same inner value, increasing the
763 /// strong reference count.
768 /// use std::sync::Arc;
770 /// let five = Arc::new(5);
772 /// let _ = Arc::clone(&five);
775 fn clone(&self) -> Arc<T> {
776 // Using a relaxed ordering is alright here, as knowledge of the
777 // original reference prevents other threads from erroneously deleting
780 // As explained in the [Boost documentation][1], Increasing the
781 // reference counter can always be done with memory_order_relaxed: New
782 // references to an object can only be formed from an existing
783 // reference, and passing an existing reference from one thread to
784 // another must already provide any required synchronization.
786 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
787 let old_size = self.inner().strong.fetch_add(1, Relaxed);
789 // However we need to guard against massive refcounts in case someone
790 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
791 // and users will use-after free. We racily saturate to `isize::MAX` on
792 // the assumption that there aren't ~2 billion threads incrementing
793 // the reference count at once. This branch will never be taken in
794 // any realistic program.
796 // We abort because such a program is incredibly degenerate, and we
797 // don't care to support it.
798 if old_size > MAX_REFCOUNT {
804 Self::from_inner(self.ptr)
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl<T: ?Sized> Deref for Arc<T> {
813 fn deref(&self) -> &T {
818 #[unstable(feature = "receiver_trait", issue = "0")]
819 impl<T: ?Sized> Receiver for Arc<T> {}
821 impl<T: Clone> Arc<T> {
822 /// Makes a mutable reference into the given `Arc`.
824 /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
825 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
826 /// ensure unique ownership. This is also referred to as clone-on-write.
828 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
830 /// [weak]: struct.Weak.html
831 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
832 /// [get_mut]: struct.Arc.html#method.get_mut
837 /// use std::sync::Arc;
839 /// let mut data = Arc::new(5);
841 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
842 /// let mut other_data = Arc::clone(&data); // Won't clone inner data
843 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
844 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
845 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
847 /// // Now `data` and `other_data` point to different values.
848 /// assert_eq!(*data, 8);
849 /// assert_eq!(*other_data, 12);
852 #[stable(feature = "arc_unique", since = "1.4.0")]
853 pub fn make_mut(this: &mut Self) -> &mut T {
854 // Note that we hold both a strong reference and a weak reference.
855 // Thus, releasing our strong reference only will not, by itself, cause
856 // the memory to be deallocated.
858 // Use Acquire to ensure that we see any writes to `weak` that happen
859 // before release writes (i.e., decrements) to `strong`. Since we hold a
860 // weak count, there's no chance the ArcInner itself could be
862 if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
863 // Another strong pointer exists; clone
864 *this = Arc::new((**this).clone());
865 } else if this.inner().weak.load(Relaxed) != 1 {
866 // Relaxed suffices in the above because this is fundamentally an
867 // optimization: we are always racing with weak pointers being
868 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
870 // We removed the last strong ref, but there are additional weak
871 // refs remaining. We'll move the contents to a new Arc, and
872 // invalidate the other weak refs.
874 // Note that it is not possible for the read of `weak` to yield
875 // usize::MAX (i.e., locked), since the weak count can only be
876 // locked by a thread with a strong reference.
878 // Materialize our own implicit weak pointer, so that it can clean
879 // up the ArcInner as needed.
880 let weak = Weak { ptr: this.ptr };
882 // mark the data itself as already deallocated
884 // there is no data race in the implicit write caused by `read`
885 // here (due to zeroing) because data is no longer accessed by
886 // other threads (due to there being no more strong refs at this
888 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
889 mem::swap(this, &mut swap);
893 // We were the sole reference of either kind; bump back up the
895 this.inner().strong.store(1, Release);
898 // As with `get_mut()`, the unsafety is ok because our reference was
899 // either unique to begin with, or became one upon cloning the contents.
901 &mut this.ptr.as_mut().data
906 impl<T: ?Sized> Arc<T> {
907 /// Returns a mutable reference to the inner value, if there are
908 /// no other `Arc` or [`Weak`][weak] pointers to the same value.
910 /// Returns [`None`][option] otherwise, because it is not safe to
911 /// mutate a shared value.
913 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
914 /// the inner value when it's shared.
916 /// [weak]: struct.Weak.html
917 /// [option]: ../../std/option/enum.Option.html
918 /// [make_mut]: struct.Arc.html#method.make_mut
919 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
924 /// use std::sync::Arc;
926 /// let mut x = Arc::new(3);
927 /// *Arc::get_mut(&mut x).unwrap() = 4;
928 /// assert_eq!(*x, 4);
930 /// let _y = Arc::clone(&x);
931 /// assert!(Arc::get_mut(&mut x).is_none());
934 #[stable(feature = "arc_unique", since = "1.4.0")]
935 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
936 if this.is_unique() {
937 // This unsafety is ok because we're guaranteed that the pointer
938 // returned is the *only* pointer that will ever be returned to T. Our
939 // reference count is guaranteed to be 1 at this point, and we required
940 // the Arc itself to be `mut`, so we're returning the only possible
941 // reference to the inner data.
943 Some(&mut this.ptr.as_mut().data)
950 /// Determine whether this is the unique reference (including weak refs) to
951 /// the underlying data.
953 /// Note that this requires locking the weak ref count.
954 fn is_unique(&mut self) -> bool {
955 // lock the weak pointer count if we appear to be the sole weak pointer
958 // The acquire label here ensures a happens-before relationship with any
959 // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
960 // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded
961 // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
962 if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
963 // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
964 // counter in `drop` -- the only access that happens when any but the last reference
966 let unique = self.inner().strong.load(Acquire) == 1;
968 // The release write here synchronizes with a read in `downgrade`,
969 // effectively preventing the above read of `strong` from happening
971 self.inner().weak.store(1, Release); // release the lock
979 #[stable(feature = "rust1", since = "1.0.0")]
980 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
983 /// This will decrement the strong reference count. If the strong reference
984 /// count reaches zero then the only other references (if any) are
985 /// [`Weak`], so we `drop` the inner value.
990 /// use std::sync::Arc;
994 /// impl Drop for Foo {
995 /// fn drop(&mut self) {
996 /// println!("dropped!");
1000 /// let foo = Arc::new(Foo);
1001 /// let foo2 = Arc::clone(&foo);
1003 /// drop(foo); // Doesn't print anything
1004 /// drop(foo2); // Prints "dropped!"
1007 /// [`Weak`]: ../../std/sync/struct.Weak.html
1009 fn drop(&mut self) {
1010 // Because `fetch_sub` is already atomic, we do not need to synchronize
1011 // with other threads unless we are going to delete the object. This
1012 // same logic applies to the below `fetch_sub` to the `weak` count.
1013 if self.inner().strong.fetch_sub(1, Release) != 1 {
1017 // This fence is needed to prevent reordering of use of the data and
1018 // deletion of the data. Because it is marked `Release`, the decreasing
1019 // of the reference count synchronizes with this `Acquire` fence. This
1020 // means that use of the data happens before decreasing the reference
1021 // count, which happens before this fence, which happens before the
1022 // deletion of the data.
1024 // As explained in the [Boost documentation][1],
1026 // > It is important to enforce any possible access to the object in one
1027 // > thread (through an existing reference) to *happen before* deleting
1028 // > the object in a different thread. This is achieved by a "release"
1029 // > operation after dropping a reference (any access to the object
1030 // > through this reference must obviously happened before), and an
1031 // > "acquire" operation before deleting the object.
1033 // In particular, while the contents of an Arc are usually immutable, it's
1034 // possible to have interior writes to something like a Mutex<T>. Since a
1035 // Mutex is not acquired when it is deleted, we can't rely on its
1036 // synchronization logic to make writes in thread A visible to a destructor
1037 // running in thread B.
1039 // Also note that the Acquire fence here could probably be replaced with an
1040 // Acquire load, which could improve performance in highly-contended
1041 // situations. See [2].
1043 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1044 // [2]: (https://github.com/rust-lang/rust/pull/41714)
1045 atomic::fence(Acquire);
1053 impl Arc<dyn Any + Send + Sync> {
1055 #[stable(feature = "rc_downcast", since = "1.29.0")]
1056 /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1061 /// use std::any::Any;
1062 /// use std::sync::Arc;
1064 /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1065 /// if let Ok(string) = value.downcast::<String>() {
1066 /// println!("String ({}): {}", string.len(), string);
1071 /// let my_string = "Hello World".to_string();
1072 /// print_if_string(Arc::new(my_string));
1073 /// print_if_string(Arc::new(0i8));
1076 pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1078 T: Any + Send + Sync + 'static,
1080 if (*self).is::<T>() {
1081 let ptr = self.ptr.cast::<ArcInner<T>>();
1083 Ok(Arc::from_inner(ptr))
1091 /// Constructs a new `Weak<T>`, without allocating any memory.
1092 /// Calling [`upgrade`] on the return value always gives [`None`].
1094 /// [`upgrade`]: struct.Weak.html#method.upgrade
1095 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1100 /// use std::sync::Weak;
1102 /// let empty: Weak<i64> = Weak::new();
1103 /// assert!(empty.upgrade().is_none());
1105 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1106 pub fn new() -> Weak<T> {
1108 ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0"),
1112 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1114 /// It is up to the caller to ensure that the object is still alive when accessing it through
1117 /// The pointer may be [`null`] or be dangling in case the object has already been destroyed.
1122 /// #![feature(weak_into_raw)]
1124 /// use std::sync::Arc;
1127 /// let strong = Arc::new("hello".to_owned());
1128 /// let weak = Arc::downgrade(&strong);
1129 /// // Both point to the same object
1130 /// assert!(ptr::eq(&*strong, weak.as_raw()));
1131 /// // The strong here keeps it alive, so we can still access the object.
1132 /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1135 /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1136 /// // undefined behaviour.
1137 /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1140 /// [`null`]: ../../std/ptr/fn.null.html
1141 #[unstable(feature = "weak_into_raw", issue = "60728")]
1142 pub fn as_raw(&self) -> *const T {
1143 match self.inner() {
1144 None => ptr::null(),
1146 let offset = data_offset_sized::<T>();
1147 let ptr = inner as *const ArcInner<T>;
1148 // Note: while the pointer we create may already point to dropped value, the
1149 // allocation still lives (it must hold the weak point as long as we are alive).
1150 // Therefore, the offset is OK to do, it won't get out of the allocation.
1151 let ptr = unsafe { (ptr as *const u8).offset(offset) };
1157 /// Consumes the `Weak<T>` and turns it into a raw pointer.
1159 /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1160 /// can be turned back into the `Weak<T>` with [`from_raw`].
1162 /// The same restrictions of accessing the target of the pointer as with
1163 /// [`as_raw`] apply.
1168 /// #![feature(weak_into_raw)]
1170 /// use std::sync::{Arc, Weak};
1172 /// let strong = Arc::new("hello".to_owned());
1173 /// let weak = Arc::downgrade(&strong);
1174 /// let raw = weak.into_raw();
1176 /// assert_eq!(1, Arc::weak_count(&strong));
1177 /// assert_eq!("hello", unsafe { &*raw });
1179 /// drop(unsafe { Weak::from_raw(raw) });
1180 /// assert_eq!(0, Arc::weak_count(&strong));
1183 /// [`from_raw`]: struct.Weak.html#method.from_raw
1184 /// [`as_raw`]: struct.Weak.html#method.as_raw
1185 #[unstable(feature = "weak_into_raw", issue = "60728")]
1186 pub fn into_raw(self) -> *const T {
1187 let result = self.as_raw();
1192 /// Converts a raw pointer previously created by [`into_raw`] back into
1195 /// This can be used to safely get a strong reference (by calling [`upgrade`]
1196 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1198 /// It takes ownership of one weak count. In case a [`null`] is passed, a dangling [`Weak`] is
1203 /// The pointer must represent one valid weak count. In other words, it must point to `T` which
1204 /// is or *was* managed by an [`Arc`] and the weak count of that [`Arc`] must not have reached
1205 /// 0. It is allowed for the strong count to be 0.
1210 /// #![feature(weak_into_raw)]
1212 /// use std::sync::{Arc, Weak};
1214 /// let strong = Arc::new("hello".to_owned());
1216 /// let raw_1 = Arc::downgrade(&strong).into_raw();
1217 /// let raw_2 = Arc::downgrade(&strong).into_raw();
1219 /// assert_eq!(2, Arc::weak_count(&strong));
1221 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1222 /// assert_eq!(1, Arc::weak_count(&strong));
1226 /// // Decrement the last weak count.
1227 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1230 /// [`null`]: ../../std/ptr/fn.null.html
1231 /// [`into_raw`]: struct.Weak.html#method.into_raw
1232 /// [`upgrade`]: struct.Weak.html#method.upgrade
1233 /// [`Weak`]: struct.Weak.html
1234 /// [`Arc`]: struct.Arc.html
1235 #[unstable(feature = "weak_into_raw", issue = "60728")]
1236 pub unsafe fn from_raw(ptr: *const T) -> Self {
1240 // See Arc::from_raw for details
1241 let offset = data_offset(ptr);
1242 let fake_ptr = ptr as *mut ArcInner<T>;
1243 let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1245 ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw"),
1251 impl<T: ?Sized> Weak<T> {
1252 /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
1253 /// the lifetime of the value if successful.
1255 /// Returns [`None`] if the value has since been dropped.
1257 /// [`Arc`]: struct.Arc.html
1258 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1263 /// use std::sync::Arc;
1265 /// let five = Arc::new(5);
1267 /// let weak_five = Arc::downgrade(&five);
1269 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1270 /// assert!(strong_five.is_some());
1272 /// // Destroy all strong pointers.
1273 /// drop(strong_five);
1276 /// assert!(weak_five.upgrade().is_none());
1278 #[stable(feature = "arc_weak", since = "1.4.0")]
1279 pub fn upgrade(&self) -> Option<Arc<T>> {
1280 // We use a CAS loop to increment the strong count instead of a
1281 // fetch_add because once the count hits 0 it must never be above 0.
1282 let inner = self.inner()?;
1284 // Relaxed load because any write of 0 that we can observe
1285 // leaves the field in a permanently zero state (so a
1286 // "stale" read of 0 is fine), and any other value is
1287 // confirmed via the CAS below.
1288 let mut n = inner.strong.load(Relaxed);
1295 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1296 if n > MAX_REFCOUNT {
1302 // Relaxed is valid for the same reason it is on Arc's Clone impl
1303 match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
1304 Ok(_) => return Some(Arc::from_inner(self.ptr)), // null checked above
1305 Err(old) => n = old,
1310 /// Gets the number of strong (`Arc`) pointers pointing to this value.
1312 /// If `self` was created using [`Weak::new`], this will return 0.
1314 /// [`Weak::new`]: #method.new
1315 #[unstable(feature = "weak_counts", issue = "57977")]
1316 pub fn strong_count(&self) -> usize {
1317 if let Some(inner) = self.inner() {
1318 inner.strong.load(SeqCst)
1324 /// Gets an approximation of the number of `Weak` pointers pointing to this
1327 /// If `self` was created using [`Weak::new`], this will return 0. If not,
1328 /// the returned value is at least 1, since `self` still points to the
1333 /// Due to implementation details, the returned value can be off by 1 in
1334 /// either direction when other threads are manipulating any `Arc`s or
1335 /// `Weak`s pointing to the same value.
1337 /// [`Weak::new`]: #method.new
1338 #[unstable(feature = "weak_counts", issue = "57977")]
1339 pub fn weak_count(&self) -> Option<usize> {
1340 // Due to the implicit weak pointer added when any strong pointers are
1341 // around, we cannot implement `weak_count` correctly since it
1342 // necessarily requires accessing the strong count and weak count in an
1343 // unsynchronized fashion. So this version is a bit racy.
1344 self.inner().map(|inner| {
1345 let strong = inner.strong.load(SeqCst);
1346 let weak = inner.weak.load(SeqCst);
1348 // If the last `Arc` has *just* been dropped, it might not yet
1349 // have removed the implicit weak count, so the value we get
1350 // here might be 1 too high.
1353 // As long as there's still at least 1 `Arc` around, subtract
1354 // the implicit weak pointer.
1355 // Note that the last `Arc` might get dropped between the 2
1356 // loads we do above, removing the implicit weak pointer. This
1357 // means that the value might be 1 too low here. In order to not
1358 // return 0 here (which would happen if we're the only weak
1359 // pointer), we guard against that specifically.
1360 cmp::max(1, weak - 1)
1365 /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
1366 /// (i.e., when this `Weak` was created by `Weak::new`).
1368 fn inner(&self) -> Option<&ArcInner<T>> {
1369 if is_dangling(self.ptr) {
1372 Some(unsafe { self.ptr.as_ref() })
1376 /// Returns `true` if the two `Weak`s point to the same value (not just values
1377 /// that compare as equal).
1381 /// Since this compares pointers it means that `Weak::new()` will equal each
1382 /// other, even though they don't point to any value.
1388 /// #![feature(weak_ptr_eq)]
1389 /// use std::sync::Arc;
1391 /// let first_rc = Arc::new(5);
1392 /// let first = Arc::downgrade(&first_rc);
1393 /// let second = Arc::downgrade(&first_rc);
1395 /// assert!(first.ptr_eq(&second));
1397 /// let third_rc = Arc::new(5);
1398 /// let third = Arc::downgrade(&third_rc);
1400 /// assert!(!first.ptr_eq(&third));
1403 /// Comparing `Weak::new`.
1406 /// #![feature(weak_ptr_eq)]
1407 /// use std::sync::{Arc, Weak};
1409 /// let first = Weak::new();
1410 /// let second = Weak::new();
1411 /// assert!(first.ptr_eq(&second));
1413 /// let third_rc = Arc::new(());
1414 /// let third = Arc::downgrade(&third_rc);
1415 /// assert!(!first.ptr_eq(&third));
1418 #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1419 pub fn ptr_eq(&self, other: &Self) -> bool {
1420 self.ptr.as_ptr() == other.ptr.as_ptr()
1424 #[stable(feature = "arc_weak", since = "1.4.0")]
1425 impl<T: ?Sized> Clone for Weak<T> {
1426 /// Makes a clone of the `Weak` pointer that points to the same value.
1431 /// use std::sync::{Arc, Weak};
1433 /// let weak_five = Arc::downgrade(&Arc::new(5));
1435 /// let _ = Weak::clone(&weak_five);
1438 fn clone(&self) -> Weak<T> {
1439 let inner = if let Some(inner) = self.inner() {
1442 return Weak { ptr: self.ptr };
1444 // See comments in Arc::clone() for why this is relaxed. This can use a
1445 // fetch_add (ignoring the lock) because the weak count is only locked
1446 // where are *no other* weak pointers in existence. (So we can't be
1447 // running this code in that case).
1448 let old_size = inner.weak.fetch_add(1, Relaxed);
1450 // See comments in Arc::clone() for why we do this (for mem::forget).
1451 if old_size > MAX_REFCOUNT {
1457 return Weak { ptr: self.ptr };
1461 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1462 impl<T> Default for Weak<T> {
1463 /// Constructs a new `Weak<T>`, without allocating memory.
1464 /// Calling [`upgrade`] on the return value always
1467 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1468 /// [`upgrade`]: ../../std/sync/struct.Weak.html#method.upgrade
1473 /// use std::sync::Weak;
1475 /// let empty: Weak<i64> = Default::default();
1476 /// assert!(empty.upgrade().is_none());
1478 fn default() -> Weak<T> {
1483 #[stable(feature = "arc_weak", since = "1.4.0")]
1484 impl<T: ?Sized> Drop for Weak<T> {
1485 /// Drops the `Weak` pointer.
1490 /// use std::sync::{Arc, Weak};
1494 /// impl Drop for Foo {
1495 /// fn drop(&mut self) {
1496 /// println!("dropped!");
1500 /// let foo = Arc::new(Foo);
1501 /// let weak_foo = Arc::downgrade(&foo);
1502 /// let other_weak_foo = Weak::clone(&weak_foo);
1504 /// drop(weak_foo); // Doesn't print anything
1505 /// drop(foo); // Prints "dropped!"
1507 /// assert!(other_weak_foo.upgrade().is_none());
1509 fn drop(&mut self) {
1510 // If we find out that we were the last weak pointer, then its time to
1511 // deallocate the data entirely. See the discussion in Arc::drop() about
1512 // the memory orderings
1514 // It's not necessary to check for the locked state here, because the
1515 // weak count can only be locked if there was precisely one weak ref,
1516 // meaning that drop could only subsequently run ON that remaining weak
1517 // ref, which can only happen after the lock is released.
1518 let inner = if let Some(inner) = self.inner() {
1524 if inner.weak.fetch_sub(1, Release) == 1 {
1525 atomic::fence(Acquire);
1527 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 trait ArcEqIdent<T: ?Sized + PartialEq> {
1535 fn eq(&self, other: &Arc<T>) -> bool;
1536 fn ne(&self, other: &Arc<T>) -> bool;
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1542 default fn eq(&self, other: &Arc<T>) -> bool {
1546 default fn ne(&self, other: &Arc<T>) -> bool {
1551 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1552 /// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
1553 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1554 /// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
1555 /// the same value, than two `&T`s.
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<T: ?Sized + Eq> ArcEqIdent<T> for Arc<T> {
1559 fn eq(&self, other: &Arc<T>) -> bool {
1560 Arc::ptr_eq(self, other) || **self == **other
1564 fn ne(&self, other: &Arc<T>) -> bool {
1565 !Arc::ptr_eq(self, other) && **self != **other
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1571 /// Equality for two `Arc`s.
1573 /// Two `Arc`s are equal if their inner values are equal.
1575 /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1581 /// use std::sync::Arc;
1583 /// let five = Arc::new(5);
1585 /// assert!(five == Arc::new(5));
1588 fn eq(&self, other: &Arc<T>) -> bool {
1589 ArcEqIdent::eq(self, other)
1592 /// Inequality for two `Arc`s.
1594 /// Two `Arc`s are unequal if their inner values are unequal.
1596 /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1602 /// use std::sync::Arc;
1604 /// let five = Arc::new(5);
1606 /// assert!(five != Arc::new(6));
1609 fn ne(&self, other: &Arc<T>) -> bool {
1610 ArcEqIdent::ne(self, other)
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1616 /// Partial comparison for two `Arc`s.
1618 /// The two are compared by calling `partial_cmp()` on their inner values.
1623 /// use std::sync::Arc;
1624 /// use std::cmp::Ordering;
1626 /// let five = Arc::new(5);
1628 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1630 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1631 (**self).partial_cmp(&**other)
1634 /// Less-than comparison for two `Arc`s.
1636 /// The two are compared by calling `<` on their inner values.
1641 /// use std::sync::Arc;
1643 /// let five = Arc::new(5);
1645 /// assert!(five < Arc::new(6));
1647 fn lt(&self, other: &Arc<T>) -> bool {
1648 *(*self) < *(*other)
1651 /// 'Less than or equal to' comparison for two `Arc`s.
1653 /// The two are compared by calling `<=` on their inner values.
1658 /// use std::sync::Arc;
1660 /// let five = Arc::new(5);
1662 /// assert!(five <= Arc::new(5));
1664 fn le(&self, other: &Arc<T>) -> bool {
1665 *(*self) <= *(*other)
1668 /// Greater-than comparison for two `Arc`s.
1670 /// The two are compared by calling `>` on their inner values.
1675 /// use std::sync::Arc;
1677 /// let five = Arc::new(5);
1679 /// assert!(five > Arc::new(4));
1681 fn gt(&self, other: &Arc<T>) -> bool {
1682 *(*self) > *(*other)
1685 /// 'Greater than or equal to' comparison for two `Arc`s.
1687 /// The two are compared by calling `>=` on their inner values.
1692 /// use std::sync::Arc;
1694 /// let five = Arc::new(5);
1696 /// assert!(five >= Arc::new(5));
1698 fn ge(&self, other: &Arc<T>) -> bool {
1699 *(*self) >= *(*other)
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<T: ?Sized + Ord> Ord for Arc<T> {
1704 /// Comparison for two `Arc`s.
1706 /// The two are compared by calling `cmp()` on their inner values.
1711 /// use std::sync::Arc;
1712 /// use std::cmp::Ordering;
1714 /// let five = Arc::new(5);
1716 /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1718 fn cmp(&self, other: &Arc<T>) -> Ordering {
1719 (**self).cmp(&**other)
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1728 fmt::Display::fmt(&**self, f)
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1735 fmt::Debug::fmt(&**self, f)
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1742 fmt::Pointer::fmt(&(&**self as *const T), f)
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<T: Default> Default for Arc<T> {
1748 /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1753 /// use std::sync::Arc;
1755 /// let x: Arc<i32> = Default::default();
1756 /// assert_eq!(*x, 0);
1758 fn default() -> Arc<T> {
1759 Arc::new(Default::default())
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<T: ?Sized + Hash> Hash for Arc<T> {
1765 fn hash<H: Hasher>(&self, state: &mut H) {
1766 (**self).hash(state)
1770 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1771 impl<T> From<T> for Arc<T> {
1772 fn from(t: T) -> Self {
1777 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1778 impl<T: Clone> From<&[T]> for Arc<[T]> {
1780 fn from(v: &[T]) -> Arc<[T]> {
1781 <Self as ArcFromSlice<T>>::from_slice(v)
1785 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1786 impl From<&str> for Arc<str> {
1788 fn from(v: &str) -> Arc<str> {
1789 let arc = Arc::<[u8]>::from(v.as_bytes());
1790 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
1794 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1795 impl From<String> for Arc<str> {
1797 fn from(v: String) -> Arc<str> {
1802 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1803 impl<T: ?Sized> From<Box<T>> for Arc<T> {
1805 fn from(v: Box<T>) -> Arc<T> {
1810 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1811 impl<T> From<Vec<T>> for Arc<[T]> {
1813 fn from(mut v: Vec<T>) -> Arc<[T]> {
1815 let arc = Arc::copy_from_slice(&v);
1817 // Allow the Vec to free its memory, but not destroy its contents
1825 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1826 impl<T> iter::FromIterator<T> for Arc<[T]> {
1827 /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
1829 /// # Performance characteristics
1831 /// ## The general case
1833 /// In the general case, collecting into `Arc<[T]>` is done by first
1834 /// collecting into a `Vec<T>`. That is, when writing the following:
1837 /// # use std::sync::Arc;
1838 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1839 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1842 /// this behaves as if we wrote:
1845 /// # use std::sync::Arc;
1846 /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1847 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1848 /// .into(); // A second allocation for `Arc<[T]>` happens here.
1849 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1852 /// This will allocate as many times as needed for constructing the `Vec<T>`
1853 /// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
1855 /// ## Iterators of known length
1857 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1858 /// a single allocation will be made for the `Arc<[T]>`. For example:
1861 /// # use std::sync::Arc;
1862 /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1863 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1865 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1866 ArcFromIter::from_iter(iter.into_iter())
1870 /// Specialization trait used for collecting into `Arc<[T]>`.
1871 trait ArcFromIter<T, I> {
1872 fn from_iter(iter: I) -> Self;
1875 impl<T, I: Iterator<Item = T>> ArcFromIter<T, I> for Arc<[T]> {
1876 default fn from_iter(iter: I) -> Self {
1877 iter.collect::<Vec<T>>().into()
1881 impl<T, I: iter::TrustedLen<Item = T>> ArcFromIter<T, I> for Arc<[T]> {
1882 default fn from_iter(iter: I) -> Self {
1883 // This is the case for a `TrustedLen` iterator.
1884 let (low, high) = iter.size_hint();
1885 if let Some(high) = high {
1888 "TrustedLen iterator's size hint is not exact: {:?}",
1893 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1894 Arc::from_iter_exact(iter, low)
1897 // Fall back to normal implementation.
1898 iter.collect::<Vec<T>>().into()
1903 impl<'a, T: 'a + Clone> ArcFromIter<&'a T, slice::Iter<'a, T>> for Arc<[T]> {
1904 fn from_iter(iter: slice::Iter<'a, T>) -> Self {
1905 // Delegate to `impl<T: Clone> From<&[T]> for Arc<[T]>`.
1907 // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1908 // which is even more performant.
1910 // In the fall-back case we have `T: Clone`. This is still better
1911 // than the `TrustedLen` implementation as slices have a known length
1912 // and so we get to avoid calling `size_hint` and avoid the branching.
1913 iter.as_slice().into()
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1919 fn borrow(&self) -> &T {
1924 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1925 impl<T: ?Sized> AsRef<T> for Arc<T> {
1926 fn as_ref(&self) -> &T {
1931 #[stable(feature = "pin", since = "1.33.0")]
1932 impl<T: ?Sized> Unpin for Arc<T> { }
1934 /// Computes the offset of the data field within `ArcInner`.
1935 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
1936 // Align the unsized value to the end of the `ArcInner`.
1937 // Because it is `?Sized`, it will always be the last field in memory.
1938 data_offset_align(align_of_val(&*ptr))
1941 /// Computes the offset of the data field within `ArcInner`.
1943 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
1944 fn data_offset_sized<T>() -> isize {
1945 data_offset_align(align_of::<T>())
1949 fn data_offset_align(align: usize) -> isize {
1950 let layout = Layout::new::<ArcInner<()>>();
1951 (layout.size() + layout.padding_needed_for(align)) as isize