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