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 //! Threadsafe reference-counted boxes (the `Arc<T>` type).
15 //! The `Arc<T>` type provides shared ownership of an immutable value.
16 //! Destruction is deterministic, and will occur as soon as the last owner is
17 //! gone. It is marked as `Send` because it uses atomic reference counting.
19 //! If you do not need thread-safety, and just need shared ownership, consider
20 //! the [`Rc<T>` type](../rc/struct.Rc.html). It is the same as `Arc<T>`, but
21 //! does not use atomics, making it both thread-unsafe as well as significantly
22 //! faster when updating the reference count.
24 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
25 //! to the box. A `Weak<T>` pointer can be upgraded to an `Arc<T>` pointer, but
26 //! will return `None` if the value has already been dropped.
28 //! For example, a tree with parent pointers can be represented by putting the
29 //! nodes behind strong `Arc<T>` pointers, and then storing the parent pointers
30 //! as `Weak<T>` pointers.
34 //! Sharing some immutable data between threads:
37 //! use std::sync::Arc;
40 //! let five = Arc::new(5);
43 //! let five = five.clone();
45 //! thread::spawn(move || {
46 //! println!("{:?}", five);
51 //! Sharing mutable data safely between threads with a `Mutex`:
54 //! use std::sync::{Arc, Mutex};
57 //! let five = Arc::new(Mutex::new(5));
60 //! let five = five.clone();
62 //! thread::spawn(move || {
63 //! let mut number = five.lock().unwrap();
67 //! println!("{}", *number); // prints 6
74 use core::sync::atomic;
75 use core::sync::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
78 use core::cmp::Ordering;
79 use core::mem::{align_of_val, size_of_val};
80 use core::intrinsics::abort;
83 use core::ops::CoerceUnsized;
84 use core::ptr::{self, Shared};
85 use core::marker::Unsize;
86 use core::hash::{Hash, Hasher};
87 use core::{usize, isize};
88 use core::convert::From;
91 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
93 /// An atomically reference counted wrapper for shared state.
97 /// In this example, a large vector is shared between several threads.
98 /// With simple pipes, without `Arc`, a copy would have to be made for each
101 /// When you clone an `Arc<T>`, it will create another pointer to the data and
102 /// increase the reference counter.
105 /// use std::sync::Arc;
109 /// let numbers: Vec<_> = (0..100u32).collect();
110 /// let shared_numbers = Arc::new(numbers);
113 /// let child_numbers = shared_numbers.clone();
115 /// thread::spawn(move || {
116 /// let local_numbers = &child_numbers[..];
118 /// // Work with the local numbers
123 #[unsafe_no_drop_flag]
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub struct Arc<T: ?Sized> {
126 // FIXME #12808: strange name to try to avoid interfering with
127 // field accesses of the contained type via Deref
128 _ptr: Shared<ArcInner<T>>,
131 #[stable(feature = "rust1", since = "1.0.0")]
132 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
133 #[stable(feature = "rust1", since = "1.0.0")]
134 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
136 #[unstable(feature = "coerce_unsized", issue = "27732")]
137 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
139 /// A weak pointer to an `Arc`.
141 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
142 /// used to break cycles between `Arc` pointers.
143 #[unsafe_no_drop_flag]
144 #[stable(feature = "arc_weak", since = "1.4.0")]
145 pub struct Weak<T: ?Sized> {
146 // FIXME #12808: strange name to try to avoid interfering with
147 // field accesses of the contained type via Deref
148 _ptr: Shared<ArcInner<T>>,
151 #[stable(feature = "rust1", since = "1.0.0")]
152 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
153 #[stable(feature = "rust1", since = "1.0.0")]
154 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
156 #[unstable(feature = "coerce_unsized", issue = "27732")]
157 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 struct ArcInner<T: ?Sized> {
167 strong: atomic::AtomicUsize,
169 // the value usize::MAX acts as a sentinel for temporarily "locking" the
170 // ability to upgrade weak pointers or downgrade strong ones; this is used
171 // to avoid races in `make_mut` and `get_mut`.
172 weak: atomic::AtomicUsize,
177 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
178 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
181 /// Constructs a new `Arc<T>`.
186 /// use std::sync::Arc;
188 /// let five = Arc::new(5);
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn new(data: T) -> Arc<T> {
193 // Start the weak pointer count as 1 which is the weak pointer that's
194 // held by all the strong pointers (kinda), see std/rc.rs for more info
195 let x: Box<_> = box ArcInner {
196 strong: atomic::AtomicUsize::new(1),
197 weak: atomic::AtomicUsize::new(1),
200 Arc { _ptr: unsafe { Shared::new(Box::into_raw(x)) } }
203 /// Unwraps the contained value if the `Arc<T>` has only one strong reference.
204 /// This will succeed even if there are outstanding weak references.
206 /// Otherwise, an `Err` is returned with the same `Arc<T>`.
211 /// use std::sync::Arc;
213 /// let x = Arc::new(3);
214 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
216 /// let x = Arc::new(4);
217 /// let _y = x.clone();
218 /// assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
221 #[stable(feature = "arc_unique", since = "1.4.0")]
222 pub fn try_unwrap(this: Self) -> Result<T, Self> {
223 // See `drop` for why all these atomics are like this
224 if this.inner().strong.compare_and_swap(1, 0, Release) != 1 {
228 atomic::fence(Acquire);
231 let ptr = *this._ptr;
232 let elem = ptr::read(&(*ptr).data);
234 // Make a weak pointer to clean up the implicit strong-weak reference
235 let _weak = Weak { _ptr: this._ptr };
243 impl<T: ?Sized> Arc<T> {
244 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
249 /// use std::sync::Arc;
251 /// let five = Arc::new(5);
253 /// let weak_five = Arc::downgrade(&five);
255 #[stable(feature = "arc_weak", since = "1.4.0")]
256 pub fn downgrade(this: &Self) -> Weak<T> {
258 // This Relaxed is OK because we're checking the value in the CAS
260 let cur = this.inner().weak.load(Relaxed);
262 // check if the weak counter is currently "locked"; if so, spin.
263 if cur == usize::MAX {
267 // NOTE: this code currently ignores the possibility of overflow
268 // into usize::MAX; in general both Rc and Arc need to be adjusted
269 // to deal with overflow.
271 // Unlike with Clone(), we need this to be an Acquire read to
272 // synchronize with the write coming from `is_unique`, so that the
273 // events prior to that write happen before this read.
274 if this.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur {
275 return Weak { _ptr: this._ptr };
280 /// Get the number of weak references to this value.
282 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
284 pub fn weak_count(this: &Self) -> usize {
285 this.inner().weak.load(SeqCst) - 1
288 /// Get the number of strong references to this value.
290 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
292 pub fn strong_count(this: &Self) -> usize {
293 this.inner().strong.load(SeqCst)
297 fn inner(&self) -> &ArcInner<T> {
298 // This unsafety is ok because while this arc is alive we're guaranteed
299 // that the inner pointer is valid. Furthermore, we know that the
300 // `ArcInner` structure itself is `Sync` because the inner data is
301 // `Sync` as well, so we're ok loaning out an immutable pointer to these
303 unsafe { &**self._ptr }
306 // Non-inlined part of `drop`.
308 unsafe fn drop_slow(&mut self) {
309 let ptr = *self._ptr;
311 // Destroy the data at this time, even though we may not free the box
312 // allocation itself (there may still be weak pointers lying around).
313 ptr::drop_in_place(&mut (*ptr).data);
315 if self.inner().weak.fetch_sub(1, Release) == 1 {
316 atomic::fence(Acquire);
317 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<T: ?Sized> Clone for Arc<T> {
324 /// Makes a clone of the `Arc<T>`.
326 /// This increases the strong reference count.
331 /// use std::sync::Arc;
333 /// let five = Arc::new(5);
338 fn clone(&self) -> Arc<T> {
339 // Using a relaxed ordering is alright here, as knowledge of the
340 // original reference prevents other threads from erroneously deleting
343 // As explained in the [Boost documentation][1], Increasing the
344 // reference counter can always be done with memory_order_relaxed: New
345 // references to an object can only be formed from an existing
346 // reference, and passing an existing reference from one thread to
347 // another must already provide any required synchronization.
349 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
350 let old_size = self.inner().strong.fetch_add(1, Relaxed);
352 // However we need to guard against massive refcounts in case someone
353 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
354 // and users will use-after free. We racily saturate to `isize::MAX` on
355 // the assumption that there aren't ~2 billion threads incrementing
356 // the reference count at once. This branch will never be taken in
357 // any realistic program.
359 // We abort because such a program is incredibly degenerate, and we
360 // don't care to support it.
361 if old_size > MAX_REFCOUNT {
367 Arc { _ptr: self._ptr }
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl<T: ?Sized> Deref for Arc<T> {
376 fn deref(&self) -> &T {
381 impl<T: Clone> Arc<T> {
382 /// Make a mutable reference into the given `Arc<T>` by cloning the inner
383 /// data if the `Arc<T>` doesn't have one strong reference and no weak
386 /// This is also referred to as a copy-on-write.
391 /// use std::sync::Arc;
393 /// let mut data = Arc::new(5);
395 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
396 /// let mut other_data = data.clone(); // Won't clone inner data
397 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
398 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
399 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
401 /// // Note: data and other_data now point to different numbers
402 /// assert_eq!(*data, 8);
403 /// assert_eq!(*other_data, 12);
407 #[stable(feature = "arc_unique", since = "1.4.0")]
408 pub fn make_mut(this: &mut Self) -> &mut T {
409 // Note that we hold both a strong reference and a weak reference.
410 // Thus, releasing our strong reference only will not, by itself, cause
411 // the memory to be deallocated.
413 // Use Acquire to ensure that we see any writes to `weak` that happen
414 // before release writes (i.e., decrements) to `strong`. Since we hold a
415 // weak count, there's no chance the ArcInner itself could be
417 if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
418 // Another strong pointer exists; clone
419 *this = Arc::new((**this).clone());
420 } else if this.inner().weak.load(Relaxed) != 1 {
421 // Relaxed suffices in the above because this is fundamentally an
422 // optimization: we are always racing with weak pointers being
423 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
425 // We removed the last strong ref, but there are additional weak
426 // refs remaining. We'll move the contents to a new Arc, and
427 // invalidate the other weak refs.
429 // Note that it is not possible for the read of `weak` to yield
430 // usize::MAX (i.e., locked), since the weak count can only be
431 // locked by a thread with a strong reference.
433 // Materialize our own implicit weak pointer, so that it can clean
434 // up the ArcInner as needed.
435 let weak = Weak { _ptr: this._ptr };
437 // mark the data itself as already deallocated
439 // there is no data race in the implicit write caused by `read`
440 // here (due to zeroing) because data is no longer accessed by
441 // other threads (due to there being no more strong refs at this
443 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
444 mem::swap(this, &mut swap);
448 // We were the sole reference of either kind; bump back up the
450 this.inner().strong.store(1, Release);
453 // As with `get_mut()`, the unsafety is ok because our reference was
454 // either unique to begin with, or became one upon cloning the contents.
456 let inner = &mut **this._ptr;
462 impl<T: ?Sized> Arc<T> {
463 /// Returns a mutable reference to the contained value if the `Arc<T>` has
464 /// one strong reference and no weak references.
469 /// use std::sync::Arc;
471 /// let mut x = Arc::new(3);
472 /// *Arc::get_mut(&mut x).unwrap() = 4;
473 /// assert_eq!(*x, 4);
475 /// let _y = x.clone();
476 /// assert!(Arc::get_mut(&mut x).is_none());
479 #[stable(feature = "arc_unique", since = "1.4.0")]
480 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
481 if this.is_unique() {
482 // This unsafety is ok because we're guaranteed that the pointer
483 // returned is the *only* pointer that will ever be returned to T. Our
484 // reference count is guaranteed to be 1 at this point, and we required
485 // the Arc itself to be `mut`, so we're returning the only possible
486 // reference to the inner data.
488 let inner = &mut **this._ptr;
489 Some(&mut inner.data)
496 /// Determine whether this is the unique reference (including weak refs) to
497 /// the underlying data.
499 /// Note that this requires locking the weak ref count.
500 fn is_unique(&mut self) -> bool {
501 // lock the weak pointer count if we appear to be the sole weak pointer
504 // The acquire label here ensures a happens-before relationship with any
505 // writes to `strong` prior to decrements of the `weak` count (via drop,
506 // which uses Release).
507 if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
508 // Due to the previous acquire read, this will observe any writes to
509 // `strong` that were due to upgrading weak pointers; only strong
510 // clones remain, which require that the strong count is > 1 anyway.
511 let unique = self.inner().strong.load(Relaxed) == 1;
513 // The release write here synchronizes with a read in `downgrade`,
514 // effectively preventing the above read of `strong` from happening
516 self.inner().weak.store(1, Release); // release the lock
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl<T: ?Sized> Drop for Arc<T> {
526 /// Drops the `Arc<T>`.
528 /// This will decrement the strong reference count. If the strong reference
529 /// count becomes zero and the only other references are `Weak<T>` ones,
530 /// `drop`s the inner value.
535 /// use std::sync::Arc;
538 /// let five = Arc::new(5);
542 /// drop(five); // explicit drop
545 /// let five = Arc::new(5);
549 /// } // implicit drop
551 #[unsafe_destructor_blind_to_params]
554 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
555 // more than once (but it is guaranteed to be zeroed after the first if
556 // it's run more than once)
557 let ptr = *self._ptr;
558 // if ptr.is_null() { return }
559 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
563 // Because `fetch_sub` is already atomic, we do not need to synchronize
564 // with other threads unless we are going to delete the object. This
565 // same logic applies to the below `fetch_sub` to the `weak` count.
566 if self.inner().strong.fetch_sub(1, Release) != 1 {
570 // This fence is needed to prevent reordering of use of the data and
571 // deletion of the data. Because it is marked `Release`, the decreasing
572 // of the reference count synchronizes with this `Acquire` fence. This
573 // means that use of the data happens before decreasing the reference
574 // count, which happens before this fence, which happens before the
575 // deletion of the data.
577 // As explained in the [Boost documentation][1],
579 // > It is important to enforce any possible access to the object in one
580 // > thread (through an existing reference) to *happen before* deleting
581 // > the object in a different thread. This is achieved by a "release"
582 // > operation after dropping a reference (any access to the object
583 // > through this reference must obviously happened before), and an
584 // > "acquire" operation before deleting the object.
586 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
587 atomic::fence(Acquire);
595 impl<T: ?Sized> Weak<T> {
596 /// Upgrades a weak reference to a strong reference.
598 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
600 /// Returns `None` if there were no strong references and the data was
606 /// use std::sync::Arc;
608 /// let five = Arc::new(5);
610 /// let weak_five = Arc::downgrade(&five);
612 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
614 #[stable(feature = "arc_weak", since = "1.4.0")]
615 pub fn upgrade(&self) -> Option<Arc<T>> {
616 // We use a CAS loop to increment the strong count instead of a
617 // fetch_add because once the count hits 0 it must never be above 0.
618 let inner = self.inner();
620 // Relaxed load because any write of 0 that we can observe
621 // leaves the field in a permanently zero state (so a
622 // "stale" read of 0 is fine), and any other value is
623 // confirmed via the CAS below.
624 let n = inner.strong.load(Relaxed);
629 // See comments in `Arc::clone` for why we do this (for `mem::forget`).
630 if n > MAX_REFCOUNT {
634 // Relaxed is valid for the same reason it is on Arc's Clone impl
635 let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
637 return Some(Arc { _ptr: self._ptr });
643 fn inner(&self) -> &ArcInner<T> {
644 // See comments above for why this is "safe"
645 unsafe { &**self._ptr }
649 #[stable(feature = "arc_weak", since = "1.4.0")]
650 impl<T: ?Sized> Clone for Weak<T> {
651 /// Makes a clone of the `Weak<T>`.
653 /// This increases the weak reference count.
658 /// use std::sync::Arc;
660 /// let weak_five = Arc::downgrade(&Arc::new(5));
662 /// weak_five.clone();
665 fn clone(&self) -> Weak<T> {
666 // See comments in Arc::clone() for why this is relaxed. This can use a
667 // fetch_add (ignoring the lock) because the weak count is only locked
668 // where are *no other* weak pointers in existence. (So we can't be
669 // running this code in that case).
670 let old_size = self.inner().weak.fetch_add(1, Relaxed);
672 // See comments in Arc::clone() for why we do this (for mem::forget).
673 if old_size > MAX_REFCOUNT {
679 return Weak { _ptr: self._ptr };
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl<T: ?Sized> Drop for Weak<T> {
685 /// Drops the `Weak<T>`.
687 /// This will decrement the weak reference count.
692 /// use std::sync::Arc;
695 /// let five = Arc::new(5);
696 /// let weak_five = Arc::downgrade(&five);
700 /// drop(weak_five); // explicit drop
703 /// let five = Arc::new(5);
704 /// let weak_five = Arc::downgrade(&five);
708 /// } // implicit drop
711 let ptr = *self._ptr;
713 // see comments above for why this check is here
714 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
718 // If we find out that we were the last weak pointer, then its time to
719 // deallocate the data entirely. See the discussion in Arc::drop() about
720 // the memory orderings
722 // It's not necessary to check for the locked state here, because the
723 // weak count can only be locked if there was precisely one weak ref,
724 // meaning that drop could only subsequently run ON that remaining weak
725 // ref, which can only happen after the lock is released.
726 if self.inner().weak.fetch_sub(1, Release) == 1 {
727 atomic::fence(Acquire);
728 unsafe { deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) }
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
735 /// Equality for two `Arc<T>`s.
737 /// Two `Arc<T>`s are equal if their inner value are equal.
742 /// use std::sync::Arc;
744 /// let five = Arc::new(5);
746 /// five == Arc::new(5);
748 fn eq(&self, other: &Arc<T>) -> bool {
749 *(*self) == *(*other)
752 /// Inequality for two `Arc<T>`s.
754 /// Two `Arc<T>`s are unequal if their inner value are unequal.
759 /// use std::sync::Arc;
761 /// let five = Arc::new(5);
763 /// five != Arc::new(5);
765 fn ne(&self, other: &Arc<T>) -> bool {
766 *(*self) != *(*other)
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
771 /// Partial comparison for two `Arc<T>`s.
773 /// The two are compared by calling `partial_cmp()` on their inner values.
778 /// use std::sync::Arc;
780 /// let five = Arc::new(5);
782 /// five.partial_cmp(&Arc::new(5));
784 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
785 (**self).partial_cmp(&**other)
788 /// Less-than comparison for two `Arc<T>`s.
790 /// The two are compared by calling `<` on their inner values.
795 /// use std::sync::Arc;
797 /// let five = Arc::new(5);
799 /// five < Arc::new(5);
801 fn lt(&self, other: &Arc<T>) -> bool {
805 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
807 /// The two are compared by calling `<=` on their inner values.
812 /// use std::sync::Arc;
814 /// let five = Arc::new(5);
816 /// five <= Arc::new(5);
818 fn le(&self, other: &Arc<T>) -> bool {
819 *(*self) <= *(*other)
822 /// Greater-than comparison for two `Arc<T>`s.
824 /// The two are compared by calling `>` on their inner values.
829 /// use std::sync::Arc;
831 /// let five = Arc::new(5);
833 /// five > Arc::new(5);
835 fn gt(&self, other: &Arc<T>) -> bool {
839 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
841 /// The two are compared by calling `>=` on their inner values.
846 /// use std::sync::Arc;
848 /// let five = Arc::new(5);
850 /// five >= Arc::new(5);
852 fn ge(&self, other: &Arc<T>) -> bool {
853 *(*self) >= *(*other)
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl<T: ?Sized + Ord> Ord for Arc<T> {
858 fn cmp(&self, other: &Arc<T>) -> Ordering {
859 (**self).cmp(&**other)
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<T: ?Sized + Eq> Eq for Arc<T> {}
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868 fmt::Display::fmt(&**self, f)
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 fmt::Debug::fmt(&**self, f)
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<T> fmt::Pointer for Arc<T> {
881 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 fmt::Pointer::fmt(&*self._ptr, f)
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<T: Default> Default for Arc<T> {
888 fn default() -> Arc<T> {
889 Arc::new(Default::default())
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<T: ?Sized + Hash> Hash for Arc<T> {
895 fn hash<H: Hasher>(&self, state: &mut H) {
900 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
901 impl<T> From<T> for Arc<T> {
902 fn from(t: T) -> Self {
909 use std::clone::Clone;
910 use std::sync::mpsc::channel;
913 use std::option::Option;
914 use std::option::Option::{Some, None};
915 use std::sync::atomic;
916 use std::sync::atomic::Ordering::{Acquire, SeqCst};
919 use super::{Arc, Weak};
920 use std::sync::Mutex;
921 use std::convert::From;
923 struct Canary(*mut atomic::AtomicUsize);
925 impl Drop for Canary {
930 (*c).fetch_add(1, SeqCst);
938 fn manually_share_arc() {
939 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
940 let arc_v = Arc::new(v);
942 let (tx, rx) = channel();
944 let _t = thread::spawn(move || {
945 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
946 assert_eq!((*arc_v)[3], 4);
949 tx.send(arc_v.clone()).unwrap();
951 assert_eq!((*arc_v)[2], 3);
952 assert_eq!((*arc_v)[4], 5);
956 fn test_arc_get_mut() {
957 let mut x = Arc::new(3);
958 *Arc::get_mut(&mut x).unwrap() = 4;
961 assert!(Arc::get_mut(&mut x).is_none());
963 assert!(Arc::get_mut(&mut x).is_some());
964 let _w = Arc::downgrade(&x);
965 assert!(Arc::get_mut(&mut x).is_none());
971 assert_eq!(Arc::try_unwrap(x), Ok(3));
974 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
976 let _w = Arc::downgrade(&x);
977 assert_eq!(Arc::try_unwrap(x), Ok(5));
981 fn test_cowarc_clone_make_mut() {
982 let mut cow0 = Arc::new(75);
983 let mut cow1 = cow0.clone();
984 let mut cow2 = cow1.clone();
986 assert!(75 == *Arc::make_mut(&mut cow0));
987 assert!(75 == *Arc::make_mut(&mut cow1));
988 assert!(75 == *Arc::make_mut(&mut cow2));
990 *Arc::make_mut(&mut cow0) += 1;
991 *Arc::make_mut(&mut cow1) += 2;
992 *Arc::make_mut(&mut cow2) += 3;
994 assert!(76 == *cow0);
995 assert!(77 == *cow1);
996 assert!(78 == *cow2);
998 // none should point to the same backing memory
999 assert!(*cow0 != *cow1);
1000 assert!(*cow0 != *cow2);
1001 assert!(*cow1 != *cow2);
1005 fn test_cowarc_clone_unique2() {
1006 let mut cow0 = Arc::new(75);
1007 let cow1 = cow0.clone();
1008 let cow2 = cow1.clone();
1010 assert!(75 == *cow0);
1011 assert!(75 == *cow1);
1012 assert!(75 == *cow2);
1014 *Arc::make_mut(&mut cow0) += 1;
1015 assert!(76 == *cow0);
1016 assert!(75 == *cow1);
1017 assert!(75 == *cow2);
1019 // cow1 and cow2 should share the same contents
1020 // cow0 should have a unique reference
1021 assert!(*cow0 != *cow1);
1022 assert!(*cow0 != *cow2);
1023 assert!(*cow1 == *cow2);
1027 fn test_cowarc_clone_weak() {
1028 let mut cow0 = Arc::new(75);
1029 let cow1_weak = Arc::downgrade(&cow0);
1031 assert!(75 == *cow0);
1032 assert!(75 == *cow1_weak.upgrade().unwrap());
1034 *Arc::make_mut(&mut cow0) += 1;
1036 assert!(76 == *cow0);
1037 assert!(cow1_weak.upgrade().is_none());
1042 let x = Arc::new(5);
1043 let y = Arc::downgrade(&x);
1044 assert!(y.upgrade().is_some());
1049 let x = Arc::new(5);
1050 let y = Arc::downgrade(&x);
1052 assert!(y.upgrade().is_none());
1056 fn weak_self_cyclic() {
1058 x: Mutex<Option<Weak<Cycle>>>,
1061 let a = Arc::new(Cycle { x: Mutex::new(None) });
1062 let b = Arc::downgrade(&a.clone());
1063 *a.x.lock().unwrap() = Some(b);
1065 // hopefully we don't double-free (or leak)...
1070 let mut canary = atomic::AtomicUsize::new(0);
1071 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1073 assert!(canary.load(Acquire) == 1);
1077 fn drop_arc_weak() {
1078 let mut canary = atomic::AtomicUsize::new(0);
1079 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1080 let arc_weak = Arc::downgrade(&arc);
1081 assert!(canary.load(Acquire) == 0);
1083 assert!(canary.load(Acquire) == 1);
1088 fn test_strong_count() {
1089 let a = Arc::new(0u32);
1090 assert!(Arc::strong_count(&a) == 1);
1091 let w = Arc::downgrade(&a);
1092 assert!(Arc::strong_count(&a) == 1);
1093 let b = w.upgrade().expect("");
1094 assert!(Arc::strong_count(&b) == 2);
1095 assert!(Arc::strong_count(&a) == 2);
1098 assert!(Arc::strong_count(&b) == 1);
1100 assert!(Arc::strong_count(&b) == 2);
1101 assert!(Arc::strong_count(&c) == 2);
1105 fn test_weak_count() {
1106 let a = Arc::new(0u32);
1107 assert!(Arc::strong_count(&a) == 1);
1108 assert!(Arc::weak_count(&a) == 0);
1109 let w = Arc::downgrade(&a);
1110 assert!(Arc::strong_count(&a) == 1);
1111 assert!(Arc::weak_count(&a) == 1);
1113 assert!(Arc::weak_count(&a) == 2);
1116 assert!(Arc::strong_count(&a) == 1);
1117 assert!(Arc::weak_count(&a) == 0);
1119 assert!(Arc::strong_count(&a) == 2);
1120 assert!(Arc::weak_count(&a) == 0);
1121 let d = Arc::downgrade(&c);
1122 assert!(Arc::weak_count(&c) == 1);
1123 assert!(Arc::strong_count(&c) == 2);
1132 let a = Arc::new(5u32);
1133 assert_eq!(format!("{:?}", a), "5");
1136 // Make sure deriving works with Arc<T>
1137 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1144 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1145 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1146 let y = Arc::downgrade(&x.clone());
1148 assert!(y.upgrade().is_none());
1152 fn test_from_owned() {
1154 let foo_arc = Arc::from(foo);
1155 assert!(123 == *foo_arc);
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1161 fn borrow(&self) -> &T {
1166 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1167 impl<T: ?Sized> AsRef<T> for Arc<T> {
1168 fn as_ref(&self) -> &T {