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;
84 use core::ops::CoerceUnsized;
85 use core::ptr::{self, Shared};
87 use core::marker::Unsize;
88 use core::hash::{Hash, Hasher};
89 use core::{usize, isize};
90 use core::convert::From;
93 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
95 /// An atomically reference counted wrapper for shared state.
99 /// In this example, a large vector is shared between several threads.
100 /// With simple pipes, without `Arc`, a copy would have to be made for each
103 /// When you clone an `Arc<T>`, it will create another pointer to the data and
104 /// increase the reference counter.
107 /// use std::sync::Arc;
111 /// let numbers: Vec<_> = (0..100u32).collect();
112 /// let shared_numbers = Arc::new(numbers);
115 /// let child_numbers = shared_numbers.clone();
117 /// thread::spawn(move || {
118 /// let local_numbers = &child_numbers[..];
120 /// // Work with the local numbers
125 #[unsafe_no_drop_flag]
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub struct Arc<T: ?Sized> {
128 // FIXME #12808: strange name to try to avoid interfering with
129 // field accesses of the contained type via Deref
130 _ptr: Shared<ArcInner<T>>,
133 #[stable(feature = "rust1", since = "1.0.0")]
134 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
135 #[stable(feature = "rust1", since = "1.0.0")]
136 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
138 // remove cfg after new snapshot
140 #[unstable(feature = "coerce_unsized", issue = "27732")]
141 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
143 /// A weak pointer to an `Arc`.
145 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
146 /// used to break cycles between `Arc` pointers.
147 #[unsafe_no_drop_flag]
148 #[stable(feature = "arc_weak", since = "1.4.0")]
149 pub struct Weak<T: ?Sized> {
150 // FIXME #12808: strange name to try to avoid interfering with
151 // field accesses of the contained type via Deref
152 _ptr: Shared<ArcInner<T>>,
155 #[stable(feature = "rust1", since = "1.0.0")]
156 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
157 #[stable(feature = "rust1", since = "1.0.0")]
158 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
160 // remove cfg after new snapshot
162 #[unstable(feature = "coerce_unsized", issue = "27732")]
163 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172 struct ArcInner<T: ?Sized> {
173 strong: atomic::AtomicUsize,
175 // the value usize::MAX acts as a sentinel for temporarily "locking" the
176 // ability to upgrade weak pointers or downgrade strong ones; this is used
177 // to avoid races in `make_mut` and `get_mut`.
178 weak: atomic::AtomicUsize,
183 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
184 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
187 /// Constructs a new `Arc<T>`.
192 /// use std::sync::Arc;
194 /// let five = Arc::new(5);
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn new(data: T) -> Arc<T> {
199 // Start the weak pointer count as 1 which is the weak pointer that's
200 // held by all the strong pointers (kinda), see std/rc.rs for more info
201 let x: Box<_> = box ArcInner {
202 strong: atomic::AtomicUsize::new(1),
203 weak: atomic::AtomicUsize::new(1),
206 Arc { _ptr: unsafe { Shared::new(Box::into_raw(x)) } }
209 /// Unwraps the contained value if the `Arc<T>` has only one strong reference.
210 /// This will succeed even if there are outstanding weak references.
212 /// Otherwise, an `Err` is returned with the same `Arc<T>`.
217 /// use std::sync::Arc;
219 /// let x = Arc::new(3);
220 /// assert_eq!(Arc::try_unwrap(x), Ok(3));
222 /// let x = Arc::new(4);
223 /// let _y = x.clone();
224 /// assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
227 #[stable(feature = "arc_unique", since = "1.4.0")]
228 pub fn try_unwrap(this: Self) -> Result<T, Self> {
229 // See `drop` for why all these atomics are like this
230 if this.inner().strong.compare_and_swap(1, 0, Release) != 1 {
234 atomic::fence(Acquire);
237 let ptr = *this._ptr;
238 let elem = ptr::read(&(*ptr).data);
240 // Make a weak pointer to clean up the implicit strong-weak reference
241 let _weak = Weak { _ptr: this._ptr };
249 impl<T: ?Sized> Arc<T> {
250 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
255 /// use std::sync::Arc;
257 /// let five = Arc::new(5);
259 /// let weak_five = Arc::downgrade(&five);
261 #[stable(feature = "arc_weak", since = "1.4.0")]
262 pub fn downgrade(this: &Self) -> Weak<T> {
264 // This Relaxed is OK because we're checking the value in the CAS
266 let cur = this.inner().weak.load(Relaxed);
268 // check if the weak counter is currently "locked"; if so, spin.
269 if cur == usize::MAX {
273 // NOTE: this code currently ignores the possibility of overflow
274 // into usize::MAX; in general both Rc and Arc need to be adjusted
275 // to deal with overflow.
277 // Unlike with Clone(), we need this to be an Acquire read to
278 // synchronize with the write coming from `is_unique`, so that the
279 // events prior to that write happen before this read.
280 if this.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur {
281 return Weak { _ptr: this._ptr };
286 /// Get the number of weak references to this value.
288 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
290 pub fn weak_count(this: &Self) -> usize {
291 this.inner().weak.load(SeqCst) - 1
294 /// Get the number of strong references to this value.
296 #[unstable(feature = "arc_counts", reason = "not clearly useful, and racy",
298 pub fn strong_count(this: &Self) -> usize {
299 this.inner().strong.load(SeqCst)
303 fn inner(&self) -> &ArcInner<T> {
304 // This unsafety is ok because while this arc is alive we're guaranteed
305 // that the inner pointer is valid. Furthermore, we know that the
306 // `ArcInner` structure itself is `Sync` because the inner data is
307 // `Sync` as well, so we're ok loaning out an immutable pointer to these
309 unsafe { &**self._ptr }
312 // Non-inlined part of `drop`.
314 unsafe fn drop_slow(&mut self) {
315 let ptr = *self._ptr;
317 // Destroy the data at this time, even though we may not free the box
318 // allocation itself (there may still be weak pointers lying around).
319 ptr::drop_in_place(&mut (*ptr).data);
321 if self.inner().weak.fetch_sub(1, Release) == 1 {
322 atomic::fence(Acquire);
323 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<T: ?Sized> Clone for Arc<T> {
330 /// Makes a clone of the `Arc<T>`.
332 /// This increases the strong reference count.
337 /// use std::sync::Arc;
339 /// let five = Arc::new(5);
344 fn clone(&self) -> Arc<T> {
345 // Using a relaxed ordering is alright here, as knowledge of the
346 // original reference prevents other threads from erroneously deleting
349 // As explained in the [Boost documentation][1], Increasing the
350 // reference counter can always be done with memory_order_relaxed: New
351 // references to an object can only be formed from an existing
352 // reference, and passing an existing reference from one thread to
353 // another must already provide any required synchronization.
355 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
356 let old_size = self.inner().strong.fetch_add(1, Relaxed);
358 // However we need to guard against massive refcounts in case someone
359 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
360 // and users will use-after free. We racily saturate to `isize::MAX` on
361 // the assumption that there aren't ~2 billion threads incrementing
362 // the reference count at once. This branch will never be taken in
363 // any realistic program.
365 // We abort because such a program is incredibly degenerate, and we
366 // don't care to support it.
367 if old_size > MAX_REFCOUNT {
373 Arc { _ptr: self._ptr }
377 #[stable(feature = "rust1", since = "1.0.0")]
378 impl<T: ?Sized> Deref for Arc<T> {
382 fn deref(&self) -> &T {
387 impl<T: Clone> Arc<T> {
388 #[unstable(feature = "arc_make_unique", reason = "renamed to Arc::make_mut",
390 #[deprecated(since = "1.4.0", reason = "renamed to Arc::make_mut")]
391 pub fn make_unique(this: &mut Self) -> &mut T {
395 /// Make a mutable reference into the given `Arc<T>` by cloning the inner
396 /// data if the `Arc<T>` doesn't have one strong reference and no weak
399 /// This is also referred to as a copy-on-write.
404 /// use std::sync::Arc;
406 /// let mut data = Arc::new(5);
408 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
409 /// let mut other_data = data.clone(); // Won't clone inner data
410 /// *Arc::make_mut(&mut data) += 1; // Clones inner data
411 /// *Arc::make_mut(&mut data) += 1; // Won't clone anything
412 /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything
414 /// // Note: data and other_data now point to different numbers
415 /// assert_eq!(*data, 8);
416 /// assert_eq!(*other_data, 12);
420 #[stable(feature = "arc_unique", since = "1.4.0")]
421 pub fn make_mut(this: &mut Self) -> &mut T {
422 // Note that we hold both a strong reference and a weak reference.
423 // Thus, releasing our strong reference only will not, by itself, cause
424 // the memory to be deallocated.
426 // Use Acquire to ensure that we see any writes to `weak` that happen
427 // before release writes (i.e., decrements) to `strong`. Since we hold a
428 // weak count, there's no chance the ArcInner itself could be
430 if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
431 // Another srong pointer exists; clone
432 *this = Arc::new((**this).clone());
433 } else if this.inner().weak.load(Relaxed) != 1 {
434 // Relaxed suffices in the above because this is fundamentally an
435 // optimization: we are always racing with weak pointers being
436 // dropped. Worst case, we end up allocated a new Arc unnecessarily.
438 // We removed the last strong ref, but there are additional weak
439 // refs remaining. We'll move the contents to a new Arc, and
440 // invalidate the other weak refs.
442 // Note that it is not possible for the read of `weak` to yield
443 // usize::MAX (i.e., locked), since the weak count can only be
444 // locked by a thread with a strong reference.
446 // Materialize our own implicit weak pointer, so that it can clean
447 // up the ArcInner as needed.
448 let weak = Weak { _ptr: this._ptr };
450 // mark the data itself as already deallocated
452 // there is no data race in the implicit write caused by `read`
453 // here (due to zeroing) because data is no longer accessed by
454 // other threads (due to there being no more strong refs at this
456 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
457 mem::swap(this, &mut swap);
461 // We were the sole reference of either kind; bump back up the
463 this.inner().strong.store(1, Release);
466 // As with `get_mut()`, the unsafety is ok because our reference was
467 // either unique to begin with, or became one upon cloning the contents.
469 let inner = &mut **this._ptr;
475 impl<T: ?Sized> Arc<T> {
476 /// Returns a mutable reference to the contained value if the `Arc<T>` has
477 /// one strong reference and no weak references.
482 /// use std::sync::Arc;
484 /// let mut x = Arc::new(3);
485 /// *Arc::get_mut(&mut x).unwrap() = 4;
486 /// assert_eq!(*x, 4);
488 /// let _y = x.clone();
489 /// assert!(Arc::get_mut(&mut x).is_none());
492 #[stable(feature = "arc_unique", since = "1.4.0")]
493 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
494 if this.is_unique() {
495 // This unsafety is ok because we're guaranteed that the pointer
496 // returned is the *only* pointer that will ever be returned to T. Our
497 // reference count is guaranteed to be 1 at this point, and we required
498 // the Arc itself to be `mut`, so we're returning the only possible
499 // reference to the inner data.
501 let inner = &mut **this._ptr;
502 Some(&mut inner.data)
509 /// Determine whether this is the unique reference (including weak refs) to
510 /// the underlying data.
512 /// Note that this requires locking the weak ref count.
513 fn is_unique(&mut self) -> bool {
514 // lock the weak pointer count if we appear to be the sole weak pointer
517 // The acquire label here ensures a happens-before relationship with any
518 // writes to `strong` prior to decrements of the `weak` count (via drop,
519 // which uses Release).
520 if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
521 // Due to the previous acquire read, this will observe any writes to
522 // `strong` that were due to upgrading weak pointers; only strong
523 // clones remain, which require that the strong count is > 1 anyway.
524 let unique = self.inner().strong.load(Relaxed) == 1;
526 // The release write here synchronizes with a read in `downgrade`,
527 // effectively preventing the above read of `strong` from happening
529 self.inner().weak.store(1, Release); // release the lock
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T: ?Sized> Drop for Arc<T> {
539 /// Drops the `Arc<T>`.
541 /// This will decrement the strong reference count. If the strong reference
542 /// count becomes zero and the only other references are `Weak<T>` ones,
543 /// `drop`s the inner value.
548 /// use std::sync::Arc;
551 /// let five = Arc::new(5);
555 /// drop(five); // explicit drop
558 /// let five = Arc::new(5);
562 /// } // implicit drop
564 #[unsafe_destructor_blind_to_params]
567 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
568 // more than once (but it is guaranteed to be zeroed after the first if
569 // it's run more than once)
570 let ptr = *self._ptr;
571 // if ptr.is_null() { return }
572 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
576 // Because `fetch_sub` is already atomic, we do not need to synchronize
577 // with other threads unless we are going to delete the object. This
578 // same logic applies to the below `fetch_sub` to the `weak` count.
579 if self.inner().strong.fetch_sub(1, Release) != 1 {
583 // This fence is needed to prevent reordering of use of the data and
584 // deletion of the data. Because it is marked `Release`, the decreasing
585 // of the reference count synchronizes with this `Acquire` fence. This
586 // means that use of the data happens before decreasing the reference
587 // count, which happens before this fence, which happens before the
588 // deletion of the data.
590 // As explained in the [Boost documentation][1],
592 // > It is important to enforce any possible access to the object in one
593 // > thread (through an existing reference) to *happen before* deleting
594 // > the object in a different thread. This is achieved by a "release"
595 // > operation after dropping a reference (any access to the object
596 // > through this reference must obviously happened before), and an
597 // > "acquire" operation before deleting the object.
599 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
600 atomic::fence(Acquire);
608 impl<T: ?Sized> Weak<T> {
609 /// Upgrades a weak reference to a strong reference.
611 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
613 /// Returns `None` if there were no strong references and the data was
619 /// use std::sync::Arc;
621 /// let five = Arc::new(5);
623 /// let weak_five = Arc::downgrade(&five);
625 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
627 #[stable(feature = "arc_weak", since = "1.4.0")]
628 pub fn upgrade(&self) -> Option<Arc<T>> {
629 // We use a CAS loop to increment the strong count instead of a
630 // fetch_add because once the count hits 0 it must never be above 0.
631 let inner = self.inner();
633 // Relaxed load because any write of 0 that we can observe
634 // leaves the field in a permanently zero state (so a
635 // "stale" read of 0 is fine), and any other value is
636 // confirmed via the CAS below.
637 let n = inner.strong.load(Relaxed);
642 // Relaxed is valid for the same reason it is on Arc's Clone impl
643 let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
645 return Some(Arc { _ptr: self._ptr });
651 fn inner(&self) -> &ArcInner<T> {
652 // See comments above for why this is "safe"
653 unsafe { &**self._ptr }
657 #[stable(feature = "arc_weak", since = "1.4.0")]
658 impl<T: ?Sized> Clone for Weak<T> {
659 /// Makes a clone of the `Weak<T>`.
661 /// This increases the weak reference count.
666 /// use std::sync::Arc;
668 /// let weak_five = Arc::downgrade(&Arc::new(5));
670 /// weak_five.clone();
673 fn clone(&self) -> Weak<T> {
674 // See comments in Arc::clone() for why this is relaxed. This can use a
675 // fetch_add (ignoring the lock) because the weak count is only locked
676 // where are *no other* weak pointers in existence. (So we can't be
677 // running this code in that case).
678 let old_size = self.inner().weak.fetch_add(1, Relaxed);
680 // See comments in Arc::clone() for why we do this (for mem::forget).
681 if old_size > MAX_REFCOUNT {
687 return Weak { _ptr: self._ptr };
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T: ?Sized> Drop for Weak<T> {
693 /// Drops the `Weak<T>`.
695 /// This will decrement the weak reference count.
700 /// use std::sync::Arc;
703 /// let five = Arc::new(5);
704 /// let weak_five = Arc::downgrade(&five);
708 /// drop(weak_five); // explicit drop
711 /// let five = Arc::new(5);
712 /// let weak_five = Arc::downgrade(&five);
716 /// } // implicit drop
719 let ptr = *self._ptr;
721 // see comments above for why this check is here
722 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
726 // If we find out that we were the last weak pointer, then its time to
727 // deallocate the data entirely. See the discussion in Arc::drop() about
728 // the memory orderings
730 // It's not necessary to check for the locked state here, because the
731 // weak count can only be locked if there was precisely one weak ref,
732 // meaning that drop could only subsequently run ON that remaining weak
733 // ref, which can only happen after the lock is released.
734 if self.inner().weak.fetch_sub(1, Release) == 1 {
735 atomic::fence(Acquire);
736 unsafe { deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) }
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
743 /// Equality for two `Arc<T>`s.
745 /// Two `Arc<T>`s are equal if their inner value are equal.
750 /// use std::sync::Arc;
752 /// let five = Arc::new(5);
754 /// five == Arc::new(5);
756 fn eq(&self, other: &Arc<T>) -> bool {
757 *(*self) == *(*other)
760 /// Inequality for two `Arc<T>`s.
762 /// Two `Arc<T>`s are unequal if their inner value are unequal.
767 /// use std::sync::Arc;
769 /// let five = Arc::new(5);
771 /// five != Arc::new(5);
773 fn ne(&self, other: &Arc<T>) -> bool {
774 *(*self) != *(*other)
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
779 /// Partial comparison for two `Arc<T>`s.
781 /// The two are compared by calling `partial_cmp()` on their inner values.
786 /// use std::sync::Arc;
788 /// let five = Arc::new(5);
790 /// five.partial_cmp(&Arc::new(5));
792 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
793 (**self).partial_cmp(&**other)
796 /// Less-than comparison for two `Arc<T>`s.
798 /// The two are compared by calling `<` on their inner values.
803 /// use std::sync::Arc;
805 /// let five = Arc::new(5);
807 /// five < Arc::new(5);
809 fn lt(&self, other: &Arc<T>) -> bool {
813 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
815 /// The two are compared by calling `<=` on their inner values.
820 /// use std::sync::Arc;
822 /// let five = Arc::new(5);
824 /// five <= Arc::new(5);
826 fn le(&self, other: &Arc<T>) -> bool {
827 *(*self) <= *(*other)
830 /// Greater-than comparison for two `Arc<T>`s.
832 /// The two are compared by calling `>` on their inner values.
837 /// use std::sync::Arc;
839 /// let five = Arc::new(5);
841 /// five > Arc::new(5);
843 fn gt(&self, other: &Arc<T>) -> bool {
847 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
849 /// The two are compared by calling `>=` on their inner values.
854 /// use std::sync::Arc;
856 /// let five = Arc::new(5);
858 /// five >= Arc::new(5);
860 fn ge(&self, other: &Arc<T>) -> bool {
861 *(*self) >= *(*other)
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<T: ?Sized + Ord> Ord for Arc<T> {
866 fn cmp(&self, other: &Arc<T>) -> Ordering {
867 (**self).cmp(&**other)
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl<T: ?Sized + Eq> Eq for Arc<T> {}
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
875 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
876 fmt::Display::fmt(&**self, f)
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
882 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883 fmt::Debug::fmt(&**self, f)
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<T> fmt::Pointer for Arc<T> {
889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
890 fmt::Pointer::fmt(&*self._ptr, f)
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<T: Default> Default for Arc<T> {
896 fn default() -> Arc<T> {
897 Arc::new(Default::default())
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<T: ?Sized + Hash> Hash for Arc<T> {
903 fn hash<H: Hasher>(&self, state: &mut H) {
908 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
909 impl<T> From<T> for Arc<T> {
910 fn from(t: T) -> Self {
917 use std::clone::Clone;
918 use std::sync::mpsc::channel;
921 use std::option::Option;
922 use std::option::Option::{Some, None};
923 use std::sync::atomic;
924 use std::sync::atomic::Ordering::{Acquire, SeqCst};
927 use super::{Arc, Weak};
928 use std::sync::Mutex;
929 use std::convert::From;
931 struct Canary(*mut atomic::AtomicUsize);
933 impl Drop for Canary {
938 (*c).fetch_add(1, SeqCst);
946 fn manually_share_arc() {
947 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
948 let arc_v = Arc::new(v);
950 let (tx, rx) = channel();
952 let _t = thread::spawn(move || {
953 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
954 assert_eq!((*arc_v)[3], 4);
957 tx.send(arc_v.clone()).unwrap();
959 assert_eq!((*arc_v)[2], 3);
960 assert_eq!((*arc_v)[4], 5);
964 fn test_arc_get_mut() {
965 let mut x = Arc::new(3);
966 *Arc::get_mut(&mut x).unwrap() = 4;
969 assert!(Arc::get_mut(&mut x).is_none());
971 assert!(Arc::get_mut(&mut x).is_some());
972 let _w = Arc::downgrade(&x);
973 assert!(Arc::get_mut(&mut x).is_none());
979 assert_eq!(Arc::try_unwrap(x), Ok(3));
982 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
984 let _w = Arc::downgrade(&x);
985 assert_eq!(Arc::try_unwrap(x), Ok(5));
989 fn test_cowarc_clone_make_mut() {
990 let mut cow0 = Arc::new(75);
991 let mut cow1 = cow0.clone();
992 let mut cow2 = cow1.clone();
994 assert!(75 == *Arc::make_mut(&mut cow0));
995 assert!(75 == *Arc::make_mut(&mut cow1));
996 assert!(75 == *Arc::make_mut(&mut cow2));
998 *Arc::make_mut(&mut cow0) += 1;
999 *Arc::make_mut(&mut cow1) += 2;
1000 *Arc::make_mut(&mut cow2) += 3;
1002 assert!(76 == *cow0);
1003 assert!(77 == *cow1);
1004 assert!(78 == *cow2);
1006 // none should point to the same backing memory
1007 assert!(*cow0 != *cow1);
1008 assert!(*cow0 != *cow2);
1009 assert!(*cow1 != *cow2);
1013 fn test_cowarc_clone_unique2() {
1014 let mut cow0 = Arc::new(75);
1015 let cow1 = cow0.clone();
1016 let cow2 = cow1.clone();
1018 assert!(75 == *cow0);
1019 assert!(75 == *cow1);
1020 assert!(75 == *cow2);
1022 *Arc::make_mut(&mut cow0) += 1;
1023 assert!(76 == *cow0);
1024 assert!(75 == *cow1);
1025 assert!(75 == *cow2);
1027 // cow1 and cow2 should share the same contents
1028 // cow0 should have a unique reference
1029 assert!(*cow0 != *cow1);
1030 assert!(*cow0 != *cow2);
1031 assert!(*cow1 == *cow2);
1035 fn test_cowarc_clone_weak() {
1036 let mut cow0 = Arc::new(75);
1037 let cow1_weak = Arc::downgrade(&cow0);
1039 assert!(75 == *cow0);
1040 assert!(75 == *cow1_weak.upgrade().unwrap());
1042 *Arc::make_mut(&mut cow0) += 1;
1044 assert!(76 == *cow0);
1045 assert!(cow1_weak.upgrade().is_none());
1050 let x = Arc::new(5);
1051 let y = Arc::downgrade(&x);
1052 assert!(y.upgrade().is_some());
1057 let x = Arc::new(5);
1058 let y = Arc::downgrade(&x);
1060 assert!(y.upgrade().is_none());
1064 fn weak_self_cyclic() {
1066 x: Mutex<Option<Weak<Cycle>>>,
1069 let a = Arc::new(Cycle { x: Mutex::new(None) });
1070 let b = Arc::downgrade(&a.clone());
1071 *a.x.lock().unwrap() = Some(b);
1073 // hopefully we don't double-free (or leak)...
1078 let mut canary = atomic::AtomicUsize::new(0);
1079 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1081 assert!(canary.load(Acquire) == 1);
1085 fn drop_arc_weak() {
1086 let mut canary = atomic::AtomicUsize::new(0);
1087 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1088 let arc_weak = Arc::downgrade(&arc);
1089 assert!(canary.load(Acquire) == 0);
1091 assert!(canary.load(Acquire) == 1);
1096 fn test_strong_count() {
1097 let a = Arc::new(0u32);
1098 assert!(Arc::strong_count(&a) == 1);
1099 let w = Arc::downgrade(&a);
1100 assert!(Arc::strong_count(&a) == 1);
1101 let b = w.upgrade().expect("");
1102 assert!(Arc::strong_count(&b) == 2);
1103 assert!(Arc::strong_count(&a) == 2);
1106 assert!(Arc::strong_count(&b) == 1);
1108 assert!(Arc::strong_count(&b) == 2);
1109 assert!(Arc::strong_count(&c) == 2);
1113 fn test_weak_count() {
1114 let a = Arc::new(0u32);
1115 assert!(Arc::strong_count(&a) == 1);
1116 assert!(Arc::weak_count(&a) == 0);
1117 let w = Arc::downgrade(&a);
1118 assert!(Arc::strong_count(&a) == 1);
1119 assert!(Arc::weak_count(&a) == 1);
1121 assert!(Arc::weak_count(&a) == 2);
1124 assert!(Arc::strong_count(&a) == 1);
1125 assert!(Arc::weak_count(&a) == 0);
1127 assert!(Arc::strong_count(&a) == 2);
1128 assert!(Arc::weak_count(&a) == 0);
1129 let d = Arc::downgrade(&c);
1130 assert!(Arc::weak_count(&c) == 1);
1131 assert!(Arc::strong_count(&c) == 2);
1140 let a = Arc::new(5u32);
1141 assert_eq!(format!("{:?}", a), "5");
1144 // Make sure deriving works with Arc<T>
1145 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1152 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1153 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1154 let y = Arc::downgrade(&x.clone());
1156 assert!(y.upgrade().is_none());
1160 fn test_from_owned() {
1162 let foo_arc = Arc::from(foo);
1163 assert!(123 == *foo_arc);
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1169 fn borrow(&self) -> &T {
1174 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1175 impl<T: ?Sized> AsRef<T> for Arc<T> {
1176 fn as_ref(&self) -> &T {