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