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