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