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