]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
Auto merge of #27630 - sylvestre:master, r=dotdash
[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 threads:
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 threads 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 #[cfg(stage0)]
75 use core::prelude::v1::*;
76
77 use core::atomic;
78 use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
79 use core::fmt;
80 use core::cmp::Ordering;
81 use core::mem::{align_of_val, size_of_val};
82 use core::intrinsics::{drop_in_place, abort};
83 use core::mem;
84 use core::nonzero::NonZero;
85 use core::ops::{Deref, CoerceUnsized};
86 use core::ptr;
87 use core::marker::Unsize;
88 use core::hash::{Hash, Hasher};
89 use core::{usize, isize};
90 use heap::deallocate;
91
92 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
93
94 /// An atomically reference counted wrapper for shared state.
95 ///
96 /// # Examples
97 ///
98 /// In this example, a large vector of floats is shared between several threads.
99 /// With simple pipes, without `Arc`, a copy would have to be made for each
100 /// thread.
101 ///
102 /// When you clone an `Arc<T>`, it will create another pointer to the data and
103 /// increase the reference counter.
104 ///
105 /// ```
106 /// use std::sync::Arc;
107 /// use std::thread;
108 ///
109 /// fn main() {
110 ///     let numbers: Vec<_> = (0..100u32).collect();
111 ///     let shared_numbers = Arc::new(numbers);
112 ///
113 ///     for _ in 0..10 {
114 ///         let child_numbers = shared_numbers.clone();
115 ///
116 ///         thread::spawn(move || {
117 ///             let local_numbers = &child_numbers[..];
118 ///
119 ///             // Work with the local numbers
120 ///         });
121 ///     }
122 /// }
123 /// ```
124 #[unsafe_no_drop_flag]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub struct Arc<T: ?Sized> {
127     // FIXME #12808: strange name to try to avoid interfering with
128     // field accesses of the contained type via Deref
129     _ptr: NonZero<*mut ArcInner<T>>,
130 }
131
132 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> { }
133 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> { }
134
135 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
136
137 /// A weak pointer to an `Arc`.
138 ///
139 /// Weak pointers will not keep the data inside of the `Arc` alive, and can be
140 /// used to break cycles between `Arc` pointers.
141 #[unsafe_no_drop_flag]
142 #[unstable(feature = "arc_weak",
143            reason = "Weak pointers may not belong in this module.")]
144 pub struct Weak<T: ?Sized> {
145     // FIXME #12808: strange name to try to avoid interfering with
146     // field accesses of the contained type via Deref
147     _ptr: NonZero<*mut ArcInner<T>>,
148 }
149
150 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> { }
151 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> { }
152
153 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
154
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
157     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158         write!(f, "(Weak)")
159     }
160 }
161
162 struct ArcInner<T: ?Sized> {
163     strong: atomic::AtomicUsize,
164
165     // the value usize::MAX acts as a sentinel for temporarily "locking" the
166     // ability to upgrade weak pointers or downgrade strong ones; this is used
167     // to avoid races in `make_unique` and `get_mut`.
168     weak: atomic::AtomicUsize,
169
170     data: T,
171 }
172
173 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
174 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
175
176 impl<T> Arc<T> {
177     /// Constructs a new `Arc<T>`.
178     ///
179     /// # Examples
180     ///
181     /// ```
182     /// use std::sync::Arc;
183     ///
184     /// let five = Arc::new(5);
185     /// ```
186     #[inline]
187     #[stable(feature = "rust1", since = "1.0.0")]
188     pub fn new(data: T) -> Arc<T> {
189         // Start the weak pointer count as 1 which is the weak pointer that's
190         // held by all the strong pointers (kinda), see std/rc.rs for more info
191         let x: Box<_> = box ArcInner {
192             strong: atomic::AtomicUsize::new(1),
193             weak: atomic::AtomicUsize::new(1),
194             data: data,
195         };
196         Arc { _ptr: unsafe { NonZero::new(Box::into_raw(x)) } }
197     }
198 }
199
200 impl<T: ?Sized> Arc<T> {
201     /// Downgrades the `Arc<T>` to a `Weak<T>` reference.
202     ///
203     /// # Examples
204     ///
205     /// ```
206     /// #![feature(arc_weak)]
207     ///
208     /// use std::sync::Arc;
209     ///
210     /// let five = Arc::new(5);
211     ///
212     /// let weak_five = five.downgrade();
213     /// ```
214     #[unstable(feature = "arc_weak",
215                reason = "Weak pointers may not belong in this module.")]
216     pub fn downgrade(&self) -> Weak<T> {
217         loop {
218             // This Relaxed is OK because we're checking the value in the CAS
219             // below.
220             let cur = self.inner().weak.load(Relaxed);
221
222             // check if the weak counter is currently "locked"; if so, spin.
223             if cur == usize::MAX { continue }
224
225             // NOTE: this code currently ignores the possibility of overflow
226             // into usize::MAX; in general both Rc and Arc need to be adjusted
227             // to deal with overflow.
228
229             // Unlike with Clone(), we need this to be an Acquire read to
230             // synchronize with the write coming from `is_unique`, so that the
231             // events prior to that write happen before this read.
232             if self.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur {
233                 return Weak { _ptr: self._ptr }
234             }
235         }
236     }
237
238     /// Get the number of weak references to this value.
239     #[inline]
240     #[unstable(feature = "arc_counts")]
241     pub fn weak_count(this: &Arc<T>) -> usize {
242         this.inner().weak.load(SeqCst) - 1
243     }
244
245     /// Get the number of strong references to this value.
246     #[inline]
247     #[unstable(feature = "arc_counts")]
248     pub fn strong_count(this: &Arc<T>) -> usize {
249         this.inner().strong.load(SeqCst)
250     }
251
252     #[inline]
253     fn inner(&self) -> &ArcInner<T> {
254         // This unsafety is ok because while this arc is alive we're guaranteed
255         // that the inner pointer is valid. Furthermore, we know that the
256         // `ArcInner` structure itself is `Sync` because the inner data is
257         // `Sync` as well, so we're ok loaning out an immutable pointer to these
258         // contents.
259         unsafe { &**self._ptr }
260     }
261
262     // Non-inlined part of `drop`.
263     #[inline(never)]
264     unsafe fn drop_slow(&mut self) {
265         let ptr = *self._ptr;
266
267         // Destroy the data at this time, even though we may not free the box
268         // allocation itself (there may still be weak pointers lying around).
269         drop_in_place(&mut (*ptr).data);
270
271         if self.inner().weak.fetch_sub(1, Release) == 1 {
272             atomic::fence(Acquire);
273             deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
274         }
275     }
276 }
277
278 /// Get the number of weak references to this value.
279 #[inline]
280 #[unstable(feature = "arc_counts")]
281 #[deprecated(since = "1.2.0", reason = "renamed to Arc::weak_count")]
282 pub fn weak_count<T: ?Sized>(this: &Arc<T>) -> usize { Arc::weak_count(this) }
283
284 /// Get the number of strong references to this value.
285 #[inline]
286 #[unstable(feature = "arc_counts")]
287 #[deprecated(since = "1.2.0", reason = "renamed to Arc::strong_count")]
288 pub fn strong_count<T: ?Sized>(this: &Arc<T>) -> usize { Arc::strong_count(this) }
289
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: ?Sized> Clone for Arc<T> {
292     /// Makes a clone of the `Arc<T>`.
293     ///
294     /// This increases the strong reference count.
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// use std::sync::Arc;
300     ///
301     /// let five = Arc::new(5);
302     ///
303     /// five.clone();
304     /// ```
305     #[inline]
306     fn clone(&self) -> Arc<T> {
307         // Using a relaxed ordering is alright here, as knowledge of the
308         // original reference prevents other threads from erroneously deleting
309         // the object.
310         //
311         // As explained in the [Boost documentation][1], Increasing the
312         // reference counter can always be done with memory_order_relaxed: New
313         // references to an object can only be formed from an existing
314         // reference, and passing an existing reference from one thread to
315         // another must already provide any required synchronization.
316         //
317         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
318         let old_size = self.inner().strong.fetch_add(1, Relaxed);
319
320         // However we need to guard against massive refcounts in case someone
321         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
322         // and users will use-after free. We racily saturate to `isize::MAX` on
323         // the assumption that there aren't ~2 billion threads incrementing
324         // the reference count at once. This branch will never be taken in
325         // any realistic program.
326         //
327         // We abort because such a program is incredibly degenerate, and we
328         // don't care to support it.
329         if old_size > MAX_REFCOUNT {
330             unsafe { abort(); }
331         }
332
333         Arc { _ptr: self._ptr }
334     }
335 }
336
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl<T: ?Sized> Deref for Arc<T> {
339     type Target = T;
340
341     #[inline]
342     fn deref(&self) -> &T {
343         &self.inner().data
344     }
345 }
346
347 impl<T: Clone> Arc<T> {
348     /// Make a mutable reference from the given `Arc<T>`.
349     ///
350     /// This is also referred to as a copy-on-write operation because the inner
351     /// data is cloned if the (strong) reference count is greater than one. If
352     /// we hold the only strong reference, any existing weak references will no
353     /// longer be upgradeable.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// #![feature(arc_unique)]
359     ///
360     /// use std::sync::Arc;
361     ///
362     /// let mut five = Arc::new(5);
363     ///
364     /// let mut_five = Arc::make_unique(&mut five);
365     /// ```
366     #[inline]
367     #[unstable(feature = "arc_unique")]
368     pub fn make_unique(this: &mut Arc<T>) -> &mut T {
369         // Note that we hold both a strong reference and a weak reference.
370         // Thus, releasing our strong reference only will not, by itself, cause
371         // the memory to be deallocated.
372         //
373         // Use Acquire to ensure that we see any writes to `weak` that happen
374         // before release writes (i.e., decrements) to `strong`. Since we hold a
375         // weak count, there's no chance the ArcInner itself could be
376         // deallocated.
377         if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
378             // Another srong pointer exists; clone
379             *this = Arc::new((**this).clone());
380         } else if this.inner().weak.load(Relaxed) != 1 {
381             // Relaxed suffices in the above because this is fundamentally an
382             // optimization: we are always racing with weak pointers being
383             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
384
385             // We removed the last strong ref, but there are additional weak
386             // refs remaining. We'll move the contents to a new Arc, and
387             // invalidate the other weak refs.
388
389             // Note that it is not possible for the read of `weak` to yield
390             // usize::MAX (i.e., locked), since the weak count can only be
391             // locked by a thread with a strong reference.
392
393             // Materialize our own implicit weak pointer, so that it can clean
394             // up the ArcInner as needed.
395             let weak = Weak { _ptr: this._ptr };
396
397             // mark the data itself as already deallocated
398             unsafe {
399                 // there is no data race in the implicit write caused by `read`
400                 // here (due to zeroing) because data is no longer accessed by
401                 // other threads (due to there being no more strong refs at this
402                 // point).
403                 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
404                 mem::swap(this, &mut swap);
405                 mem::forget(swap);
406             }
407         } else {
408             // We were the sole reference of either kind; bump back up the
409             // strong ref count.
410             this.inner().strong.store(1, Release);
411         }
412
413         // As with `get_mut()`, the unsafety is ok because our reference was
414         // either unique to begin with, or became one upon cloning the contents.
415         unsafe {
416             let inner = &mut **this._ptr;
417             &mut inner.data
418         }
419     }
420 }
421
422 impl<T: ?Sized> Arc<T> {
423     /// Returns a mutable reference to the contained value if the `Arc<T>` is unique.
424     ///
425     /// Returns `None` if the `Arc<T>` is not unique.
426     ///
427     /// # Examples
428     ///
429     /// ```
430     /// #![feature(arc_unique, alloc)]
431     ///
432     /// extern crate alloc;
433     /// # fn main() {
434     /// use alloc::arc::Arc;
435     ///
436     /// let mut x = Arc::new(3);
437     /// *Arc::get_mut(&mut x).unwrap() = 4;
438     /// assert_eq!(*x, 4);
439     ///
440     /// let _y = x.clone();
441     /// assert!(Arc::get_mut(&mut x).is_none());
442     /// # }
443     /// ```
444     #[inline]
445     #[unstable(feature = "arc_unique")]
446     pub fn get_mut(this: &mut Arc<T>) -> Option<&mut T> {
447         if this.is_unique() {
448             // This unsafety is ok because we're guaranteed that the pointer
449             // returned is the *only* pointer that will ever be returned to T. Our
450             // reference count is guaranteed to be 1 at this point, and we required
451             // the Arc itself to be `mut`, so we're returning the only possible
452             // reference to the inner data.
453             unsafe {
454                 let inner = &mut **this._ptr;
455                 Some(&mut inner.data)
456             }
457         } else {
458             None
459         }
460     }
461
462     /// Determine whether this is the unique reference (including weak refs) to
463     /// the underlying data.
464     ///
465     /// Note that this requires locking the weak ref count.
466     fn is_unique(&mut self) -> bool {
467         // lock the weak pointer count if we appear to be the sole weak pointer
468         // holder.
469         //
470         // The acquire label here ensures a happens-before relationship with any
471         // writes to `strong` prior to decrements of the `weak` count (via drop,
472         // which uses Release).
473         if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
474             // Due to the previous acquire read, this will observe any writes to
475             // `strong` that were due to upgrading weak pointers; only strong
476             // clones remain, which require that the strong count is > 1 anyway.
477             let unique = self.inner().strong.load(Relaxed) == 1;
478
479             // The release write here synchronizes with a read in `downgrade`,
480             // effectively preventing the above read of `strong` from happening
481             // after the write.
482             self.inner().weak.store(1, Release); // release the lock
483             unique
484         } else {
485             false
486         }
487     }
488 }
489
490 #[inline]
491 #[unstable(feature = "arc_unique")]
492 #[deprecated(since = "1.2", reason = "use Arc::get_mut instead")]
493 pub fn get_mut<T: ?Sized>(this: &mut Arc<T>) -> Option<&mut T> {
494     Arc::get_mut(this)
495 }
496
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: ?Sized> Drop for Arc<T> {
499     /// Drops the `Arc<T>`.
500     ///
501     /// This will decrement the strong reference count. If the strong reference
502     /// count becomes zero and the only other references are `Weak<T>` ones,
503     /// `drop`s the inner value.
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// use std::sync::Arc;
509     ///
510     /// {
511     ///     let five = Arc::new(5);
512     ///
513     ///     // stuff
514     ///
515     ///     drop(five); // explicit drop
516     /// }
517     /// {
518     ///     let five = Arc::new(5);
519     ///
520     ///     // stuff
521     ///
522     /// } // implicit drop
523     /// ```
524     #[inline]
525     fn drop(&mut self) {
526         // This structure has #[unsafe_no_drop_flag], so this drop glue may run
527         // more than once (but it is guaranteed to be zeroed after the first if
528         // it's run more than once)
529         let ptr = *self._ptr;
530         // if ptr.is_null() { return }
531         if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
532             return
533         }
534
535         // Because `fetch_sub` is already atomic, we do not need to synchronize
536         // with other threads unless we are going to delete the object. This
537         // same logic applies to the below `fetch_sub` to the `weak` count.
538         if self.inner().strong.fetch_sub(1, Release) != 1 { return }
539
540         // This fence is needed to prevent reordering of use of the data and
541         // deletion of the data.  Because it is marked `Release`, the decreasing
542         // of the reference count synchronizes with this `Acquire` fence. This
543         // means that use of the data happens before decreasing the reference
544         // count, which happens before this fence, which happens before the
545         // deletion of the data.
546         //
547         // As explained in the [Boost documentation][1],
548         //
549         // > It is important to enforce any possible access to the object in one
550         // > thread (through an existing reference) to *happen before* deleting
551         // > the object in a different thread. This is achieved by a "release"
552         // > operation after dropping a reference (any access to the object
553         // > through this reference must obviously happened before), and an
554         // > "acquire" operation before deleting the object.
555         //
556         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
557         atomic::fence(Acquire);
558
559         unsafe {
560             self.drop_slow()
561         }
562     }
563 }
564
565 #[unstable(feature = "arc_weak",
566            reason = "Weak pointers may not belong in this module.")]
567 impl<T: ?Sized> Weak<T> {
568     /// Upgrades a weak reference to a strong reference.
569     ///
570     /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
571     ///
572     /// Returns `None` if there were no strong references and the data was
573     /// destroyed.
574     ///
575     /// # Examples
576     ///
577     /// ```
578     /// #![feature(arc_weak)]
579     ///
580     /// use std::sync::Arc;
581     ///
582     /// let five = Arc::new(5);
583     ///
584     /// let weak_five = five.downgrade();
585     ///
586     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
587     /// ```
588     pub fn upgrade(&self) -> Option<Arc<T>> {
589         // We use a CAS loop to increment the strong count instead of a
590         // fetch_add because once the count hits 0 it must never be above 0.
591         let inner = self.inner();
592         loop {
593             // Relaxed load because any write of 0 that we can observe
594             // leaves the field in a permanently zero state (so a
595             // "stale" read of 0 is fine), and any other value is
596             // confirmed via the CAS below.
597             let n = inner.strong.load(Relaxed);
598             if n == 0 { return None }
599
600             // Relaxed is valid for the same reason it is on Arc's Clone impl
601             let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
602             if old == n { return Some(Arc { _ptr: self._ptr }) }
603         }
604     }
605
606     #[inline]
607     fn inner(&self) -> &ArcInner<T> {
608         // See comments above for why this is "safe"
609         unsafe { &**self._ptr }
610     }
611 }
612
613 #[unstable(feature = "arc_weak",
614            reason = "Weak pointers may not belong in this module.")]
615 impl<T: ?Sized> Clone for Weak<T> {
616     /// Makes a clone of the `Weak<T>`.
617     ///
618     /// This increases the weak reference count.
619     ///
620     /// # Examples
621     ///
622     /// ```
623     /// #![feature(arc_weak)]
624     ///
625     /// use std::sync::Arc;
626     ///
627     /// let weak_five = Arc::new(5).downgrade();
628     ///
629     /// weak_five.clone();
630     /// ```
631     #[inline]
632     fn clone(&self) -> Weak<T> {
633         // See comments in Arc::clone() for why this is relaxed.  This can use a
634         // fetch_add (ignoring the lock) because the weak count is only locked
635         // where are *no other* weak pointers in existence. (So we can't be
636         // running this code in that case).
637         let old_size = self.inner().weak.fetch_add(1, Relaxed);
638
639         // See comments in Arc::clone() for why we do this (for mem::forget).
640         if old_size > MAX_REFCOUNT {
641             unsafe { abort(); }
642         }
643
644         return Weak { _ptr: self._ptr }
645     }
646 }
647
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<T: ?Sized> Drop for Weak<T> {
650     /// Drops the `Weak<T>`.
651     ///
652     /// This will decrement the weak reference count.
653     ///
654     /// # Examples
655     ///
656     /// ```
657     /// #![feature(arc_weak)]
658     ///
659     /// use std::sync::Arc;
660     ///
661     /// {
662     ///     let five = Arc::new(5);
663     ///     let weak_five = five.downgrade();
664     ///
665     ///     // stuff
666     ///
667     ///     drop(weak_five); // explicit drop
668     /// }
669     /// {
670     ///     let five = Arc::new(5);
671     ///     let weak_five = five.downgrade();
672     ///
673     ///     // stuff
674     ///
675     /// } // implicit drop
676     /// ```
677     fn drop(&mut self) {
678         let ptr = *self._ptr;
679
680         // see comments above for why this check is here
681         if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
682             return
683         }
684
685         // If we find out that we were the last weak pointer, then its time to
686         // deallocate the data entirely. See the discussion in Arc::drop() about
687         // the memory orderings
688         //
689         // It's not necessary to check for the locked state here, because the
690         // weak count can only be locked if there was precisely one weak ref,
691         // meaning that drop could only subsequently run ON that remaining weak
692         // ref, which can only happen after the lock is released.
693         if self.inner().weak.fetch_sub(1, Release) == 1 {
694             atomic::fence(Acquire);
695             unsafe { deallocate(ptr as *mut u8,
696                                 size_of_val(&*ptr),
697                                 align_of_val(&*ptr)) }
698         }
699     }
700 }
701
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
704     /// Equality for two `Arc<T>`s.
705     ///
706     /// Two `Arc<T>`s are equal if their inner value are equal.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// use std::sync::Arc;
712     ///
713     /// let five = Arc::new(5);
714     ///
715     /// five == Arc::new(5);
716     /// ```
717     fn eq(&self, other: &Arc<T>) -> bool { *(*self) == *(*other) }
718
719     /// Inequality for two `Arc<T>`s.
720     ///
721     /// Two `Arc<T>`s are unequal if their inner value are unequal.
722     ///
723     /// # Examples
724     ///
725     /// ```
726     /// use std::sync::Arc;
727     ///
728     /// let five = Arc::new(5);
729     ///
730     /// five != Arc::new(5);
731     /// ```
732     fn ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) }
733 }
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
736     /// Partial comparison for two `Arc<T>`s.
737     ///
738     /// The two are compared by calling `partial_cmp()` on their inner values.
739     ///
740     /// # Examples
741     ///
742     /// ```
743     /// use std::sync::Arc;
744     ///
745     /// let five = Arc::new(5);
746     ///
747     /// five.partial_cmp(&Arc::new(5));
748     /// ```
749     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
750         (**self).partial_cmp(&**other)
751     }
752
753     /// Less-than comparison for two `Arc<T>`s.
754     ///
755     /// The two are compared by calling `<` on their inner values.
756     ///
757     /// # Examples
758     ///
759     /// ```
760     /// use std::sync::Arc;
761     ///
762     /// let five = Arc::new(5);
763     ///
764     /// five < Arc::new(5);
765     /// ```
766     fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) }
767
768     /// 'Less-than or equal to' comparison for two `Arc<T>`s.
769     ///
770     /// The two are compared by calling `<=` on their inner values.
771     ///
772     /// # Examples
773     ///
774     /// ```
775     /// use std::sync::Arc;
776     ///
777     /// let five = Arc::new(5);
778     ///
779     /// five <= Arc::new(5);
780     /// ```
781     fn le(&self, other: &Arc<T>) -> bool { *(*self) <= *(*other) }
782
783     /// Greater-than comparison for two `Arc<T>`s.
784     ///
785     /// The two are compared by calling `>` on their inner values.
786     ///
787     /// # Examples
788     ///
789     /// ```
790     /// use std::sync::Arc;
791     ///
792     /// let five = Arc::new(5);
793     ///
794     /// five > Arc::new(5);
795     /// ```
796     fn gt(&self, other: &Arc<T>) -> bool { *(*self) > *(*other) }
797
798     /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
799     ///
800     /// The two are compared by calling `>=` on their inner values.
801     ///
802     /// # Examples
803     ///
804     /// ```
805     /// use std::sync::Arc;
806     ///
807     /// let five = Arc::new(5);
808     ///
809     /// five >= Arc::new(5);
810     /// ```
811     fn ge(&self, other: &Arc<T>) -> bool { *(*self) >= *(*other) }
812 }
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl<T: ?Sized + Ord> Ord for Arc<T> {
815     fn cmp(&self, other: &Arc<T>) -> Ordering { (**self).cmp(&**other) }
816 }
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<T: ?Sized + Eq> Eq for Arc<T> {}
819
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
822     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
823         fmt::Display::fmt(&**self, f)
824     }
825 }
826
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
829     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
830         fmt::Debug::fmt(&**self, f)
831     }
832 }
833
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl<T> fmt::Pointer for Arc<T> {
836     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837         fmt::Pointer::fmt(&*self._ptr, f)
838     }
839 }
840
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T: Default> Default for Arc<T> {
843     #[stable(feature = "rust1", since = "1.0.0")]
844     fn default() -> Arc<T> { Arc::new(Default::default()) }
845 }
846
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<T: ?Sized + Hash> Hash for Arc<T> {
849     fn hash<H: Hasher>(&self, state: &mut H) {
850         (**self).hash(state)
851     }
852 }
853
854 #[cfg(test)]
855 mod tests {
856     use std::clone::Clone;
857     use std::sync::mpsc::channel;
858     use std::mem::drop;
859     use std::ops::Drop;
860     use std::option::Option;
861     use std::option::Option::{Some, None};
862     use std::sync::atomic;
863     use std::sync::atomic::Ordering::{Acquire, SeqCst};
864     use std::thread;
865     use std::vec::Vec;
866     use super::{Arc, Weak, get_mut, weak_count, strong_count};
867     use std::sync::Mutex;
868
869     struct Canary(*mut atomic::AtomicUsize);
870
871     impl Drop for Canary
872     {
873         fn drop(&mut self) {
874             unsafe {
875                 match *self {
876                     Canary(c) => {
877                         (*c).fetch_add(1, SeqCst);
878                     }
879                 }
880             }
881         }
882     }
883
884     #[test]
885     fn manually_share_arc() {
886         let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
887         let arc_v = Arc::new(v);
888
889         let (tx, rx) = channel();
890
891         let _t = thread::spawn(move || {
892             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
893             assert_eq!((*arc_v)[3], 4);
894         });
895
896         tx.send(arc_v.clone()).unwrap();
897
898         assert_eq!((*arc_v)[2], 3);
899         assert_eq!((*arc_v)[4], 5);
900     }
901
902     #[test]
903     fn test_arc_get_mut() {
904         unsafe {
905             let mut x = Arc::new(3);
906             *get_mut(&mut x).unwrap() = 4;
907             assert_eq!(*x, 4);
908             let y = x.clone();
909             assert!(get_mut(&mut x).is_none());
910             drop(y);
911             assert!(get_mut(&mut x).is_some());
912             let _w = x.downgrade();
913             assert!(get_mut(&mut x).is_none());
914         }
915     }
916
917     #[test]
918     fn test_cowarc_clone_make_unique() {
919         unsafe {
920             let mut cow0 = Arc::new(75);
921             let mut cow1 = cow0.clone();
922             let mut cow2 = cow1.clone();
923
924             assert!(75 == *Arc::make_unique(&mut cow0));
925             assert!(75 == *Arc::make_unique(&mut cow1));
926             assert!(75 == *Arc::make_unique(&mut cow2));
927
928             *Arc::make_unique(&mut cow0) += 1;
929             *Arc::make_unique(&mut cow1) += 2;
930             *Arc::make_unique(&mut cow2) += 3;
931
932             assert!(76 == *cow0);
933             assert!(77 == *cow1);
934             assert!(78 == *cow2);
935
936             // none should point to the same backing memory
937             assert!(*cow0 != *cow1);
938             assert!(*cow0 != *cow2);
939             assert!(*cow1 != *cow2);
940         }
941     }
942
943     #[test]
944     fn test_cowarc_clone_unique2() {
945         let mut cow0 = Arc::new(75);
946         let cow1 = cow0.clone();
947         let cow2 = cow1.clone();
948
949         assert!(75 == *cow0);
950         assert!(75 == *cow1);
951         assert!(75 == *cow2);
952
953         unsafe {
954             *Arc::make_unique(&mut cow0) += 1;
955         }
956
957         assert!(76 == *cow0);
958         assert!(75 == *cow1);
959         assert!(75 == *cow2);
960
961         // cow1 and cow2 should share the same contents
962         // cow0 should have a unique reference
963         assert!(*cow0 != *cow1);
964         assert!(*cow0 != *cow2);
965         assert!(*cow1 == *cow2);
966     }
967
968     #[test]
969     fn test_cowarc_clone_weak() {
970         let mut cow0 = Arc::new(75);
971         let cow1_weak = cow0.downgrade();
972
973         assert!(75 == *cow0);
974         assert!(75 == *cow1_weak.upgrade().unwrap());
975
976         unsafe {
977             *Arc::make_unique(&mut cow0) += 1;
978         }
979
980         assert!(76 == *cow0);
981         assert!(cow1_weak.upgrade().is_none());
982     }
983
984     #[test]
985     fn test_live() {
986         let x = Arc::new(5);
987         let y = x.downgrade();
988         assert!(y.upgrade().is_some());
989     }
990
991     #[test]
992     fn test_dead() {
993         let x = Arc::new(5);
994         let y = x.downgrade();
995         drop(x);
996         assert!(y.upgrade().is_none());
997     }
998
999     #[test]
1000     fn weak_self_cyclic() {
1001         struct Cycle {
1002             x: Mutex<Option<Weak<Cycle>>>
1003         }
1004
1005         let a = Arc::new(Cycle { x: Mutex::new(None) });
1006         let b = a.clone().downgrade();
1007         *a.x.lock().unwrap() = Some(b);
1008
1009         // hopefully we don't double-free (or leak)...
1010     }
1011
1012     #[test]
1013     fn drop_arc() {
1014         let mut canary = atomic::AtomicUsize::new(0);
1015         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1016         drop(x);
1017         assert!(canary.load(Acquire) == 1);
1018     }
1019
1020     #[test]
1021     fn drop_arc_weak() {
1022         let mut canary = atomic::AtomicUsize::new(0);
1023         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1024         let arc_weak = arc.downgrade();
1025         assert!(canary.load(Acquire) == 0);
1026         drop(arc);
1027         assert!(canary.load(Acquire) == 1);
1028         drop(arc_weak);
1029     }
1030
1031     #[test]
1032     fn test_strong_count() {
1033         let a = Arc::new(0u32);
1034         assert!(strong_count(&a) == 1);
1035         let w = a.downgrade();
1036         assert!(strong_count(&a) == 1);
1037         let b = w.upgrade().expect("");
1038         assert!(strong_count(&b) == 2);
1039         assert!(strong_count(&a) == 2);
1040         drop(w);
1041         drop(a);
1042         assert!(strong_count(&b) == 1);
1043         let c = b.clone();
1044         assert!(strong_count(&b) == 2);
1045         assert!(strong_count(&c) == 2);
1046     }
1047
1048     #[test]
1049     fn test_weak_count() {
1050         let a = Arc::new(0u32);
1051         assert!(strong_count(&a) == 1);
1052         assert!(weak_count(&a) == 0);
1053         let w = a.downgrade();
1054         assert!(strong_count(&a) == 1);
1055         assert!(weak_count(&a) == 1);
1056         let x = w.clone();
1057         assert!(weak_count(&a) == 2);
1058         drop(w);
1059         drop(x);
1060         assert!(strong_count(&a) == 1);
1061         assert!(weak_count(&a) == 0);
1062         let c = a.clone();
1063         assert!(strong_count(&a) == 2);
1064         assert!(weak_count(&a) == 0);
1065         let d = c.downgrade();
1066         assert!(weak_count(&c) == 1);
1067         assert!(strong_count(&c) == 2);
1068
1069         drop(a);
1070         drop(c);
1071         drop(d);
1072     }
1073
1074     #[test]
1075     fn show_arc() {
1076         let a = Arc::new(5u32);
1077         assert_eq!(format!("{:?}", a), "5");
1078     }
1079
1080     // Make sure deriving works with Arc<T>
1081     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1082     struct Foo { inner: Arc<i32> }
1083
1084     #[test]
1085     fn test_unsized() {
1086         let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1087         assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1088         let y = x.clone().downgrade();
1089         drop(x);
1090         assert!(y.upgrade().is_none());
1091     }
1092 }