1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![stable(feature = "rust1", since = "1.0.0")]
13 //! Thread-safe reference-counting pointers.
15 //! See the [`Arc<T>`][arc] documentation for more details.
17 //! [arc]: struct.Arc.html
20 use core::sync::atomic;
21 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
24 use core::cmp::Ordering;
25 use core::intrinsics::abort;
26 use core::mem::{self, align_of_val, size_of_val};
28 use core::ops::CoerceUnsized;
30 use core::ptr::{self, NonNull};
31 use core::marker::{Unpin, Unsize, PhantomData};
32 use core::hash::{Hash, Hasher};
33 use core::{isize, usize};
34 use core::convert::From;
36 use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
42 /// A soft limit on the amount of references that may be made to an `Arc`.
44 /// Going above this limit will abort your program (although not
45 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
46 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
48 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
49 /// Reference Counted'.
51 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
52 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
53 /// a new `Arc` instance, which points to the same value on the heap as the
54 /// source `Arc`, while increasing a reference count. When the last `Arc`
55 /// pointer to a given value is destroyed, the pointed-to value is also
58 /// Shared references in Rust disallow mutation by default, and `Arc` is no
59 /// exception: you cannot generally obtain a mutable reference to something
60 /// inside an `Arc`. If you need to mutate through an `Arc`, use
61 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
66 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
67 /// counting. This means that it is thread-safe. The disadvantage is that
68 /// atomic operations are more expensive than ordinary memory accesses. If you
69 /// are not sharing reference-counted values between threads, consider using
70 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
71 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
72 /// However, a library might choose `Arc<T>` in order to give library consumers
75 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
76 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
77 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
78 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
79 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
80 /// data, but it doesn't add thread safety to its data. Consider
81 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
82 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
83 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
84 /// non-atomic operations.
86 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
87 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
89 /// ## Breaking cycles with `Weak`
91 /// The [`downgrade`][downgrade] method can be used to create a non-owning
92 /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d
93 /// to an `Arc`, but this will return [`None`] if the value has already been
96 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
97 /// [`Weak`][weak] is used to break cycles. For example, a tree could have
98 /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak]
99 /// pointers from children back to their parents.
101 /// # Cloning references
103 /// Creating a new reference from an existing reference counted pointer is done using the
104 /// `Clone` trait implemented for [`Arc<T>`][arc] and [`Weak<T>`][weak].
107 /// use std::sync::Arc;
108 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
109 /// // The two syntaxes below are equivalent.
110 /// let a = foo.clone();
111 /// let b = Arc::clone(&foo);
112 /// // a, b, and foo are all Arcs that point to the same memory location
115 /// The [`Arc::clone(&from)`] syntax is the most idiomatic because it conveys more explicitly
116 /// the meaning of the code. In the example above, this syntax makes it easier to see that
117 /// this code is creating a new reference rather than copying the whole content of foo.
119 /// ## `Deref` behavior
121 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
122 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
123 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are [associated
124 /// functions][assoc], called using function-like syntax:
127 /// use std::sync::Arc;
128 /// let my_arc = Arc::new(());
130 /// Arc::downgrade(&my_arc);
133 /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have
134 /// already been destroyed.
136 /// [arc]: struct.Arc.html
137 /// [weak]: struct.Weak.html
138 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
139 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
140 /// [mutex]: ../../std/sync/struct.Mutex.html
141 /// [rwlock]: ../../std/sync/struct.RwLock.html
142 /// [atomic]: ../../std/sync/atomic/index.html
143 /// [`Send`]: ../../std/marker/trait.Send.html
144 /// [`Sync`]: ../../std/marker/trait.Sync.html
145 /// [deref]: ../../std/ops/trait.Deref.html
146 /// [downgrade]: struct.Arc.html#method.downgrade
147 /// [upgrade]: struct.Weak.html#method.upgrade
148 /// [`None`]: ../../std/option/enum.Option.html#variant.None
149 /// [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
150 /// [`RefCell<T>`]: ../../std/cell/struct.RefCell.html
151 /// [`std::sync`]: ../../std/sync/index.html
152 /// [`Arc::clone(&from)`]: #method.clone
156 /// Sharing some immutable data between threads:
158 // Note that we **do not** run these tests here. The windows builders get super
159 // unhappy if a thread outlives the main thread and then exits at the same time
160 // (something deadlocks) so we just avoid this entirely by not running these
163 /// use std::sync::Arc;
166 /// let five = Arc::new(5);
169 /// let five = Arc::clone(&five);
171 /// thread::spawn(move || {
172 /// println!("{:?}", five);
177 /// Sharing a mutable [`AtomicUsize`]:
179 /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html
182 /// use std::sync::Arc;
183 /// use std::sync::atomic::{AtomicUsize, Ordering};
186 /// let val = Arc::new(AtomicUsize::new(5));
189 /// let val = Arc::clone(&val);
191 /// thread::spawn(move || {
192 /// let v = val.fetch_add(1, Ordering::SeqCst);
193 /// println!("{:?}", v);
198 /// See the [`rc` documentation][rc_examples] for more examples of reference
199 /// counting in general.
201 /// [rc_examples]: ../../std/rc/index.html#examples
202 #[cfg_attr(all(not(stage0), not(test)), lang = "arc")]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub struct Arc<T: ?Sized> {
205 ptr: NonNull<ArcInner<T>>,
206 phantom: PhantomData<T>,
209 #[stable(feature = "rust1", since = "1.0.0")]
210 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
211 #[stable(feature = "rust1", since = "1.0.0")]
212 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
214 #[unstable(feature = "coerce_unsized", issue = "27732")]
215 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
217 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
218 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
219 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
221 /// Since a `Weak` reference does not count towards ownership, it will not
222 /// prevent the inner value from being dropped, and `Weak` itself makes no
223 /// guarantees about the value still being present and may return [`None`]
224 /// when [`upgrade`]d.
226 /// A `Weak` pointer is useful for keeping a temporary reference to the value
227 /// within [`Arc`] without extending its lifetime. It is also used to prevent
228 /// circular references between [`Arc`] pointers, since mutual owning references
229 /// would never allow either [`Arc`] to be dropped. For example, a tree could
230 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
231 /// pointers from children back to their parents.
233 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
235 /// [`Arc`]: struct.Arc.html
236 /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade
237 /// [`upgrade`]: struct.Weak.html#method.upgrade
238 /// [`Option`]: ../../std/option/enum.Option.html
239 /// [`None`]: ../../std/option/enum.Option.html#variant.None
240 #[stable(feature = "arc_weak", since = "1.4.0")]
241 pub struct Weak<T: ?Sized> {
242 // This is a `NonNull` to allow optimizing the size of this type in enums,
243 // but it is not necessarily a valid pointer.
244 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
245 // to allocate space on the heap. That's not a value a real pointer
246 // will ever have because RcBox has alignment at least 2.
247 ptr: NonNull<ArcInner<T>>,
250 #[stable(feature = "arc_weak", since = "1.4.0")]
251 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
252 #[stable(feature = "arc_weak", since = "1.4.0")]
253 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
255 #[unstable(feature = "coerce_unsized", issue = "27732")]
256 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
258 #[stable(feature = "arc_weak", since = "1.4.0")]
259 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
265 struct ArcInner<T: ?Sized> {
266 strong: atomic::AtomicUsize,
268 // the value usize::MAX acts as a sentinel for temporarily "locking" the
269 // ability to upgrade weak pointers or downgrade strong ones; this is used
270 // to avoid races in `make_mut` and `get_mut`.
271 weak: atomic::AtomicUsize,
276 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
277 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
280 /// Constructs a new `Arc<T>`.
285 /// use std::sync::Arc;
287 /// let five = Arc::new(5);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn new(data: T) -> Arc<T> {
292 // Start the weak pointer count as 1 which is the weak pointer that's
293 // held by all the strong pointers (kinda), see std/rc.rs for more info
294 let x: Box<_> = box ArcInner {
295 strong: atomic::AtomicUsize::new(1),
296 weak: atomic::AtomicUsize::new(1),
299 Arc { ptr: Box::into_raw_non_null(x), phantom: PhantomData }
302 #[unstable(feature = "pin", issue = "49150")]
303 pub fn pinned(data: T) -> Pin<Arc<T>> {
304 unsafe { Pin::new_unchecked(Arc::new(data)) }
307 /// Returns the contained value, if the `Arc` has exactly one strong reference.
309 /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was
312 /// This will succeed even if there are outstanding weak references.
314 /// [result]: ../../std/result/enum.Result.html
319 /// use std::sync::Arc;
321 /// let x = Arc::new(3);
322 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
324 /// let x = Arc::new(4);
325 /// let _y = Arc::clone(&x);
326 /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
329 #[stable(feature = "arc_unique", since = "1.4.0")]
330 pub fn try_unwrap(this: Self) -> Result<T, Self> {
331 // See `drop` for why all these atomics are like this
332 if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() {
336 atomic::fence(Acquire);
339 let elem = ptr::read(&this.ptr.as_ref().data);
341 // Make a weak pointer to clean up the implicit strong-weak reference
342 let _weak = Weak { ptr: this.ptr };
350 impl<T: ?Sized> Arc<T> {
351 /// Consumes the `Arc`, returning the wrapped pointer.
353 /// To avoid a memory leak the pointer must be converted back to an `Arc` using
354 /// [`Arc::from_raw`][from_raw].
356 /// [from_raw]: struct.Arc.html#method.from_raw
361 /// use std::sync::Arc;
363 /// let x = Arc::new(10);
364 /// let x_ptr = Arc::into_raw(x);
365 /// assert_eq!(unsafe { *x_ptr }, 10);
367 #[stable(feature = "rc_raw", since = "1.17.0")]
368 pub fn into_raw(this: Self) -> *const T {
369 let ptr: *const T = &*this;
374 /// Constructs an `Arc` from a raw pointer.
376 /// The raw pointer must have been previously returned by a call to a
377 /// [`Arc::into_raw`][into_raw].
379 /// This function is unsafe because improper use may lead to memory problems. For example, a
380 /// double-free may occur if the function is called twice on the same raw pointer.
382 /// [into_raw]: struct.Arc.html#method.into_raw
387 /// use std::sync::Arc;
389 /// let x = Arc::new(10);
390 /// let x_ptr = Arc::into_raw(x);
393 /// // Convert back to an `Arc` to prevent leak.
394 /// let x = Arc::from_raw(x_ptr);
395 /// assert_eq!(*x, 10);
397 /// // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe.
400 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
402 #[stable(feature = "rc_raw", since = "1.17.0")]
403 pub unsafe fn from_raw(ptr: *const T) -> Self {
404 // Align the unsized value to the end of the ArcInner.
405 // Because it is ?Sized, it will always be the last field in memory.
406 let align = align_of_val(&*ptr);
407 let layout = Layout::new::<ArcInner<()>>();
408 let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
410 // Reverse the offset to find the original ArcInner.
411 let fake_ptr = ptr as *mut ArcInner<T>;
412 let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
415 ptr: NonNull::new_unchecked(arc_ptr),
416 phantom: PhantomData,
420 /// Creates a new [`Weak`][weak] pointer to this value.
422 /// [weak]: struct.Weak.html
427 /// use std::sync::Arc;
429 /// let five = Arc::new(5);
431 /// let weak_five = Arc::downgrade(&five);
433 #[stable(feature = "arc_weak", since = "1.4.0")]
434 pub fn downgrade(this: &Self) -> Weak<T> {
435 // This Relaxed is OK because we're checking the value in the CAS
437 let mut cur = this.inner().weak.load(Relaxed);
440 // check if the weak counter is currently "locked"; if so, spin.
441 if cur == usize::MAX {
442 cur = this.inner().weak.load(Relaxed);
446 // NOTE: this code currently ignores the possibility of overflow
447 // into usize::MAX; in general both Rc and Arc need to be adjusted
448 // to deal with overflow.
450 // Unlike with Clone(), we need this to be an Acquire read to
451 // synchronize with the write coming from `is_unique`, so that the
452 // events prior to that write happen before this read.
453 match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
455 // Make sure we do not create a dangling Weak
456 debug_assert!(!is_dangling(this.ptr));
457 return Weak { ptr: this.ptr };
459 Err(old) => cur = old,
464 /// Gets the number of [`Weak`][weak] pointers to this value.
466 /// [weak]: struct.Weak.html
470 /// This method by itself is safe, but using it correctly requires extra care.
471 /// Another thread can change the weak count at any time,
472 /// including potentially between calling this method and acting on the result.
477 /// use std::sync::Arc;
479 /// let five = Arc::new(5);
480 /// let _weak_five = Arc::downgrade(&five);
482 /// // This assertion is deterministic because we haven't shared
483 /// // the `Arc` or `Weak` between threads.
484 /// assert_eq!(1, Arc::weak_count(&five));
487 #[stable(feature = "arc_counts", since = "1.15.0")]
488 pub fn weak_count(this: &Self) -> usize {
489 let cnt = this.inner().weak.load(SeqCst);
490 // If the weak count is currently locked, the value of the
491 // count was 0 just before taking the lock.
492 if cnt == usize::MAX { 0 } else { cnt - 1 }
495 /// Gets the number of strong (`Arc`) pointers to this value.
499 /// This method by itself is safe, but using it correctly requires extra care.
500 /// Another thread can change the strong count at any time,
501 /// including potentially between calling this method and acting on the result.
506 /// use std::sync::Arc;
508 /// let five = Arc::new(5);
509 /// let _also_five = Arc::clone(&five);
511 /// // This assertion is deterministic because we haven't shared
512 /// // the `Arc` between threads.
513 /// assert_eq!(2, Arc::strong_count(&five));
516 #[stable(feature = "arc_counts", since = "1.15.0")]
517 pub fn strong_count(this: &Self) -> usize {
518 this.inner().strong.load(SeqCst)
522 fn inner(&self) -> &ArcInner<T> {
523 // This unsafety is ok because while this arc is alive we're guaranteed
524 // that the inner pointer is valid. Furthermore, we know that the
525 // `ArcInner` structure itself is `Sync` because the inner data is
526 // `Sync` as well, so we're ok loaning out an immutable pointer to these
528 unsafe { self.ptr.as_ref() }
531 // Non-inlined part of `drop`.
533 unsafe fn drop_slow(&mut self) {
534 // Destroy the data at this time, even though we may not free the box
535 // allocation itself (there may still be weak pointers lying around).
536 ptr::drop_in_place(&mut self.ptr.as_mut().data);
538 if self.inner().weak.fetch_sub(1, Release) == 1 {
539 atomic::fence(Acquire);
540 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
545 #[stable(feature = "ptr_eq", since = "1.17.0")]
546 /// Returns true if the two `Arc`s point to the same value (not
547 /// just values that compare as equal).
552 /// use std::sync::Arc;
554 /// let five = Arc::new(5);
555 /// let same_five = Arc::clone(&five);
556 /// let other_five = Arc::new(5);
558 /// assert!(Arc::ptr_eq(&five, &same_five));
559 /// assert!(!Arc::ptr_eq(&five, &other_five));
561 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
562 this.ptr.as_ptr() == other.ptr.as_ptr()
566 impl<T: ?Sized> Arc<T> {
567 // Allocates an `ArcInner<T>` with sufficient space for an unsized value
568 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
569 // Create a fake ArcInner to find allocation size and alignment
570 let fake_ptr = ptr as *mut ArcInner<T>;
572 let layout = Layout::for_value(&*fake_ptr);
574 let mem = Global.alloc(layout)
575 .unwrap_or_else(|_| handle_alloc_error(layout));
577 // Initialize the real ArcInner
578 let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
580 ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
581 ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
586 fn from_box(v: Box<T>) -> Arc<T> {
588 let box_unique = Box::into_unique(v);
589 let bptr = box_unique.as_ptr();
591 let value_size = size_of_val(&*bptr);
592 let ptr = Self::allocate_for_ptr(bptr);
594 // Copy value as bytes
595 ptr::copy_nonoverlapping(
596 bptr as *const T as *const u8,
597 &mut (*ptr).data as *mut _ as *mut u8,
600 // Free the allocation without dropping its contents
601 box_free(box_unique);
603 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
608 // Sets the data pointer of a `?Sized` raw pointer.
610 // For a slice/trait object, this sets the `data` field and leaves the rest
611 // unchanged. For a sized raw pointer, this simply sets the pointer.
612 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
613 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
618 // Copy elements from slice into newly allocated Arc<[T]>
620 // Unsafe because the caller must either take ownership or bind `T: Copy`
621 unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
622 let v_ptr = v as *const [T];
623 let ptr = Self::allocate_for_ptr(v_ptr);
625 ptr::copy_nonoverlapping(
627 &mut (*ptr).data as *mut [T] as *mut T,
630 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
634 // Specialization trait used for From<&[T]>
635 trait ArcFromSlice<T> {
636 fn from_slice(slice: &[T]) -> Self;
639 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
641 default fn from_slice(v: &[T]) -> Self {
642 // Panic guard while cloning T elements.
643 // In the event of a panic, elements that have been written
644 // into the new ArcInner will be dropped, then the memory freed.
652 impl<T> Drop for Guard<T> {
654 use core::slice::from_raw_parts_mut;
657 let slice = from_raw_parts_mut(self.elems, self.n_elems);
658 ptr::drop_in_place(slice);
660 Global.dealloc(self.mem.cast(), self.layout.clone());
666 let v_ptr = v as *const [T];
667 let ptr = Self::allocate_for_ptr(v_ptr);
669 let mem = ptr as *mut _ as *mut u8;
670 let layout = Layout::for_value(&*ptr);
672 // Pointer to first element
673 let elems = &mut (*ptr).data as *mut [T] as *mut T;
675 let mut guard = Guard{
676 mem: NonNull::new_unchecked(mem),
682 for (i, item) in v.iter().enumerate() {
683 ptr::write(elems.add(i), item.clone());
687 // All clear. Forget the guard so it doesn't free the new ArcInner.
690 Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
695 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
697 fn from_slice(v: &[T]) -> Self {
698 unsafe { Arc::copy_from_slice(v) }
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<T: ?Sized> Clone for Arc<T> {
704 /// Makes a clone of the `Arc` pointer.
706 /// This creates another pointer to the same inner value, increasing the
707 /// strong reference count.
712 /// use std::sync::Arc;
714 /// let five = Arc::new(5);
716 /// let _ = Arc::clone(&five);
719 fn clone(&self) -> Arc<T> {
720 // Using a relaxed ordering is alright here, as knowledge of the
721 // original reference prevents other threads from erroneously deleting
724 // As explained in the [Boost documentation][1], Increasing the
725 // reference counter can always be done with memory_order_relaxed: New
726 // references to an object can only be formed from an existing
727 // reference, and passing an existing reference from one thread to
728 // another must already provide any required synchronization.
730 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
731 let old_size = self.inner().strong.fetch_add(1, Relaxed);
733 // However we need to guard against massive refcounts in case someone
734 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
735 // and users will use-after free. We racily saturate to `isize::MAX` on
736 // the assumption that there aren't ~2 billion threads incrementing
737 // the reference count at once. This branch will never be taken in
738 // any realistic program.
740 // We abort because such a program is incredibly degenerate, and we
741 // don't care to support it.
742 if old_size > MAX_REFCOUNT {
748 Arc { ptr: self.ptr, phantom: PhantomData }
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<T: ?Sized> Deref for Arc<T> {
757 fn deref(&self) -> &T {
762 impl<T: Clone> Arc<T> {
763 /// Makes a mutable reference into the given `Arc`.
765 /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
766 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
767 /// ensure unique ownership. This is also referred to as clone-on-write.
769 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
771 /// [weak]: struct.Weak.html
772 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
773 /// [get_mut]: struct.Arc.html#method.get_mut
778 /// use std::sync::Arc;
780 /// let mut data = Arc::new(5);
782 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
783 /// let mut other_data = Arc::clone(&data); // Won't clone inner data
784 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
785 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
786 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
788 /// // Now `data` and `other_data` point to different values.
789 /// assert_eq!(*data, 8);
790 /// assert_eq!(*other_data, 12);
793 #[stable(feature = "arc_unique", since = "1.4.0")]
794 pub fn make_mut(this: &mut Self) -> &mut T {
795 // Note that we hold both a strong reference and a weak reference.
796 // Thus, releasing our strong reference only will not, by itself, cause
797 // the memory to be deallocated.
799 // Use Acquire to ensure that we see any writes to `weak` that happen
800 // before release writes (i.e., decrements) to `strong`. Since we hold a
801 // weak count, there's no chance the ArcInner itself could be
803 if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
804 // Another strong pointer exists; clone
805 *this = Arc::new((**this).clone());
806 } else if this.inner().weak.load(Relaxed) != 1 {
807 // Relaxed suffices in the above because this is fundamentally an
808 // optimization: we are always racing with weak pointers being
809 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
811 // We removed the last strong ref, but there are additional weak
812 // refs remaining. We'll move the contents to a new Arc, and
813 // invalidate the other weak refs.
815 // Note that it is not possible for the read of `weak` to yield
816 // usize::MAX (i.e., locked), since the weak count can only be
817 // locked by a thread with a strong reference.
819 // Materialize our own implicit weak pointer, so that it can clean
820 // up the ArcInner as needed.
821 let weak = Weak { ptr: this.ptr };
823 // mark the data itself as already deallocated
825 // there is no data race in the implicit write caused by `read`
826 // here (due to zeroing) because data is no longer accessed by
827 // other threads (due to there being no more strong refs at this
829 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
830 mem::swap(this, &mut swap);
834 // We were the sole reference of either kind; bump back up the
836 this.inner().strong.store(1, Release);
839 // As with `get_mut()`, the unsafety is ok because our reference was
840 // either unique to begin with, or became one upon cloning the contents.
842 &mut this.ptr.as_mut().data
847 impl<T: ?Sized> Arc<T> {
848 /// Returns a mutable reference to the inner value, if there are
849 /// no other `Arc` or [`Weak`][weak] pointers to the same value.
851 /// Returns [`None`][option] otherwise, because it is not safe to
852 /// mutate a shared value.
854 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
855 /// the inner value when it's shared.
857 /// [weak]: struct.Weak.html
858 /// [option]: ../../std/option/enum.Option.html
859 /// [make_mut]: struct.Arc.html#method.make_mut
860 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
865 /// use std::sync::Arc;
867 /// let mut x = Arc::new(3);
868 /// *Arc::get_mut(&mut x).unwrap() = 4;
869 /// assert_eq!(*x, 4);
871 /// let _y = Arc::clone(&x);
872 /// assert!(Arc::get_mut(&mut x).is_none());
875 #[stable(feature = "arc_unique", since = "1.4.0")]
876 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
877 if this.is_unique() {
878 // This unsafety is ok because we're guaranteed that the pointer
879 // returned is the *only* pointer that will ever be returned to T. Our
880 // reference count is guaranteed to be 1 at this point, and we required
881 // the Arc itself to be `mut`, so we're returning the only possible
882 // reference to the inner data.
884 Some(&mut this.ptr.as_mut().data)
891 /// Determine whether this is the unique reference (including weak refs) to
892 /// the underlying data.
894 /// Note that this requires locking the weak ref count.
895 fn is_unique(&mut self) -> bool {
896 // lock the weak pointer count if we appear to be the sole weak pointer
899 // The acquire label here ensures a happens-before relationship with any
900 // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
901 // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded
902 // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
903 if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
904 // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
905 // counter in `drop` -- the only access that happens when any but the last reference
907 let unique = self.inner().strong.load(Acquire) == 1;
909 // The release write here synchronizes with a read in `downgrade`,
910 // effectively preventing the above read of `strong` from happening
912 self.inner().weak.store(1, Release); // release the lock
920 #[stable(feature = "rust1", since = "1.0.0")]
921 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
924 /// This will decrement the strong reference count. If the strong reference
925 /// count reaches zero then the only other references (if any) are
926 /// [`Weak`], so we `drop` the inner value.
931 /// use std::sync::Arc;
935 /// impl Drop for Foo {
936 /// fn drop(&mut self) {
937 /// println!("dropped!");
941 /// let foo = Arc::new(Foo);
942 /// let foo2 = Arc::clone(&foo);
944 /// drop(foo); // Doesn't print anything
945 /// drop(foo2); // Prints "dropped!"
949 // Because `fetch_sub` is already atomic, we do not need to synchronize
950 // with other threads unless we are going to delete the object. This
951 // same logic applies to the below `fetch_sub` to the `weak` count.
952 if self.inner().strong.fetch_sub(1, Release) != 1 {
956 // This fence is needed to prevent reordering of use of the data and
957 // deletion of the data. Because it is marked `Release`, the decreasing
958 // of the reference count synchronizes with this `Acquire` fence. This
959 // means that use of the data happens before decreasing the reference
960 // count, which happens before this fence, which happens before the
961 // deletion of the data.
963 // As explained in the [Boost documentation][1],
965 // > It is important to enforce any possible access to the object in one
966 // > thread (through an existing reference) to *happen before* deleting
967 // > the object in a different thread. This is achieved by a "release"
968 // > operation after dropping a reference (any access to the object
969 // > through this reference must obviously happened before), and an
970 // > "acquire" operation before deleting the object.
972 // In particular, while the contents of an Arc are usually immutable, it's
973 // possible to have interior writes to something like a Mutex<T>. Since a
974 // Mutex is not acquired when it is deleted, we can't rely on its
975 // synchronization logic to make writes in thread A visible to a destructor
976 // running in thread B.
978 // Also note that the Acquire fence here could probably be replaced with an
979 // Acquire load, which could improve performance in highly-contended
980 // situations. See [2].
982 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
983 // [2]: (https://github.com/rust-lang/rust/pull/41714)
984 atomic::fence(Acquire);
992 impl Arc<dyn Any + Send + Sync> {
994 #[stable(feature = "rc_downcast", since = "1.29.0")]
995 /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1000 /// use std::any::Any;
1001 /// use std::sync::Arc;
1003 /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1004 /// if let Ok(string) = value.downcast::<String>() {
1005 /// println!("String ({}): {}", string.len(), string);
1010 /// let my_string = "Hello World".to_string();
1011 /// print_if_string(Arc::new(my_string));
1012 /// print_if_string(Arc::new(0i8));
1015 pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1017 T: Any + Send + Sync + 'static,
1019 if (*self).is::<T>() {
1020 let ptr = self.ptr.cast::<ArcInner<T>>();
1022 Ok(Arc { ptr, phantom: PhantomData })
1030 /// Constructs a new `Weak<T>`, without allocating any memory.
1031 /// Calling [`upgrade`] on the return value always gives [`None`].
1033 /// [`upgrade`]: struct.Weak.html#method.upgrade
1034 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1039 /// use std::sync::Weak;
1041 /// let empty: Weak<i64> = Weak::new();
1042 /// assert!(empty.upgrade().is_none());
1044 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1045 pub fn new() -> Weak<T> {
1047 ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0"),
1052 impl<T: ?Sized> Weak<T> {
1053 /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
1054 /// the lifetime of the value if successful.
1056 /// Returns [`None`] if the value has since been dropped.
1058 /// [`Arc`]: struct.Arc.html
1059 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1064 /// use std::sync::Arc;
1066 /// let five = Arc::new(5);
1068 /// let weak_five = Arc::downgrade(&five);
1070 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1071 /// assert!(strong_five.is_some());
1073 /// // Destroy all strong pointers.
1074 /// drop(strong_five);
1077 /// assert!(weak_five.upgrade().is_none());
1079 #[stable(feature = "arc_weak", since = "1.4.0")]
1080 pub fn upgrade(&self) -> Option<Arc<T>> {
1081 // We use a CAS loop to increment the strong count instead of a
1082 // fetch_add because once the count hits 0 it must never be above 0.
1083 let inner = self.inner()?;
1085 // Relaxed load because any write of 0 that we can observe
1086 // leaves the field in a permanently zero state (so a
1087 // "stale" read of 0 is fine), and any other value is
1088 // confirmed via the CAS below.
1089 let mut n = inner.strong.load(Relaxed);
1096 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1097 if n > MAX_REFCOUNT {
1103 // Relaxed is valid for the same reason it is on Arc's Clone impl
1104 match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
1105 Ok(_) => return Some(Arc {
1106 // null checked above
1108 phantom: PhantomData,
1110 Err(old) => n = old,
1115 /// Return `None` when the pointer is dangling and there is no allocated `ArcInner`,
1116 /// i.e. this `Weak` was created by `Weak::new`
1118 fn inner(&self) -> Option<&ArcInner<T>> {
1119 if is_dangling(self.ptr) {
1122 Some(unsafe { self.ptr.as_ref() })
1127 #[stable(feature = "arc_weak", since = "1.4.0")]
1128 impl<T: ?Sized> Clone for Weak<T> {
1129 /// Makes a clone of the `Weak` pointer that points to the same value.
1134 /// use std::sync::{Arc, Weak};
1136 /// let weak_five = Arc::downgrade(&Arc::new(5));
1138 /// let _ = Weak::clone(&weak_five);
1141 fn clone(&self) -> Weak<T> {
1142 let inner = if let Some(inner) = self.inner() {
1145 return Weak { ptr: self.ptr };
1147 // See comments in Arc::clone() for why this is relaxed. This can use a
1148 // fetch_add (ignoring the lock) because the weak count is only locked
1149 // where are *no other* weak pointers in existence. (So we can't be
1150 // running this code in that case).
1151 let old_size = inner.weak.fetch_add(1, Relaxed);
1153 // See comments in Arc::clone() for why we do this (for mem::forget).
1154 if old_size > MAX_REFCOUNT {
1160 return Weak { ptr: self.ptr };
1164 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1165 impl<T> Default for Weak<T> {
1166 /// Constructs a new `Weak<T>`, without allocating memory.
1167 /// Calling [`upgrade`][Weak::upgrade] on the return value always
1170 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1175 /// use std::sync::Weak;
1177 /// let empty: Weak<i64> = Default::default();
1178 /// assert!(empty.upgrade().is_none());
1180 fn default() -> Weak<T> {
1185 #[stable(feature = "arc_weak", since = "1.4.0")]
1186 impl<T: ?Sized> Drop for Weak<T> {
1187 /// Drops the `Weak` pointer.
1192 /// use std::sync::{Arc, Weak};
1196 /// impl Drop for Foo {
1197 /// fn drop(&mut self) {
1198 /// println!("dropped!");
1202 /// let foo = Arc::new(Foo);
1203 /// let weak_foo = Arc::downgrade(&foo);
1204 /// let other_weak_foo = Weak::clone(&weak_foo);
1206 /// drop(weak_foo); // Doesn't print anything
1207 /// drop(foo); // Prints "dropped!"
1209 /// assert!(other_weak_foo.upgrade().is_none());
1211 fn drop(&mut self) {
1212 // If we find out that we were the last weak pointer, then its time to
1213 // deallocate the data entirely. See the discussion in Arc::drop() about
1214 // the memory orderings
1216 // It's not necessary to check for the locked state here, because the
1217 // weak count can only be locked if there was precisely one weak ref,
1218 // meaning that drop could only subsequently run ON that remaining weak
1219 // ref, which can only happen after the lock is released.
1220 let inner = if let Some(inner) = self.inner() {
1226 if inner.weak.fetch_sub(1, Release) == 1 {
1227 atomic::fence(Acquire);
1229 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1237 /// Equality for two `Arc`s.
1239 /// Two `Arc`s are equal if their inner values are equal.
1244 /// use std::sync::Arc;
1246 /// let five = Arc::new(5);
1248 /// assert!(five == Arc::new(5));
1250 fn eq(&self, other: &Arc<T>) -> bool {
1251 *(*self) == *(*other)
1254 /// Inequality for two `Arc`s.
1256 /// Two `Arc`s are unequal if their inner values are unequal.
1261 /// use std::sync::Arc;
1263 /// let five = Arc::new(5);
1265 /// assert!(five != Arc::new(6));
1267 fn ne(&self, other: &Arc<T>) -> bool {
1268 *(*self) != *(*other)
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1273 /// Partial comparison for two `Arc`s.
1275 /// The two are compared by calling `partial_cmp()` on their inner values.
1280 /// use std::sync::Arc;
1281 /// use std::cmp::Ordering;
1283 /// let five = Arc::new(5);
1285 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1287 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1288 (**self).partial_cmp(&**other)
1291 /// Less-than comparison for two `Arc`s.
1293 /// The two are compared by calling `<` on their inner values.
1298 /// use std::sync::Arc;
1300 /// let five = Arc::new(5);
1302 /// assert!(five < Arc::new(6));
1304 fn lt(&self, other: &Arc<T>) -> bool {
1305 *(*self) < *(*other)
1308 /// 'Less than or equal to' comparison for two `Arc`s.
1310 /// The two are compared by calling `<=` on their inner values.
1315 /// use std::sync::Arc;
1317 /// let five = Arc::new(5);
1319 /// assert!(five <= Arc::new(5));
1321 fn le(&self, other: &Arc<T>) -> bool {
1322 *(*self) <= *(*other)
1325 /// Greater-than comparison for two `Arc`s.
1327 /// The two are compared by calling `>` on their inner values.
1332 /// use std::sync::Arc;
1334 /// let five = Arc::new(5);
1336 /// assert!(five > Arc::new(4));
1338 fn gt(&self, other: &Arc<T>) -> bool {
1339 *(*self) > *(*other)
1342 /// 'Greater than or equal to' comparison for two `Arc`s.
1344 /// The two are compared by calling `>=` on their inner values.
1349 /// use std::sync::Arc;
1351 /// let five = Arc::new(5);
1353 /// assert!(five >= Arc::new(5));
1355 fn ge(&self, other: &Arc<T>) -> bool {
1356 *(*self) >= *(*other)
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<T: ?Sized + Ord> Ord for Arc<T> {
1361 /// Comparison for two `Arc`s.
1363 /// The two are compared by calling `cmp()` on their inner values.
1368 /// use std::sync::Arc;
1369 /// use std::cmp::Ordering;
1371 /// let five = Arc::new(5);
1373 /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1375 fn cmp(&self, other: &Arc<T>) -> Ordering {
1376 (**self).cmp(&**other)
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1385 fmt::Display::fmt(&**self, f)
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1391 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1392 fmt::Debug::fmt(&**self, f)
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1399 fmt::Pointer::fmt(&(&**self as *const T), f)
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<T: Default> Default for Arc<T> {
1405 /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1410 /// use std::sync::Arc;
1412 /// let x: Arc<i32> = Default::default();
1413 /// assert_eq!(*x, 0);
1415 fn default() -> Arc<T> {
1416 Arc::new(Default::default())
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<T: ?Sized + Hash> Hash for Arc<T> {
1422 fn hash<H: Hasher>(&self, state: &mut H) {
1423 (**self).hash(state)
1427 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1428 impl<T> From<T> for Arc<T> {
1429 fn from(t: T) -> Self {
1434 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1435 impl<'a, T: Clone> From<&'a [T]> for Arc<[T]> {
1437 fn from(v: &[T]) -> Arc<[T]> {
1438 <Self as ArcFromSlice<T>>::from_slice(v)
1442 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1443 impl<'a> From<&'a str> for Arc<str> {
1445 fn from(v: &str) -> Arc<str> {
1446 let arc = Arc::<[u8]>::from(v.as_bytes());
1447 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
1451 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1452 impl From<String> for Arc<str> {
1454 fn from(v: String) -> Arc<str> {
1459 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1460 impl<T: ?Sized> From<Box<T>> for Arc<T> {
1462 fn from(v: Box<T>) -> Arc<T> {
1467 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1468 impl<T> From<Vec<T>> for Arc<[T]> {
1470 fn from(mut v: Vec<T>) -> Arc<[T]> {
1472 let arc = Arc::copy_from_slice(&v);
1474 // Allow the Vec to free its memory, but not destroy its contents
1484 use std::boxed::Box;
1485 use std::clone::Clone;
1486 use std::sync::mpsc::channel;
1489 use std::option::Option;
1490 use std::option::Option::{None, Some};
1491 use std::sync::atomic;
1492 use std::sync::atomic::Ordering::{Acquire, SeqCst};
1494 use std::sync::Mutex;
1495 use std::convert::From;
1497 use super::{Arc, Weak};
1500 struct Canary(*mut atomic::AtomicUsize);
1502 impl Drop for Canary {
1503 fn drop(&mut self) {
1507 (*c).fetch_add(1, SeqCst);
1515 #[cfg_attr(target_os = "emscripten", ignore)]
1516 fn manually_share_arc() {
1517 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1518 let arc_v = Arc::new(v);
1520 let (tx, rx) = channel();
1522 let _t = thread::spawn(move || {
1523 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
1524 assert_eq!((*arc_v)[3], 4);
1527 tx.send(arc_v.clone()).unwrap();
1529 assert_eq!((*arc_v)[2], 3);
1530 assert_eq!((*arc_v)[4], 5);
1534 fn test_arc_get_mut() {
1535 let mut x = Arc::new(3);
1536 *Arc::get_mut(&mut x).unwrap() = 4;
1539 assert!(Arc::get_mut(&mut x).is_none());
1541 assert!(Arc::get_mut(&mut x).is_some());
1542 let _w = Arc::downgrade(&x);
1543 assert!(Arc::get_mut(&mut x).is_none());
1548 let x = Arc::new(3);
1549 assert_eq!(Arc::try_unwrap(x), Ok(3));
1550 let x = Arc::new(4);
1552 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1553 let x = Arc::new(5);
1554 let _w = Arc::downgrade(&x);
1555 assert_eq!(Arc::try_unwrap(x), Ok(5));
1559 fn into_from_raw() {
1560 let x = Arc::new(box "hello");
1563 let x_ptr = Arc::into_raw(x);
1566 assert_eq!(**x_ptr, "hello");
1568 let x = Arc::from_raw(x_ptr);
1569 assert_eq!(**x, "hello");
1571 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
1576 fn test_into_from_raw_unsized() {
1577 use std::fmt::Display;
1578 use std::string::ToString;
1580 let arc: Arc<str> = Arc::from("foo");
1582 let ptr = Arc::into_raw(arc.clone());
1583 let arc2 = unsafe { Arc::from_raw(ptr) };
1585 assert_eq!(unsafe { &*ptr }, "foo");
1586 assert_eq!(arc, arc2);
1588 let arc: Arc<dyn Display> = Arc::new(123);
1590 let ptr = Arc::into_raw(arc.clone());
1591 let arc2 = unsafe { Arc::from_raw(ptr) };
1593 assert_eq!(unsafe { &*ptr }.to_string(), "123");
1594 assert_eq!(arc2.to_string(), "123");
1598 fn test_cowarc_clone_make_mut() {
1599 let mut cow0 = Arc::new(75);
1600 let mut cow1 = cow0.clone();
1601 let mut cow2 = cow1.clone();
1603 assert!(75 == *Arc::make_mut(&mut cow0));
1604 assert!(75 == *Arc::make_mut(&mut cow1));
1605 assert!(75 == *Arc::make_mut(&mut cow2));
1607 *Arc::make_mut(&mut cow0) += 1;
1608 *Arc::make_mut(&mut cow1) += 2;
1609 *Arc::make_mut(&mut cow2) += 3;
1611 assert!(76 == *cow0);
1612 assert!(77 == *cow1);
1613 assert!(78 == *cow2);
1615 // none should point to the same backing memory
1616 assert!(*cow0 != *cow1);
1617 assert!(*cow0 != *cow2);
1618 assert!(*cow1 != *cow2);
1622 fn test_cowarc_clone_unique2() {
1623 let mut cow0 = Arc::new(75);
1624 let cow1 = cow0.clone();
1625 let cow2 = cow1.clone();
1627 assert!(75 == *cow0);
1628 assert!(75 == *cow1);
1629 assert!(75 == *cow2);
1631 *Arc::make_mut(&mut cow0) += 1;
1632 assert!(76 == *cow0);
1633 assert!(75 == *cow1);
1634 assert!(75 == *cow2);
1636 // cow1 and cow2 should share the same contents
1637 // cow0 should have a unique reference
1638 assert!(*cow0 != *cow1);
1639 assert!(*cow0 != *cow2);
1640 assert!(*cow1 == *cow2);
1644 fn test_cowarc_clone_weak() {
1645 let mut cow0 = Arc::new(75);
1646 let cow1_weak = Arc::downgrade(&cow0);
1648 assert!(75 == *cow0);
1649 assert!(75 == *cow1_weak.upgrade().unwrap());
1651 *Arc::make_mut(&mut cow0) += 1;
1653 assert!(76 == *cow0);
1654 assert!(cow1_weak.upgrade().is_none());
1659 let x = Arc::new(5);
1660 let y = Arc::downgrade(&x);
1661 assert!(y.upgrade().is_some());
1666 let x = Arc::new(5);
1667 let y = Arc::downgrade(&x);
1669 assert!(y.upgrade().is_none());
1673 fn weak_self_cyclic() {
1675 x: Mutex<Option<Weak<Cycle>>>,
1678 let a = Arc::new(Cycle { x: Mutex::new(None) });
1679 let b = Arc::downgrade(&a.clone());
1680 *a.x.lock().unwrap() = Some(b);
1682 // hopefully we don't double-free (or leak)...
1687 let mut canary = atomic::AtomicUsize::new(0);
1688 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1690 assert!(canary.load(Acquire) == 1);
1694 fn drop_arc_weak() {
1695 let mut canary = atomic::AtomicUsize::new(0);
1696 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1697 let arc_weak = Arc::downgrade(&arc);
1698 assert!(canary.load(Acquire) == 0);
1700 assert!(canary.load(Acquire) == 1);
1705 fn test_strong_count() {
1706 let a = Arc::new(0);
1707 assert!(Arc::strong_count(&a) == 1);
1708 let w = Arc::downgrade(&a);
1709 assert!(Arc::strong_count(&a) == 1);
1710 let b = w.upgrade().expect("");
1711 assert!(Arc::strong_count(&b) == 2);
1712 assert!(Arc::strong_count(&a) == 2);
1715 assert!(Arc::strong_count(&b) == 1);
1717 assert!(Arc::strong_count(&b) == 2);
1718 assert!(Arc::strong_count(&c) == 2);
1722 fn test_weak_count() {
1723 let a = Arc::new(0);
1724 assert!(Arc::strong_count(&a) == 1);
1725 assert!(Arc::weak_count(&a) == 0);
1726 let w = Arc::downgrade(&a);
1727 assert!(Arc::strong_count(&a) == 1);
1728 assert!(Arc::weak_count(&a) == 1);
1730 assert!(Arc::weak_count(&a) == 2);
1733 assert!(Arc::strong_count(&a) == 1);
1734 assert!(Arc::weak_count(&a) == 0);
1736 assert!(Arc::strong_count(&a) == 2);
1737 assert!(Arc::weak_count(&a) == 0);
1738 let d = Arc::downgrade(&c);
1739 assert!(Arc::weak_count(&c) == 1);
1740 assert!(Arc::strong_count(&c) == 2);
1749 let a = Arc::new(5);
1750 assert_eq!(format!("{:?}", a), "5");
1753 // Make sure deriving works with Arc<T>
1754 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1761 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1762 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1763 let y = Arc::downgrade(&x.clone());
1765 assert!(y.upgrade().is_none());
1769 fn test_from_owned() {
1771 let foo_arc = Arc::from(foo);
1772 assert!(123 == *foo_arc);
1776 fn test_new_weak() {
1777 let foo: Weak<usize> = Weak::new();
1778 assert!(foo.upgrade().is_none());
1783 let five = Arc::new(5);
1784 let same_five = five.clone();
1785 let other_five = Arc::new(5);
1787 assert!(Arc::ptr_eq(&five, &same_five));
1788 assert!(!Arc::ptr_eq(&five, &other_five));
1792 #[cfg_attr(target_os = "emscripten", ignore)]
1793 fn test_weak_count_locked() {
1794 let mut a = Arc::new(atomic::AtomicBool::new(false));
1796 let t = thread::spawn(move || {
1797 for _i in 0..1000000 {
1798 Arc::get_mut(&mut a);
1800 a.store(true, SeqCst);
1803 while !a2.load(SeqCst) {
1804 let n = Arc::weak_count(&a2);
1805 assert!(n < 2, "bad weak count: {}", n);
1811 fn test_from_str() {
1812 let r: Arc<str> = Arc::from("foo");
1814 assert_eq!(&r[..], "foo");
1818 fn test_copy_from_slice() {
1819 let s: &[u32] = &[1, 2, 3];
1820 let r: Arc<[u32]> = Arc::from(s);
1822 assert_eq!(&r[..], [1, 2, 3]);
1826 fn test_clone_from_slice() {
1827 #[derive(Clone, Debug, Eq, PartialEq)]
1830 let s: &[X] = &[X(1), X(2), X(3)];
1831 let r: Arc<[X]> = Arc::from(s);
1833 assert_eq!(&r[..], s);
1838 fn test_clone_from_slice_panic() {
1839 use std::string::{String, ToString};
1841 struct Fail(u32, String);
1843 impl Clone for Fail {
1844 fn clone(&self) -> Fail {
1848 Fail(self.0, self.1.clone())
1853 Fail(0, "foo".to_string()),
1854 Fail(1, "bar".to_string()),
1855 Fail(2, "baz".to_string()),
1858 // Should panic, but not cause memory corruption
1859 let _r: Arc<[Fail]> = Arc::from(s);
1863 fn test_from_box() {
1864 let b: Box<u32> = box 123;
1865 let r: Arc<u32> = Arc::from(b);
1867 assert_eq!(*r, 123);
1871 fn test_from_box_str() {
1872 use std::string::String;
1874 let s = String::from("foo").into_boxed_str();
1875 let r: Arc<str> = Arc::from(s);
1877 assert_eq!(&r[..], "foo");
1881 fn test_from_box_slice() {
1882 let s = vec![1, 2, 3].into_boxed_slice();
1883 let r: Arc<[u32]> = Arc::from(s);
1885 assert_eq!(&r[..], [1, 2, 3]);
1889 fn test_from_box_trait() {
1890 use std::fmt::Display;
1891 use std::string::ToString;
1893 let b: Box<dyn Display> = box 123;
1894 let r: Arc<dyn Display> = Arc::from(b);
1896 assert_eq!(r.to_string(), "123");
1900 fn test_from_box_trait_zero_sized() {
1901 use std::fmt::Debug;
1903 let b: Box<dyn Debug> = box ();
1904 let r: Arc<dyn Debug> = Arc::from(b);
1906 assert_eq!(format!("{:?}", r), "()");
1910 fn test_from_vec() {
1911 let v = vec![1, 2, 3];
1912 let r: Arc<[u32]> = Arc::from(v);
1914 assert_eq!(&r[..], [1, 2, 3]);
1918 fn test_downcast() {
1921 let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::max_value());
1922 let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
1924 assert!(r1.clone().downcast::<u32>().is_err());
1926 let r1i32 = r1.downcast::<i32>();
1927 assert!(r1i32.is_ok());
1928 assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value()));
1930 assert!(r2.clone().downcast::<i32>().is_err());
1932 let r2str = r2.downcast::<&'static str>();
1933 assert!(r2str.is_ok());
1934 assert_eq!(r2str.unwrap(), Arc::new("abc"));
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1940 fn borrow(&self) -> &T {
1945 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1946 impl<T: ?Sized> AsRef<T> for Arc<T> {
1947 fn as_ref(&self) -> &T {
1952 #[unstable(feature = "pin", issue = "49150")]
1953 impl<T: ?Sized> Unpin for Arc<T> { }