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