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