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
77 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
79 use core::cmp::Ordering;
80 use core::mem::{min_align_of_val, size_of_val};
81 use core::intrinsics::drop_in_place;
83 use core::nonzero::NonZero;
84 use core::ops::{Deref, CoerceUnsized};
85 use core::marker::Unsize;
86 use core::hash::{Hash, Hasher};
89 /// An atomically reference counted wrapper for shared state.
93 /// In this example, a large vector of floats is shared between several threads.
94 /// With simple pipes, without `Arc`, a copy would have to be made for each
97 /// When you clone an `Arc<T>`, it will create another pointer to the data and
98 /// increase the reference counter.
101 /// # #![feature(alloc, core)]
102 /// use std::sync::Arc;
106 /// let numbers: Vec<_> = (0..100u32).collect();
107 /// let shared_numbers = Arc::new(numbers);
110 /// let child_numbers = shared_numbers.clone();
112 /// thread::spawn(move || {
113 /// let local_numbers = &child_numbers[..];
115 /// // Work with the local numbers
120 #[unsafe_no_drop_flag]
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub struct Arc<T: ?Sized> {
123 // FIXME #12808: strange name to try to avoid interfering with
124 // field accesses of the contained type via Deref
125 _ptr: NonZero<*mut ArcInner<T>>,
128 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> { }
129 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> { }
131 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
133 /// A weak pointer to an `Arc`.
135 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
136 /// used to break cycles between `Arc` pointers.
137 #[unsafe_no_drop_flag]
138 #[unstable(feature = "alloc",
139 reason = "Weak pointers may not belong in this module.")]
140 pub struct Weak<T: ?Sized> {
141 // FIXME #12808: strange name to try to avoid interfering with
142 // field accesses of the contained type via Deref
143 _ptr: NonZero<*mut ArcInner<T>>,
146 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> { }
147 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> { }
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
151 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 struct ArcInner<T: ?Sized> {
157 strong: atomic::AtomicUsize,
158 weak: atomic::AtomicUsize,
162 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
163 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
166 /// Constructs a new `Arc<T>`.
171 /// use std::sync::Arc;
173 /// let five = Arc::new(5);
176 #[stable(feature = "rust1", since = "1.0.0")]
177 pub fn new(data: T) -> Arc<T> {
178 // Start the weak pointer count as 1 which is the weak pointer that's
179 // held by all the strong pointers (kinda), see std/rc.rs for more info
180 let x: Box<_> = box ArcInner {
181 strong: atomic::AtomicUsize::new(1),
182 weak: atomic::AtomicUsize::new(1),
185 Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
189 impl<T: ?Sized> Arc<T> {
190 /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
195 /// # #![feature(alloc)]
196 /// use std::sync::Arc;
198 /// let five = Arc::new(5);
200 /// let weak_five = five.downgrade();
202 #[unstable(feature = "alloc",
203 reason = "Weak pointers may not belong in this module.")]
204 pub fn downgrade(&self) -> Weak<T> {
205 // See the clone() impl for why this is relaxed
206 self.inner().weak.fetch_add(1, Relaxed);
207 Weak { _ptr: self._ptr }
211 impl<T: ?Sized> Arc<T> {
213 fn inner(&self) -> &ArcInner<T> {
214 // This unsafety is ok because while this arc is alive we're guaranteed
215 // that the inner pointer is valid. Furthermore, we know that the
216 // `ArcInner` structure itself is `Sync` because the inner data is
217 // `Sync` as well, so we're ok loaning out an immutable pointer to these
219 unsafe { &**self._ptr }
222 // Non-inlined part of `drop`.
224 unsafe fn drop_slow(&mut self) {
225 let ptr = *self._ptr;
227 // Destroy the data at this time, even though we may not free the box
228 // allocation itself (there may still be weak pointers lying around).
229 drop_in_place(&mut (*ptr).data);
231 if self.inner().weak.fetch_sub(1, Release) == 1 {
232 atomic::fence(Acquire);
233 deallocate(ptr as *mut u8, size_of_val(&*ptr), min_align_of_val(&*ptr))
238 /// Get the number of weak references to this value.
240 #[unstable(feature = "alloc")]
241 pub fn weak_count<T: ?Sized>(this: &Arc<T>) -> usize { this.inner().weak.load(SeqCst) - 1 }
243 /// Get the number of strong references to this value.
245 #[unstable(feature = "alloc")]
246 pub fn strong_count<T: ?Sized>(this: &Arc<T>) -> usize { this.inner().strong.load(SeqCst) }
249 /// Returns a mutable reference to the contained value if the `Arc<T>` is unique.
251 /// Returns `None` if the `Arc<T>` is not unique.
253 /// This function is marked **unsafe** because it is racy if weak pointers
259 /// # #![feature(alloc)]
260 /// extern crate alloc;
262 /// use alloc::arc::{Arc, get_mut};
265 /// let mut x = Arc::new(3);
266 /// *get_mut(&mut x).unwrap() = 4;
267 /// assert_eq!(*x, 4);
269 /// let _y = x.clone();
270 /// assert!(get_mut(&mut x).is_none());
275 #[unstable(feature = "alloc")]
276 pub unsafe fn get_mut<T: ?Sized>(this: &mut Arc<T>) -> Option<&mut T> {
277 // FIXME(#24880) potential race with upgraded weak pointers here
278 if strong_count(this) == 1 && weak_count(this) == 0 {
279 // This unsafety is ok because we're guaranteed that the pointer
280 // returned is the *only* pointer that will ever be returned to T. Our
281 // reference count is guaranteed to be 1 at this point, and we required
282 // the Arc itself to be `mut`, so we're returning the only possible
283 // reference to the inner data.
284 let inner = &mut **this._ptr;
285 Some(&mut inner.data)
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<T: ?Sized> Clone for Arc<T> {
293 /// Makes a clone of the `Arc<T>`.
295 /// This increases the strong reference count.
300 /// # #![feature(alloc)]
301 /// use std::sync::Arc;
303 /// let five = Arc::new(5);
308 fn clone(&self) -> Arc<T> {
309 // Using a relaxed ordering is alright here, as knowledge of the
310 // original reference prevents other threads from erroneously deleting
313 // As explained in the [Boost documentation][1], Increasing the
314 // reference counter can always be done with memory_order_relaxed: New
315 // references to an object can only be formed from an existing
316 // reference, and passing an existing reference from one thread to
317 // another must already provide any required synchronization.
319 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
320 self.inner().strong.fetch_add(1, Relaxed);
321 Arc { _ptr: self._ptr }
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl<T: ?Sized> Deref for Arc<T> {
330 fn deref(&self) -> &T {
335 impl<T: Clone> Arc<T> {
336 /// Make a mutable reference from the given `Arc<T>`.
338 /// This is also referred to as a copy-on-write operation because the inner
339 /// data is cloned if the reference count is greater than one.
341 /// This method is marked **unsafe** because it is racy if weak pointers
347 /// # #![feature(alloc)]
348 /// use std::sync::Arc;
351 /// let mut five = Arc::new(5);
353 /// let mut_five = five.make_unique();
357 #[unstable(feature = "alloc")]
358 pub unsafe fn make_unique(&mut self) -> &mut T {
359 // FIXME(#24880) potential race with upgraded weak pointers here
361 // Note that we hold a strong reference, which also counts as a weak
362 // reference, so we only clone if there is an additional reference of
364 if self.inner().strong.load(SeqCst) != 1 ||
365 self.inner().weak.load(SeqCst) != 1 {
366 *self = Arc::new((**self).clone())
368 // As with `get_mut()`, the unsafety is ok because our reference was
369 // either unique to begin with, or became one upon cloning the contents.
370 let inner = &mut **self._ptr;
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl<T: ?Sized> Drop for Arc<T> {
377 /// Drops the `Arc<T>`.
379 /// This will decrement the strong reference count. If the strong reference
380 /// count becomes zero and the only other references are `Weak<T>` ones,
381 /// `drop`s the inner value.
386 /// # #![feature(alloc)]
387 /// use std::sync::Arc;
390 /// let five = Arc::new(5);
394 /// drop(five); // explicit drop
397 /// let five = Arc::new(5);
401 /// } // implicit drop
405 // This structure has #[unsafe_no_drop_flag], so this drop glue may run
406 // more than once (but it is guaranteed to be zeroed after the first if
407 // it's run more than once)
408 let ptr = *self._ptr;
409 // if ptr.is_null() { return }
410 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
414 // Because `fetch_sub` is already atomic, we do not need to synchronize
415 // with other threads unless we are going to delete the object. This
416 // same logic applies to the below `fetch_sub` to the `weak` count.
417 if self.inner().strong.fetch_sub(1, Release) != 1 { return }
419 // This fence is needed to prevent reordering of use of the data and
420 // deletion of the data. Because it is marked `Release`, the decreasing
421 // of the reference count synchronizes with this `Acquire` fence. This
422 // means that use of the data happens before decreasing the reference
423 // count, which happens before this fence, which happens before the
424 // deletion of the data.
426 // As explained in the [Boost documentation][1],
428 // > It is important to enforce any possible access to the object in one
429 // > thread (through an existing reference) to *happen before* deleting
430 // > the object in a different thread. This is achieved by a "release"
431 // > operation after dropping a reference (any access to the object
432 // > through this reference must obviously happened before), and an
433 // > "acquire" operation before deleting the object.
435 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
436 atomic::fence(Acquire);
444 #[unstable(feature = "alloc",
445 reason = "Weak pointers may not belong in this module.")]
446 impl<T: ?Sized> Weak<T> {
447 /// Upgrades a weak reference to a strong reference.
449 /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
451 /// Returns `None` if there were no strong references and the data was
457 /// # #![feature(alloc)]
458 /// use std::sync::Arc;
460 /// let five = Arc::new(5);
462 /// let weak_five = five.downgrade();
464 /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
466 pub fn upgrade(&self) -> Option<Arc<T>> {
467 // We use a CAS loop to increment the strong count instead of a
468 // fetch_add because once the count hits 0 it must never be above 0.
469 let inner = self.inner();
471 let n = inner.strong.load(SeqCst);
472 if n == 0 { return None }
473 let old = inner.strong.compare_and_swap(n, n + 1, SeqCst);
474 if old == n { return Some(Arc { _ptr: self._ptr }) }
479 fn inner(&self) -> &ArcInner<T> {
480 // See comments above for why this is "safe"
481 unsafe { &**self._ptr }
485 #[unstable(feature = "alloc",
486 reason = "Weak pointers may not belong in this module.")]
487 impl<T: ?Sized> Clone for Weak<T> {
488 /// Makes a clone of the `Weak<T>`.
490 /// This increases the weak reference count.
495 /// # #![feature(alloc)]
496 /// use std::sync::Arc;
498 /// let weak_five = Arc::new(5).downgrade();
500 /// weak_five.clone();
503 fn clone(&self) -> Weak<T> {
504 // See comments in Arc::clone() for why this is relaxed
505 self.inner().weak.fetch_add(1, Relaxed);
506 Weak { _ptr: self._ptr }
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl<T: ?Sized> Drop for Weak<T> {
512 /// Drops the `Weak<T>`.
514 /// This will decrement the weak reference count.
519 /// # #![feature(alloc)]
520 /// use std::sync::Arc;
523 /// let five = Arc::new(5);
524 /// let weak_five = five.downgrade();
528 /// drop(weak_five); // explicit drop
531 /// let five = Arc::new(5);
532 /// let weak_five = five.downgrade();
536 /// } // implicit drop
539 let ptr = *self._ptr;
541 // see comments above for why this check is here
542 if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
546 // If we find out that we were the last weak pointer, then its time to
547 // deallocate the data entirely. See the discussion in Arc::drop() about
548 // the memory orderings
549 if self.inner().weak.fetch_sub(1, Release) == 1 {
550 atomic::fence(Acquire);
551 unsafe { deallocate(ptr as *mut u8,
553 min_align_of_val(&*ptr)) }
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
560 /// Equality for two `Arc<T>`s.
562 /// Two `Arc<T>`s are equal if their inner value are equal.
567 /// use std::sync::Arc;
569 /// let five = Arc::new(5);
571 /// five == Arc::new(5);
573 fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
575 /// Inequality for two `Arc<T>`s.
577 /// Two `Arc<T>`s are unequal if their inner value are unequal.
582 /// use std::sync::Arc;
584 /// let five = Arc::new(5);
586 /// five != Arc::new(5);
588 fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
592 /// Partial comparison for two `Arc<T>`s.
594 /// The two are compared by calling `partial_cmp()` on their inner values.
599 /// use std::sync::Arc;
601 /// let five = Arc::new(5);
603 /// five.partial_cmp(&Arc::new(5));
605 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
606 (**self).partial_cmp(&**other)
609 /// Less-than comparison for two `Arc<T>`s.
611 /// The two are compared by calling `<` on their inner values.
616 /// use std::sync::Arc;
618 /// let five = Arc::new(5);
620 /// five < Arc::new(5);
622 fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
624 /// 'Less-than or equal to' comparison for two `Arc<T>`s.
626 /// The two are compared by calling `<=` on their inner values.
631 /// use std::sync::Arc;
633 /// let five = Arc::new(5);
635 /// five <= Arc::new(5);
637 fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
639 /// Greater-than comparison for two `Arc<T>`s.
641 /// The two are compared by calling `>` on their inner values.
646 /// use std::sync::Arc;
648 /// let five = Arc::new(5);
650 /// five > Arc::new(5);
652 fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
654 /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
656 /// The two are compared by calling `>=` on their inner values.
661 /// use std::sync::Arc;
663 /// let five = Arc::new(5);
665 /// five >= Arc::new(5);
667 fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl<T: ?Sized + Ord> Ord for Arc<T> {
671 fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl<T: ?Sized + Eq> Eq for Arc<T> {}
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
678 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679 fmt::Display::fmt(&**self, f)
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
686 fmt::Debug::fmt(&**self, f)
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T> fmt::Pointer for Arc<T> {
692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693 fmt::Pointer::fmt(&*self._ptr, f)
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl<T: Default> Default for Arc<T> {
699 #[stable(feature = "rust1", since = "1.0.0")]
700 fn default() -> Arc<T> { Arc::new(Default::default()) }
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T: ?Sized + Hash> Hash for Arc<T> {
705 fn hash<H: Hasher>(&self, state: &mut H) {
712 use std::clone::Clone;
713 use std::sync::mpsc::channel;
716 use std::option::Option;
717 use std::option::Option::{Some, None};
718 use std::sync::atomic;
719 use std::sync::atomic::Ordering::{Acquire, SeqCst};
722 use super::{Arc, Weak, get_mut, weak_count, strong_count};
723 use std::sync::Mutex;
725 struct Canary(*mut atomic::AtomicUsize);
733 (*c).fetch_add(1, SeqCst);
741 fn manually_share_arc() {
742 let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
743 let arc_v = Arc::new(v);
745 let (tx, rx) = channel();
747 let _t = thread::spawn(move || {
748 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
749 assert_eq!((*arc_v)[3], 4);
752 tx.send(arc_v.clone()).unwrap();
754 assert_eq!((*arc_v)[2], 3);
755 assert_eq!((*arc_v)[4], 5);
759 fn test_arc_get_mut() {
761 let mut x = Arc::new(3);
762 *get_mut(&mut x).unwrap() = 4;
765 assert!(get_mut(&mut x).is_none());
767 assert!(get_mut(&mut x).is_some());
768 let _w = x.downgrade();
769 assert!(get_mut(&mut x).is_none());
774 fn test_cowarc_clone_make_unique() {
776 let mut cow0 = Arc::new(75);
777 let mut cow1 = cow0.clone();
778 let mut cow2 = cow1.clone();
780 assert!(75 == *cow0.make_unique());
781 assert!(75 == *cow1.make_unique());
782 assert!(75 == *cow2.make_unique());
784 *cow0.make_unique() += 1;
785 *cow1.make_unique() += 2;
786 *cow2.make_unique() += 3;
788 assert!(76 == *cow0);
789 assert!(77 == *cow1);
790 assert!(78 == *cow2);
792 // none should point to the same backing memory
793 assert!(*cow0 != *cow1);
794 assert!(*cow0 != *cow2);
795 assert!(*cow1 != *cow2);
800 fn test_cowarc_clone_unique2() {
801 let mut cow0 = Arc::new(75);
802 let cow1 = cow0.clone();
803 let cow2 = cow1.clone();
805 assert!(75 == *cow0);
806 assert!(75 == *cow1);
807 assert!(75 == *cow2);
810 *cow0.make_unique() += 1;
813 assert!(76 == *cow0);
814 assert!(75 == *cow1);
815 assert!(75 == *cow2);
817 // cow1 and cow2 should share the same contents
818 // cow0 should have a unique reference
819 assert!(*cow0 != *cow1);
820 assert!(*cow0 != *cow2);
821 assert!(*cow1 == *cow2);
825 fn test_cowarc_clone_weak() {
826 let mut cow0 = Arc::new(75);
827 let cow1_weak = cow0.downgrade();
829 assert!(75 == *cow0);
830 assert!(75 == *cow1_weak.upgrade().unwrap());
833 *cow0.make_unique() += 1;
836 assert!(76 == *cow0);
837 assert!(cow1_weak.upgrade().is_none());
843 let y = x.downgrade();
844 assert!(y.upgrade().is_some());
850 let y = x.downgrade();
852 assert!(y.upgrade().is_none());
856 fn weak_self_cyclic() {
858 x: Mutex<Option<Weak<Cycle>>>
861 let a = Arc::new(Cycle { x: Mutex::new(None) });
862 let b = a.clone().downgrade();
863 *a.x.lock().unwrap() = Some(b);
865 // hopefully we don't double-free (or leak)...
870 let mut canary = atomic::AtomicUsize::new(0);
871 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
873 assert!(canary.load(Acquire) == 1);
878 let mut canary = atomic::AtomicUsize::new(0);
879 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
880 let arc_weak = arc.downgrade();
881 assert!(canary.load(Acquire) == 0);
883 assert!(canary.load(Acquire) == 1);
888 fn test_strong_count() {
889 let a = Arc::new(0u32);
890 assert!(strong_count(&a) == 1);
891 let w = a.downgrade();
892 assert!(strong_count(&a) == 1);
893 let b = w.upgrade().expect("");
894 assert!(strong_count(&b) == 2);
895 assert!(strong_count(&a) == 2);
898 assert!(strong_count(&b) == 1);
900 assert!(strong_count(&b) == 2);
901 assert!(strong_count(&c) == 2);
905 fn test_weak_count() {
906 let a = Arc::new(0u32);
907 assert!(strong_count(&a) == 1);
908 assert!(weak_count(&a) == 0);
909 let w = a.downgrade();
910 assert!(strong_count(&a) == 1);
911 assert!(weak_count(&a) == 1);
913 assert!(weak_count(&a) == 2);
916 assert!(strong_count(&a) == 1);
917 assert!(weak_count(&a) == 0);
919 assert!(strong_count(&a) == 2);
920 assert!(weak_count(&a) == 0);
921 let d = c.downgrade();
922 assert!(weak_count(&c) == 1);
923 assert!(strong_count(&c) == 2);
932 let a = Arc::new(5u32);
933 assert_eq!(format!("{:?}", a), "5");
936 // Make sure deriving works with Arc<T>
937 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
938 struct Foo { inner: Arc<i32> }
942 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
943 assert_eq!(format!("{:?}", x), "[1, 2, 3]");
944 let y = x.clone().downgrade();
946 assert!(y.upgrade().is_none());