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