]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
std: Add AsRef/AsMut impls to Box/Rc/Arc
[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,
311                        size_of_val(&*ptr),
312                        align_of_val(&*ptr))
313         }
314     }
315 }
316
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl<T: ?Sized> Clone for Arc<T> {
319     /// Makes a clone of the `Arc<T>`.
320     ///
321     /// This increases the strong reference count.
322     ///
323     /// # Examples
324     ///
325     /// ```
326     /// use std::sync::Arc;
327     ///
328     /// let five = Arc::new(5);
329     ///
330     /// five.clone();
331     /// ```
332     #[inline]
333     fn clone(&self) -> Arc<T> {
334         // Using a relaxed ordering is alright here, as knowledge of the
335         // original reference prevents other threads from erroneously deleting
336         // the object.
337         //
338         // As explained in the [Boost documentation][1], Increasing the
339         // reference counter can always be done with memory_order_relaxed: New
340         // references to an object can only be formed from an existing
341         // reference, and passing an existing reference from one thread to
342         // another must already provide any required synchronization.
343         //
344         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
345         let old_size = self.inner().strong.fetch_add(1, Relaxed);
346
347         // However we need to guard against massive refcounts in case someone
348         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
349         // and users will use-after free. We racily saturate to `isize::MAX` on
350         // the assumption that there aren't ~2 billion threads incrementing
351         // the reference count at once. This branch will never be taken in
352         // any realistic program.
353         //
354         // We abort because such a program is incredibly degenerate, and we
355         // don't care to support it.
356         if old_size > MAX_REFCOUNT {
357             unsafe {
358                 abort();
359             }
360         }
361
362         Arc { _ptr: self._ptr }
363     }
364 }
365
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<T: ?Sized> Deref for Arc<T> {
368     type Target = T;
369
370     #[inline]
371     fn deref(&self) -> &T {
372         &self.inner().data
373     }
374 }
375
376 impl<T: Clone> Arc<T> {
377     #[unstable(feature = "arc_make_unique", reason = "renamed to Arc::make_mut",
378                issue = "27718")]
379     #[deprecated(since = "1.4.0", reason = "renamed to Arc::make_mut")]
380     pub fn make_unique(this: &mut Self) -> &mut T {
381         Arc::make_mut(this)
382     }
383
384     /// Make a mutable reference into the given `Arc<T>` by cloning the inner
385     /// data if the `Arc<T>` doesn't have one strong reference and no weak
386     /// references.
387     ///
388     /// This is also referred to as a copy-on-write.
389     ///
390     /// # Examples
391     ///
392     /// ```
393     /// use std::sync::Arc;
394     ///
395     /// let mut data = Arc::new(5);
396     ///
397     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
398     /// let mut other_data = data.clone();      // Won't clone inner data
399     /// *Arc::make_mut(&mut data) += 1;         // Clones inner data
400     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
401     /// *Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything
402     ///
403     /// // Note: data and other_data now point to different numbers
404     /// assert_eq!(*data, 8);
405     /// assert_eq!(*other_data, 12);
406     ///
407     /// ```
408     #[inline]
409     #[stable(feature = "arc_unique", since = "1.4.0")]
410     pub fn make_mut(this: &mut Self) -> &mut T {
411         // Note that we hold both a strong reference and a weak reference.
412         // Thus, releasing our strong reference only will not, by itself, cause
413         // the memory to be deallocated.
414         //
415         // Use Acquire to ensure that we see any writes to `weak` that happen
416         // before release writes (i.e., decrements) to `strong`. Since we hold a
417         // weak count, there's no chance the ArcInner itself could be
418         // deallocated.
419         if this.inner().strong.compare_and_swap(1, 0, Acquire) != 1 {
420             // Another srong pointer exists; clone
421             *this = Arc::new((**this).clone());
422         } else if this.inner().weak.load(Relaxed) != 1 {
423             // Relaxed suffices in the above because this is fundamentally an
424             // optimization: we are always racing with weak pointers being
425             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
426
427             // We removed the last strong ref, but there are additional weak
428             // refs remaining. We'll move the contents to a new Arc, and
429             // invalidate the other weak refs.
430
431             // Note that it is not possible for the read of `weak` to yield
432             // usize::MAX (i.e., locked), since the weak count can only be
433             // locked by a thread with a strong reference.
434
435             // Materialize our own implicit weak pointer, so that it can clean
436             // up the ArcInner as needed.
437             let weak = Weak { _ptr: this._ptr };
438
439             // mark the data itself as already deallocated
440             unsafe {
441                 // there is no data race in the implicit write caused by `read`
442                 // here (due to zeroing) because data is no longer accessed by
443                 // other threads (due to there being no more strong refs at this
444                 // point).
445                 let mut swap = Arc::new(ptr::read(&(**weak._ptr).data));
446                 mem::swap(this, &mut swap);
447                 mem::forget(swap);
448             }
449         } else {
450             // We were the sole reference of either kind; bump back up the
451             // strong ref count.
452             this.inner().strong.store(1, Release);
453         }
454
455         // As with `get_mut()`, the unsafety is ok because our reference was
456         // either unique to begin with, or became one upon cloning the contents.
457         unsafe {
458             let inner = &mut **this._ptr;
459             &mut inner.data
460         }
461     }
462 }
463
464 impl<T: ?Sized> Arc<T> {
465     /// Returns a mutable reference to the contained value if the `Arc<T>` has
466     /// one strong reference and no weak references.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// use std::sync::Arc;
472     ///
473     /// let mut x = Arc::new(3);
474     /// *Arc::get_mut(&mut x).unwrap() = 4;
475     /// assert_eq!(*x, 4);
476     ///
477     /// let _y = x.clone();
478     /// assert!(Arc::get_mut(&mut x).is_none());
479     /// ```
480     #[inline]
481     #[stable(feature = "arc_unique", since = "1.4.0")]
482     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
483         if this.is_unique() {
484             // This unsafety is ok because we're guaranteed that the pointer
485             // returned is the *only* pointer that will ever be returned to T. Our
486             // reference count is guaranteed to be 1 at this point, and we required
487             // the Arc itself to be `mut`, so we're returning the only possible
488             // reference to the inner data.
489             unsafe {
490                 let inner = &mut **this._ptr;
491                 Some(&mut inner.data)
492             }
493         } else {
494             None
495         }
496     }
497
498     /// Determine whether this is the unique reference (including weak refs) to
499     /// the underlying data.
500     ///
501     /// Note that this requires locking the weak ref count.
502     fn is_unique(&mut self) -> bool {
503         // lock the weak pointer count if we appear to be the sole weak pointer
504         // holder.
505         //
506         // The acquire label here ensures a happens-before relationship with any
507         // writes to `strong` prior to decrements of the `weak` count (via drop,
508         // which uses Release).
509         if self.inner().weak.compare_and_swap(1, usize::MAX, Acquire) == 1 {
510             // Due to the previous acquire read, this will observe any writes to
511             // `strong` that were due to upgrading weak pointers; only strong
512             // clones remain, which require that the strong count is > 1 anyway.
513             let unique = self.inner().strong.load(Relaxed) == 1;
514
515             // The release write here synchronizes with a read in `downgrade`,
516             // effectively preventing the above read of `strong` from happening
517             // after the write.
518             self.inner().weak.store(1, Release); // release the lock
519             unique
520         } else {
521             false
522         }
523     }
524 }
525
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl<T: ?Sized> Drop for Arc<T> {
528     /// Drops the `Arc<T>`.
529     ///
530     /// This will decrement the strong reference count. If the strong reference
531     /// count becomes zero and the only other references are `Weak<T>` ones,
532     /// `drop`s the inner value.
533     ///
534     /// # Examples
535     ///
536     /// ```
537     /// use std::sync::Arc;
538     ///
539     /// {
540     ///     let five = Arc::new(5);
541     ///
542     ///     // stuff
543     ///
544     ///     drop(five); // explicit drop
545     /// }
546     /// {
547     ///     let five = Arc::new(5);
548     ///
549     ///     // stuff
550     ///
551     /// } // implicit drop
552     /// ```
553     #[inline]
554     fn drop(&mut self) {
555         // This structure has #[unsafe_no_drop_flag], so this drop glue may run
556         // more than once (but it is guaranteed to be zeroed after the first if
557         // it's run more than once)
558         let ptr = *self._ptr;
559         // if ptr.is_null() { return }
560         if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
561             return
562         }
563
564         // Because `fetch_sub` is already atomic, we do not need to synchronize
565         // with other threads unless we are going to delete the object. This
566         // same logic applies to the below `fetch_sub` to the `weak` count.
567         if self.inner().strong.fetch_sub(1, Release) != 1 {
568             return
569         }
570
571         // This fence is needed to prevent reordering of use of the data and
572         // deletion of the data.  Because it is marked `Release`, the decreasing
573         // of the reference count synchronizes with this `Acquire` fence. This
574         // means that use of the data happens before decreasing the reference
575         // count, which happens before this fence, which happens before the
576         // deletion of the data.
577         //
578         // As explained in the [Boost documentation][1],
579         //
580         // > It is important to enforce any possible access to the object in one
581         // > thread (through an existing reference) to *happen before* deleting
582         // > the object in a different thread. This is achieved by a "release"
583         // > operation after dropping a reference (any access to the object
584         // > through this reference must obviously happened before), and an
585         // > "acquire" operation before deleting the object.
586         //
587         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
588         atomic::fence(Acquire);
589
590         unsafe {
591             self.drop_slow();
592         }
593     }
594 }
595
596 impl<T: ?Sized> Weak<T> {
597     /// Upgrades a weak reference to a strong reference.
598     ///
599     /// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
600     ///
601     /// Returns `None` if there were no strong references and the data was
602     /// destroyed.
603     ///
604     /// # Examples
605     ///
606     /// ```
607     /// use std::sync::Arc;
608     ///
609     /// let five = Arc::new(5);
610     ///
611     /// let weak_five = Arc::downgrade(&five);
612     ///
613     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
614     /// ```
615     #[stable(feature = "arc_weak", since = "1.4.0")]
616     pub fn upgrade(&self) -> Option<Arc<T>> {
617         // We use a CAS loop to increment the strong count instead of a
618         // fetch_add because once the count hits 0 it must never be above 0.
619         let inner = self.inner();
620         loop {
621             // Relaxed load because any write of 0 that we can observe
622             // leaves the field in a permanently zero state (so a
623             // "stale" read of 0 is fine), and any other value is
624             // confirmed via the CAS below.
625             let n = inner.strong.load(Relaxed);
626             if n == 0 {
627                 return None
628             }
629
630             // Relaxed is valid for the same reason it is on Arc's Clone impl
631             let old = inner.strong.compare_and_swap(n, n + 1, Relaxed);
632             if old == n {
633                 return Some(Arc { _ptr: self._ptr })
634             }
635         }
636     }
637
638     #[inline]
639     fn inner(&self) -> &ArcInner<T> {
640         // See comments above for why this is "safe"
641         unsafe { &**self._ptr }
642     }
643 }
644
645 #[stable(feature = "arc_weak", since = "1.4.0")]
646 impl<T: ?Sized> Clone for Weak<T> {
647     /// Makes a clone of the `Weak<T>`.
648     ///
649     /// This increases the weak reference count.
650     ///
651     /// # Examples
652     ///
653     /// ```
654     /// use std::sync::Arc;
655     ///
656     /// let weak_five = Arc::downgrade(&Arc::new(5));
657     ///
658     /// weak_five.clone();
659     /// ```
660     #[inline]
661     fn clone(&self) -> Weak<T> {
662         // See comments in Arc::clone() for why this is relaxed.  This can use a
663         // fetch_add (ignoring the lock) because the weak count is only locked
664         // where are *no other* weak pointers in existence. (So we can't be
665         // running this code in that case).
666         let old_size = self.inner().weak.fetch_add(1, Relaxed);
667
668         // See comments in Arc::clone() for why we do this (for mem::forget).
669         if old_size > MAX_REFCOUNT {
670             unsafe {
671                 abort();
672             }
673         }
674
675         return Weak { _ptr: self._ptr }
676     }
677 }
678
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<T: ?Sized> Drop for Weak<T> {
681     /// Drops the `Weak<T>`.
682     ///
683     /// This will decrement the weak reference count.
684     ///
685     /// # Examples
686     ///
687     /// ```
688     /// use std::sync::Arc;
689     ///
690     /// {
691     ///     let five = Arc::new(5);
692     ///     let weak_five = Arc::downgrade(&five);
693     ///
694     ///     // stuff
695     ///
696     ///     drop(weak_five); // explicit drop
697     /// }
698     /// {
699     ///     let five = Arc::new(5);
700     ///     let weak_five = Arc::downgrade(&five);
701     ///
702     ///     // stuff
703     ///
704     /// } // implicit drop
705     /// ```
706     fn drop(&mut self) {
707         let ptr = *self._ptr;
708
709         // see comments above for why this check is here
710         if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE {
711             return
712         }
713
714         // If we find out that we were the last weak pointer, then its time to
715         // deallocate the data entirely. See the discussion in Arc::drop() about
716         // the memory orderings
717         //
718         // It's not necessary to check for the locked state here, because the
719         // weak count can only be locked if there was precisely one weak ref,
720         // meaning that drop could only subsequently run ON that remaining weak
721         // ref, which can only happen after the lock is released.
722         if self.inner().weak.fetch_sub(1, Release) == 1 {
723             atomic::fence(Acquire);
724             unsafe {
725                 deallocate(ptr as *mut u8,
726                            size_of_val(&*ptr),
727                            align_of_val(&*ptr))
728             }
729         }
730     }
731 }
732
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
735     /// Equality for two `Arc<T>`s.
736     ///
737     /// Two `Arc<T>`s are equal if their inner value are equal.
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 eq(&self, other: &Arc<T>) -> bool {
749         *(*self) == *(*other)
750     }
751
752     /// Inequality for two `Arc<T>`s.
753     ///
754     /// Two `Arc<T>`s are unequal if their inner value are unequal.
755     ///
756     /// # Examples
757     ///
758     /// ```
759     /// use std::sync::Arc;
760     ///
761     /// let five = Arc::new(5);
762     ///
763     /// five != Arc::new(5);
764     /// ```
765     fn ne(&self, other: &Arc<T>) -> bool {
766         *(*self) != *(*other)
767     }
768 }
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
771     /// Partial comparison for two `Arc<T>`s.
772     ///
773     /// The two are compared by calling `partial_cmp()` on their inner values.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// use std::sync::Arc;
779     ///
780     /// let five = Arc::new(5);
781     ///
782     /// five.partial_cmp(&Arc::new(5));
783     /// ```
784     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
785         (**self).partial_cmp(&**other)
786     }
787
788     /// Less-than comparison for two `Arc<T>`s.
789     ///
790     /// The two are compared by calling `<` on their inner values.
791     ///
792     /// # Examples
793     ///
794     /// ```
795     /// use std::sync::Arc;
796     ///
797     /// let five = Arc::new(5);
798     ///
799     /// five < Arc::new(5);
800     /// ```
801     fn lt(&self, other: &Arc<T>) -> bool {
802         *(*self) < *(*other)
803     }
804
805     /// 'Less-than or equal to' comparison for two `Arc<T>`s.
806     ///
807     /// The two are compared by calling `<=` on their inner values.
808     ///
809     /// # Examples
810     ///
811     /// ```
812     /// use std::sync::Arc;
813     ///
814     /// let five = Arc::new(5);
815     ///
816     /// five <= Arc::new(5);
817     /// ```
818     fn le(&self, other: &Arc<T>) -> bool {
819         *(*self) <= *(*other)
820     }
821
822     /// Greater-than comparison for two `Arc<T>`s.
823     ///
824     /// The two are compared by calling `>` on their inner values.
825     ///
826     /// # Examples
827     ///
828     /// ```
829     /// use std::sync::Arc;
830     ///
831     /// let five = Arc::new(5);
832     ///
833     /// five > Arc::new(5);
834     /// ```
835     fn gt(&self, other: &Arc<T>) -> bool {
836         *(*self) > *(*other)
837     }
838
839     /// 'Greater-than or equal to' comparison for two `Arc<T>`s.
840     ///
841     /// The two are compared by calling `>=` on their inner values.
842     ///
843     /// # Examples
844     ///
845     /// ```
846     /// use std::sync::Arc;
847     ///
848     /// let five = Arc::new(5);
849     ///
850     /// five >= Arc::new(5);
851     /// ```
852     fn ge(&self, other: &Arc<T>) -> bool {
853         *(*self) >= *(*other)
854     }
855 }
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl<T: ?Sized + Ord> Ord for Arc<T> {
858     fn cmp(&self, other: &Arc<T>) -> Ordering {
859         (**self).cmp(&**other)
860     }
861 }
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<T: ?Sized + Eq> Eq for Arc<T> {}
864
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
867     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868         fmt::Display::fmt(&**self, f)
869     }
870 }
871
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
874     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875         fmt::Debug::fmt(&**self, f)
876     }
877 }
878
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<T> fmt::Pointer for Arc<T> {
881     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882         fmt::Pointer::fmt(&*self._ptr, f)
883     }
884 }
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<T: Default> Default for Arc<T> {
888     #[stable(feature = "rust1", since = "1.0.0")]
889     fn default() -> Arc<T> {
890         Arc::new(Default::default())
891     }
892 }
893
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<T: ?Sized + Hash> Hash for Arc<T> {
896     fn hash<H: Hasher>(&self, state: &mut H) {
897         (**self).hash(state)
898     }
899 }
900
901 #[cfg(test)]
902 mod tests {
903     use std::clone::Clone;
904     use std::sync::mpsc::channel;
905     use std::mem::drop;
906     use std::ops::Drop;
907     use std::option::Option;
908     use std::option::Option::{Some, None};
909     use std::sync::atomic;
910     use std::sync::atomic::Ordering::{Acquire, SeqCst};
911     use std::thread;
912     use std::vec::Vec;
913     use super::{Arc, Weak};
914     use std::sync::Mutex;
915
916     struct Canary(*mut atomic::AtomicUsize);
917
918     impl Drop for Canary
919     {
920         fn drop(&mut self) {
921             unsafe {
922                 match *self {
923                     Canary(c) => {
924                         (*c).fetch_add(1, SeqCst);
925                     }
926                 }
927             }
928         }
929     }
930
931     #[test]
932     fn manually_share_arc() {
933         let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
934         let arc_v = Arc::new(v);
935
936         let (tx, rx) = channel();
937
938         let _t = thread::spawn(move || {
939             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
940             assert_eq!((*arc_v)[3], 4);
941         });
942
943         tx.send(arc_v.clone()).unwrap();
944
945         assert_eq!((*arc_v)[2], 3);
946         assert_eq!((*arc_v)[4], 5);
947     }
948
949     #[test]
950     fn test_arc_get_mut() {
951         let mut x = Arc::new(3);
952         *Arc::get_mut(&mut x).unwrap() = 4;
953         assert_eq!(*x, 4);
954         let y = x.clone();
955         assert!(Arc::get_mut(&mut x).is_none());
956         drop(y);
957         assert!(Arc::get_mut(&mut x).is_some());
958         let _w = Arc::downgrade(&x);
959         assert!(Arc::get_mut(&mut x).is_none());
960     }
961
962     #[test]
963     fn try_unwrap() {
964         let x = Arc::new(3);
965         assert_eq!(Arc::try_unwrap(x), Ok(3));
966         let x = Arc::new(4);
967         let _y = x.clone();
968         assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
969         let x = Arc::new(5);
970         let _w = Arc::downgrade(&x);
971         assert_eq!(Arc::try_unwrap(x), Ok(5));
972     }
973
974     #[test]
975     fn test_cowarc_clone_make_mut() {
976         let mut cow0 = Arc::new(75);
977         let mut cow1 = cow0.clone();
978         let mut cow2 = cow1.clone();
979
980         assert!(75 == *Arc::make_mut(&mut cow0));
981         assert!(75 == *Arc::make_mut(&mut cow1));
982         assert!(75 == *Arc::make_mut(&mut cow2));
983
984         *Arc::make_mut(&mut cow0) += 1;
985         *Arc::make_mut(&mut cow1) += 2;
986         *Arc::make_mut(&mut cow2) += 3;
987
988         assert!(76 == *cow0);
989         assert!(77 == *cow1);
990         assert!(78 == *cow2);
991
992         // none should point to the same backing memory
993         assert!(*cow0 != *cow1);
994         assert!(*cow0 != *cow2);
995         assert!(*cow1 != *cow2);
996     }
997
998     #[test]
999     fn test_cowarc_clone_unique2() {
1000         let mut cow0 = Arc::new(75);
1001         let cow1 = cow0.clone();
1002         let cow2 = cow1.clone();
1003
1004         assert!(75 == *cow0);
1005         assert!(75 == *cow1);
1006         assert!(75 == *cow2);
1007
1008         *Arc::make_mut(&mut cow0) += 1;
1009         assert!(76 == *cow0);
1010         assert!(75 == *cow1);
1011         assert!(75 == *cow2);
1012
1013         // cow1 and cow2 should share the same contents
1014         // cow0 should have a unique reference
1015         assert!(*cow0 != *cow1);
1016         assert!(*cow0 != *cow2);
1017         assert!(*cow1 == *cow2);
1018     }
1019
1020     #[test]
1021     fn test_cowarc_clone_weak() {
1022         let mut cow0 = Arc::new(75);
1023         let cow1_weak = Arc::downgrade(&cow0);
1024
1025         assert!(75 == *cow0);
1026         assert!(75 == *cow1_weak.upgrade().unwrap());
1027
1028         *Arc::make_mut(&mut cow0) += 1;
1029
1030         assert!(76 == *cow0);
1031         assert!(cow1_weak.upgrade().is_none());
1032     }
1033
1034     #[test]
1035     fn test_live() {
1036         let x = Arc::new(5);
1037         let y = Arc::downgrade(&x);
1038         assert!(y.upgrade().is_some());
1039     }
1040
1041     #[test]
1042     fn test_dead() {
1043         let x = Arc::new(5);
1044         let y = Arc::downgrade(&x);
1045         drop(x);
1046         assert!(y.upgrade().is_none());
1047     }
1048
1049     #[test]
1050     fn weak_self_cyclic() {
1051         struct Cycle {
1052             x: Mutex<Option<Weak<Cycle>>>,
1053         }
1054
1055         let a = Arc::new(Cycle { x: Mutex::new(None) });
1056         let b = Arc::downgrade(&a.clone());
1057         *a.x.lock().unwrap() = Some(b);
1058
1059         // hopefully we don't double-free (or leak)...
1060     }
1061
1062     #[test]
1063     fn drop_arc() {
1064         let mut canary = atomic::AtomicUsize::new(0);
1065         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1066         drop(x);
1067         assert!(canary.load(Acquire) == 1);
1068     }
1069
1070     #[test]
1071     fn drop_arc_weak() {
1072         let mut canary = atomic::AtomicUsize::new(0);
1073         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1074         let arc_weak = Arc::downgrade(&arc);
1075         assert!(canary.load(Acquire) == 0);
1076         drop(arc);
1077         assert!(canary.load(Acquire) == 1);
1078         drop(arc_weak);
1079     }
1080
1081     #[test]
1082     fn test_strong_count() {
1083         let a = Arc::new(0u32);
1084         assert!(Arc::strong_count(&a) == 1);
1085         let w = Arc::downgrade(&a);
1086         assert!(Arc::strong_count(&a) == 1);
1087         let b = w.upgrade().expect("");
1088         assert!(Arc::strong_count(&b) == 2);
1089         assert!(Arc::strong_count(&a) == 2);
1090         drop(w);
1091         drop(a);
1092         assert!(Arc::strong_count(&b) == 1);
1093         let c = b.clone();
1094         assert!(Arc::strong_count(&b) == 2);
1095         assert!(Arc::strong_count(&c) == 2);
1096     }
1097
1098     #[test]
1099     fn test_weak_count() {
1100         let a = Arc::new(0u32);
1101         assert!(Arc::strong_count(&a) == 1);
1102         assert!(Arc::weak_count(&a) == 0);
1103         let w = Arc::downgrade(&a);
1104         assert!(Arc::strong_count(&a) == 1);
1105         assert!(Arc::weak_count(&a) == 1);
1106         let x = w.clone();
1107         assert!(Arc::weak_count(&a) == 2);
1108         drop(w);
1109         drop(x);
1110         assert!(Arc::strong_count(&a) == 1);
1111         assert!(Arc::weak_count(&a) == 0);
1112         let c = a.clone();
1113         assert!(Arc::strong_count(&a) == 2);
1114         assert!(Arc::weak_count(&a) == 0);
1115         let d = Arc::downgrade(&c);
1116         assert!(Arc::weak_count(&c) == 1);
1117         assert!(Arc::strong_count(&c) == 2);
1118
1119         drop(a);
1120         drop(c);
1121         drop(d);
1122     }
1123
1124     #[test]
1125     fn show_arc() {
1126         let a = Arc::new(5u32);
1127         assert_eq!(format!("{:?}", a), "5");
1128     }
1129
1130     // Make sure deriving works with Arc<T>
1131     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1132     struct Foo {
1133         inner: Arc<i32>,
1134     }
1135
1136     #[test]
1137     fn test_unsized() {
1138         let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1139         assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1140         let y = Arc::downgrade(&x.clone());
1141         drop(x);
1142         assert!(y.upgrade().is_none());
1143     }
1144 }
1145
1146 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1147     fn borrow(&self) -> &T {
1148         &**self
1149     }
1150 }
1151
1152 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1153 impl<T: ?Sized> AsRef<T> for Arc<T> {
1154     fn as_ref(&self) -> &T { &**self }
1155 }