]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
Auto merge of #22573 - nwin:impl-debug-rwlock-weak, r=Manishearth
[rust.git] / src / liballoc / arc.rs
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.
4 //
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.
10
11 #![stable(feature = "rust1", since = "1.0.0")]
12
13 //! Threadsafe reference-counted boxes (the `Arc<T>` type).
14 //!
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.
18 //!
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.
23 //!
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.
27 //!
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.
31 //!
32 //! # Examples
33 //!
34 //! Sharing some immutable data between tasks:
35 //!
36 //! ```
37 //! use std::sync::Arc;
38 //! use std::thread;
39 //!
40 //! let five = Arc::new(5);
41 //!
42 //! for _ in 0..10 {
43 //!     let five = five.clone();
44 //!
45 //!     thread::spawn(move || {
46 //!         println!("{:?}", five);
47 //!     });
48 //! }
49 //! ```
50 //!
51 //! Sharing mutable data safely between tasks with a `Mutex`:
52 //!
53 //! ```
54 //! use std::sync::{Arc, Mutex};
55 //! use std::thread;
56 //!
57 //! let five = Arc::new(Mutex::new(5));
58 //!
59 //! for _ in 0..10 {
60 //!     let five = five.clone();
61 //!
62 //!     thread::spawn(move || {
63 //!         let mut number = five.lock().unwrap();
64 //!
65 //!         *number += 1;
66 //!
67 //!         println!("{}", *number); // prints 6
68 //!     });
69 //! }
70 //! ```
71
72 use core::prelude::*;
73
74 use core::atomic;
75 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
76 use core::fmt;
77 use core::cmp::{Ordering};
78 use core::default::Default;
79 use core::mem::{min_align_of, size_of};
80 use core::mem;
81 use core::nonzero::NonZero;
82 use core::ops::Deref;
83 use core::ptr;
84 use core::hash::{Hash, Hasher};
85 use heap::deallocate;
86
87 /// An atomically reference counted wrapper for shared state.
88 ///
89 /// # Example
90 ///
91 /// In this example, a large vector of floats is shared between several tasks.
92 /// With simple pipes, without `Arc`, a copy would have to be made for each
93 /// task.
94 ///
95 /// ```rust
96 /// use std::sync::Arc;
97 /// use std::thread;
98 ///
99 /// fn main() {
100 ///     let numbers: Vec<_> = (0..100u32).map(|i| i as f32).collect();
101 ///     let shared_numbers = Arc::new(numbers);
102 ///
103 ///     for _ in 0..10 {
104 ///         let child_numbers = shared_numbers.clone();
105 ///
106 ///         thread::spawn(move || {
107 ///             let local_numbers = child_numbers.as_slice();
108 ///
109 ///             // Work with the local numbers
110 ///         });
111 ///     }
112 /// }
113 /// ```
114 #[unsafe_no_drop_flag]
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub struct Arc<T> {
117     // FIXME #12808: strange name to try to avoid interfering with
118     // field accesses of the contained type via Deref
119     _ptr: NonZero<*mut ArcInner<T>>,
120 }
121
122 unsafe impl<T: Sync + Send> Send for Arc<T> { }
123 unsafe impl<T: Sync + Send> Sync for Arc<T> { }
124
125
126 /// A weak pointer to an `Arc`.
127 ///
128 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be used to break cycles
129 /// between `Arc` pointers.
130 #[unsafe_no_drop_flag]
131 #[unstable(feature = "alloc",
132            reason = "Weak pointers may not belong in this module.")]
133 pub struct Weak<T> {
134     // FIXME #12808: strange name to try to avoid interfering with
135     // field accesses of the contained type via Deref
136     _ptr: NonZero<*mut ArcInner<T>>,
137 }
138
139 unsafe impl<T: Sync + Send> Send for Weak<T> { }
140 unsafe impl<T: Sync + Send> Sync for Weak<T> { }
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
144     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145         write!(f, "(Weak)")
146     }
147 }
148
149 struct ArcInner<T> {
150     strong: atomic::AtomicUsize,
151     weak: atomic::AtomicUsize,
152     data: T,
153 }
154
155 unsafe impl<T: Sync + Send> Send for ArcInner<T> {}
156 unsafe impl<T: Sync + Send> Sync for ArcInner<T> {}
157
158 impl<T> Arc<T> {
159     /// Constructs a new `Arc<T>`.
160     ///
161     /// # Examples
162     ///
163     /// ```
164     /// use std::sync::Arc;
165     ///
166     /// let five = Arc::new(5);
167     /// ```
168     #[inline]
169     #[stable(feature = "rust1", since = "1.0.0")]
170     pub fn new(data: T) -> Arc<T> {
171         // Start the weak pointer count as 1 which is the weak pointer that's
172         // held by all the strong pointers (kinda), see std/rc.rs for more info
173         let x = box ArcInner {
174             strong: atomic::AtomicUsize::new(1),
175             weak: atomic::AtomicUsize::new(1),
176             data: data,
177         };
178         Arc { _ptr: unsafe { NonZero::new(mem::transmute(x)) } }
179     }
180
181     /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
182     ///
183     /// # Examples
184     ///
185     /// ```
186     /// use std::sync::Arc;
187     ///
188     /// let five = Arc::new(5);
189     ///
190     /// let weak_five = five.downgrade();
191     /// ```
192     #[unstable(feature = "alloc",
193                reason = "Weak pointers may not belong in this module.")]
194     pub fn downgrade(&self) -> Weak<T> {
195         // See the clone() impl for why this is relaxed
196         self.inner().weak.fetch_add(1, Relaxed);
197         Weak { _ptr: self._ptr }
198     }
199 }
200
201 impl<T> Arc<T> {
202     #[inline]
203     fn inner(&self) -> &ArcInner<T> {
204         // This unsafety is ok because while this arc is alive we're guaranteed that the inner
205         // pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
206         // because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
207         // to these contents.
208         unsafe { &**self._ptr }
209     }
210 }
211
212 /// Get the number of weak references to this value.
213 #[inline]
214 #[unstable(feature = "alloc")]
215 pub fn weak_count<T>(this: &Arc<T>) -> usize { this.inner().weak.load(SeqCst) - 1 }
216
217 /// Get the number of strong references to this value.
218 #[inline]
219 #[unstable(feature = "alloc")]
220 pub fn strong_count<T>(this: &Arc<T>) -> usize { this.inner().strong.load(SeqCst) }
221
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<T> Clone for Arc<T> {
224     /// Makes a clone of the `Arc<T>`.
225     ///
226     /// This increases the strong reference count.
227     ///
228     /// # Examples
229     ///
230     /// ```
231     /// use std::sync::Arc;
232     ///
233     /// let five = Arc::new(5);
234     ///
235     /// five.clone();
236     /// ```
237     #[inline]
238     fn clone(&self) -> Arc<T> {
239         // Using a relaxed ordering is alright here, as knowledge of the original reference
240         // prevents other threads from erroneously deleting the object.
241         //
242         // As explained in the [Boost documentation][1], Increasing the reference counter can
243         // always be done with memory_order_relaxed: New references to an object can only be formed
244         // from an existing reference, and passing an existing reference from one thread to another
245         // must already provide any required synchronization.
246         //
247         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
248         self.inner().strong.fetch_add(1, Relaxed);
249         Arc { _ptr: self._ptr }
250     }
251 }
252
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<T> Deref for Arc<T> {
255     type Target = T;
256
257     #[inline]
258     fn deref(&self) -> &T {
259         &self.inner().data
260     }
261 }
262
263 impl<T: Send + Sync + Clone> Arc<T> {
264     /// Make a mutable reference from the given `Arc<T>`.
265     ///
266     /// This is also referred to as a copy-on-write operation because the inner data is cloned if
267     /// the reference count is greater than one.
268     ///
269     /// # Examples
270     ///
271     /// ```
272     /// use std::sync::Arc;
273     ///
274     /// let mut five = Arc::new(5);
275     ///
276     /// let mut_five = five.make_unique();
277     /// ```
278     #[inline]
279     #[unstable(feature = "alloc")]
280     pub fn make_unique(&mut self) -> &mut T {
281         // Note that we hold a strong reference, which also counts as a weak reference, so we only
282         // clone if there is an additional reference of either kind.
283         if self.inner().strong.load(SeqCst) != 1 ||
284            self.inner().weak.load(SeqCst) != 1 {
285             *self = Arc::new((**self).clone())
286         }
287         // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
288         // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
289         // this point, and we required the Arc itself to be `mut`, so we're returning the only
290         // possible reference to the inner data.
291         let inner = unsafe { &mut **self._ptr };
292         &mut inner.data
293     }
294 }
295
296 #[unsafe_destructor]
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<T: Sync + Send> Drop for Arc<T> {
299     /// Drops the `Arc<T>`.
300     ///
301     /// This will decrement the strong reference count. If the strong reference count becomes zero
302     /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
303     ///
304     /// # Examples
305     ///
306     /// ```
307     /// use std::sync::Arc;
308     ///
309     /// {
310     ///     let five = Arc::new(5);
311     ///
312     ///     // stuff
313     ///
314     ///     drop(five); // explicit drop
315     /// }
316     /// {
317     ///     let five = Arc::new(5);
318     ///
319     ///     // stuff
320     ///
321     /// } // implicit drop
322     /// ```
323     fn drop(&mut self) {
324         // This structure has #[unsafe_no_drop_flag], so this drop glue may run more than once (but
325         // it is guaranteed to be zeroed after the first if it's run more than once)
326         let ptr = *self._ptr;
327         if ptr.is_null() { return }
328
329         // Because `fetch_sub` is already atomic, we do not need to synchronize with other threads
330         // unless we are going to delete the object. This same logic applies to the below
331         // `fetch_sub` to the `weak` count.
332         if self.inner().strong.fetch_sub(1, Release) != 1 { return }
333
334         // This fence is needed to prevent reordering of use of the data and deletion of the data.
335         // Because it is marked `Release`, the decreasing of the reference count synchronizes with
336         // this `Acquire` fence. This means that use of the data happens before decreasing the
337         // reference count, which happens before this fence, which happens before the deletion of
338         // the data.
339         //
340         // As explained in the [Boost documentation][1],
341         //
342         // > It is important to enforce any possible access to the object in one thread (through an
343         // > existing reference) to *happen before* deleting the object in a different thread. This
344         // > is achieved by a "release" operation after dropping a reference (any access to the
345         // > object through this reference must obviously happened before), and an "acquire"
346         // > operation before deleting the object.
347         //
348         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
349         atomic::fence(Acquire);
350
351         // Destroy the data at this time, even though we may not free the box allocation itself
352         // (there may still be weak pointers lying around).
353         unsafe { drop(ptr::read(&self.inner().data)); }
354
355         if self.inner().weak.fetch_sub(1, Release) == 1 {
356             atomic::fence(Acquire);
357             unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
358                                 min_align_of::<ArcInner<T>>()) }
359         }
360     }
361 }
362
363 #[unstable(feature = "alloc",
364            reason = "Weak pointers may not belong in this module.")]
365 impl<T: Sync + Send> Weak<T> {
366     /// Upgrades a weak reference to a strong reference.
367     ///
368     /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
369     ///
370     /// Returns `None` if there were no strong references and the data was destroyed.
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::sync::Arc;
376     ///
377     /// let five = Arc::new(5);
378     ///
379     /// let weak_five = five.downgrade();
380     ///
381     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
382     /// ```
383     pub fn upgrade(&self) -> Option<Arc<T>> {
384         // We use a CAS loop to increment the strong count instead of a fetch_add because once the
385         // count hits 0 is must never be above 0.
386         let inner = self.inner();
387         loop {
388             let n = inner.strong.load(SeqCst);
389             if n == 0 { return None }
390             let old = inner.strong.compare_and_swap(n, n + 1, SeqCst);
391             if old == n { return Some(Arc { _ptr: self._ptr }) }
392         }
393     }
394
395     #[inline]
396     fn inner(&self) -> &ArcInner<T> {
397         // See comments above for why this is "safe"
398         unsafe { &**self._ptr }
399     }
400 }
401
402 #[unstable(feature = "alloc",
403            reason = "Weak pointers may not belong in this module.")]
404 impl<T: Sync + Send> Clone for Weak<T> {
405     /// Makes a clone of the `Weak<T>`.
406     ///
407     /// This increases the weak reference count.
408     ///
409     /// # Examples
410     ///
411     /// ```
412     /// use std::sync::Arc;
413     ///
414     /// let weak_five = Arc::new(5).downgrade();
415     ///
416     /// weak_five.clone();
417     /// ```
418     #[inline]
419     fn clone(&self) -> Weak<T> {
420         // See comments in Arc::clone() for why this is relaxed
421         self.inner().weak.fetch_add(1, Relaxed);
422         Weak { _ptr: self._ptr }
423     }
424 }
425
426 #[unsafe_destructor]
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl<T: Sync + Send> Drop for Weak<T> {
429     /// Drops the `Weak<T>`.
430     ///
431     /// This will decrement the weak reference count.
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// use std::sync::Arc;
437     ///
438     /// {
439     ///     let five = Arc::new(5);
440     ///     let weak_five = five.downgrade();
441     ///
442     ///     // stuff
443     ///
444     ///     drop(weak_five); // explicit drop
445     /// }
446     /// {
447     ///     let five = Arc::new(5);
448     ///     let weak_five = five.downgrade();
449     ///
450     ///     // stuff
451     ///
452     /// } // implicit drop
453     /// ```
454     fn drop(&mut self) {
455         let ptr = *self._ptr;
456
457         // see comments above for why this check is here
458         if ptr.is_null() { return }
459
460         // If we find out that we were the last weak pointer, then its time to deallocate the data
461         // entirely. See the discussion in Arc::drop() about the memory orderings
462         if self.inner().weak.fetch_sub(1, Release) == 1 {
463             atomic::fence(Acquire);
464             unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
465                                 min_align_of::<ArcInner<T>>()) }
466         }
467     }
468 }
469
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: PartialEq> PartialEq for Arc<T> {
472     /// Equality for two `Arc<T>`s.
473     ///
474     /// Two `Arc<T>`s are equal if their inner value are equal.
475     ///
476     /// # Examples
477     ///
478     /// ```
479     /// use std::sync::Arc;
480     ///
481     /// let five = Arc::new(5);
482     ///
483     /// five == Arc::new(5);
484     /// ```
485     fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
486
487     /// Inequality for two `Arc<T>`s.
488     ///
489     /// Two `Arc<T>`s are unequal if their inner value are unequal.
490     ///
491     /// # Examples
492     ///
493     /// ```
494     /// use std::sync::Arc;
495     ///
496     /// let five = Arc::new(5);
497     ///
498     /// five != Arc::new(5);
499     /// ```
500     fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
501 }
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T: PartialOrd> PartialOrd for Arc<T> {
504     /// Partial comparison for two `Arc<T>`s.
505     ///
506     /// The two are compared by calling `partial_cmp()` on their inner values.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// use std::sync::Arc;
512     ///
513     /// let five = Arc::new(5);
514     ///
515     /// five.partial_cmp(&Arc::new(5));
516     /// ```
517     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
518         (**self).partial_cmp(&**other)
519     }
520
521     /// Less-than comparison for two `Arc<T>`s.
522     ///
523     /// The two are compared by calling `<` on their inner values.
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// use std::sync::Arc;
529     ///
530     /// let five = Arc::new(5);
531     ///
532     /// five < Arc::new(5);
533     /// ```
534     fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
535
536     /// 'Less-than or equal to' comparison for two `Arc<T>`s.
537     ///
538     /// The two are compared by calling `<=` on their inner values.
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// use std::sync::Arc;
544     ///
545     /// let five = Arc::new(5);
546     ///
547     /// five <= Arc::new(5);
548     /// ```
549     fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
550
551     /// Greater-than comparison for two `Arc<T>`s.
552     ///
553     /// The two are compared by calling `>` on their inner values.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// use std::sync::Arc;
559     ///
560     /// let five = Arc::new(5);
561     ///
562     /// five > Arc::new(5);
563     /// ```
564     fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
565
566     /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
567     ///
568     /// The two are compared by calling `>=` on their inner values.
569     ///
570     /// # Examples
571     ///
572     /// ```
573     /// use std::sync::Arc;
574     ///
575     /// let five = Arc::new(5);
576     ///
577     /// five >= Arc::new(5);
578     /// ```
579     fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
580 }
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T: Ord> Ord for Arc<T> {
583     fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
584 }
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl<T: Eq> Eq for Arc<T> {}
587
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl<T: fmt::Display> fmt::Display for Arc<T> {
590     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591         fmt::Display::fmt(&**self, f)
592     }
593 }
594
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl<T: fmt::Debug> fmt::Debug for Arc<T> {
597     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
598         fmt::Debug::fmt(&**self, f)
599     }
600 }
601
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl<T: Default + Sync + Send> Default for Arc<T> {
604     #[stable(feature = "rust1", since = "1.0.0")]
605     fn default() -> Arc<T> { Arc::new(Default::default()) }
606 }
607
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl<T: Hash> Hash for Arc<T> {
610     fn hash<H: Hasher>(&self, state: &mut H) {
611         (**self).hash(state)
612     }
613 }
614
615 #[cfg(test)]
616 mod tests {
617     use std::clone::Clone;
618     use std::sync::mpsc::channel;
619     use std::mem::drop;
620     use std::ops::Drop;
621     use std::option::Option;
622     use std::option::Option::{Some, None};
623     use std::sync::atomic;
624     use std::sync::atomic::Ordering::{Acquire, SeqCst};
625     use std::thread;
626     use std::vec::Vec;
627     use super::{Arc, Weak, weak_count, strong_count};
628     use std::sync::Mutex;
629
630     struct Canary(*mut atomic::AtomicUsize);
631
632     impl Drop for Canary
633     {
634         fn drop(&mut self) {
635             unsafe {
636                 match *self {
637                     Canary(c) => {
638                         (*c).fetch_add(1, SeqCst);
639                     }
640                 }
641             }
642         }
643     }
644
645     #[test]
646     fn manually_share_arc() {
647         let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
648         let arc_v = Arc::new(v);
649
650         let (tx, rx) = channel();
651
652         let _t = thread::spawn(move || {
653             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
654             assert_eq!((*arc_v)[3], 4);
655         });
656
657         tx.send(arc_v.clone()).unwrap();
658
659         assert_eq!((*arc_v)[2], 3);
660         assert_eq!((*arc_v)[4], 5);
661     }
662
663     #[test]
664     fn test_cowarc_clone_make_unique() {
665         let mut cow0 = Arc::new(75);
666         let mut cow1 = cow0.clone();
667         let mut cow2 = cow1.clone();
668
669         assert!(75 == *cow0.make_unique());
670         assert!(75 == *cow1.make_unique());
671         assert!(75 == *cow2.make_unique());
672
673         *cow0.make_unique() += 1;
674         *cow1.make_unique() += 2;
675         *cow2.make_unique() += 3;
676
677         assert!(76 == *cow0);
678         assert!(77 == *cow1);
679         assert!(78 == *cow2);
680
681         // none should point to the same backing memory
682         assert!(*cow0 != *cow1);
683         assert!(*cow0 != *cow2);
684         assert!(*cow1 != *cow2);
685     }
686
687     #[test]
688     fn test_cowarc_clone_unique2() {
689         let mut cow0 = Arc::new(75);
690         let cow1 = cow0.clone();
691         let cow2 = cow1.clone();
692
693         assert!(75 == *cow0);
694         assert!(75 == *cow1);
695         assert!(75 == *cow2);
696
697         *cow0.make_unique() += 1;
698
699         assert!(76 == *cow0);
700         assert!(75 == *cow1);
701         assert!(75 == *cow2);
702
703         // cow1 and cow2 should share the same contents
704         // cow0 should have a unique reference
705         assert!(*cow0 != *cow1);
706         assert!(*cow0 != *cow2);
707         assert!(*cow1 == *cow2);
708     }
709
710     #[test]
711     fn test_cowarc_clone_weak() {
712         let mut cow0 = Arc::new(75);
713         let cow1_weak = cow0.downgrade();
714
715         assert!(75 == *cow0);
716         assert!(75 == *cow1_weak.upgrade().unwrap());
717
718         *cow0.make_unique() += 1;
719
720         assert!(76 == *cow0);
721         assert!(cow1_weak.upgrade().is_none());
722     }
723
724     #[test]
725     fn test_live() {
726         let x = Arc::new(5);
727         let y = x.downgrade();
728         assert!(y.upgrade().is_some());
729     }
730
731     #[test]
732     fn test_dead() {
733         let x = Arc::new(5);
734         let y = x.downgrade();
735         drop(x);
736         assert!(y.upgrade().is_none());
737     }
738
739     #[test]
740     fn weak_self_cyclic() {
741         struct Cycle {
742             x: Mutex<Option<Weak<Cycle>>>
743         }
744
745         let a = Arc::new(Cycle { x: Mutex::new(None) });
746         let b = a.clone().downgrade();
747         *a.x.lock().unwrap() = Some(b);
748
749         // hopefully we don't double-free (or leak)...
750     }
751
752     #[test]
753     fn drop_arc() {
754         let mut canary = atomic::AtomicUsize::new(0);
755         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
756         drop(x);
757         assert!(canary.load(Acquire) == 1);
758     }
759
760     #[test]
761     fn drop_arc_weak() {
762         let mut canary = atomic::AtomicUsize::new(0);
763         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
764         let arc_weak = arc.downgrade();
765         assert!(canary.load(Acquire) == 0);
766         drop(arc);
767         assert!(canary.load(Acquire) == 1);
768         drop(arc_weak);
769     }
770
771     #[test]
772     fn test_strong_count() {
773         let a = Arc::new(0u32);
774         assert!(strong_count(&a) == 1);
775         let w = a.downgrade();
776         assert!(strong_count(&a) == 1);
777         let b = w.upgrade().expect("");
778         assert!(strong_count(&b) == 2);
779         assert!(strong_count(&a) == 2);
780         drop(w);
781         drop(a);
782         assert!(strong_count(&b) == 1);
783         let c = b.clone();
784         assert!(strong_count(&b) == 2);
785         assert!(strong_count(&c) == 2);
786     }
787
788     #[test]
789     fn test_weak_count() {
790         let a = Arc::new(0u32);
791         assert!(strong_count(&a) == 1);
792         assert!(weak_count(&a) == 0);
793         let w = a.downgrade();
794         assert!(strong_count(&a) == 1);
795         assert!(weak_count(&a) == 1);
796         let x = w.clone();
797         assert!(weak_count(&a) == 2);
798         drop(w);
799         drop(x);
800         assert!(strong_count(&a) == 1);
801         assert!(weak_count(&a) == 0);
802         let c = a.clone();
803         assert!(strong_count(&a) == 2);
804         assert!(weak_count(&a) == 0);
805         let d = c.downgrade();
806         assert!(weak_count(&c) == 1);
807         assert!(strong_count(&c) == 2);
808
809         drop(a);
810         drop(c);
811         drop(d);
812     }
813
814     #[test]
815     fn show_arc() {
816         let a = Arc::new(5u32);
817         assert_eq!(format!("{:?}", a), "5");
818     }
819
820     // Make sure deriving works with Arc<T>
821     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
822     struct Foo { inner: Arc<i32> }
823 }