]> git.lizzy.rs Git - rust.git/blob - src/liballoc/arc.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[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 //! Thread-safe reference-counting pointers.
14 //!
15 //! See the [`Arc<T>`][arc] documentation for more details.
16 //!
17 //! [arc]: struct.Arc.html
18
19 use boxed::Box;
20
21 use core::sync::atomic;
22 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
23 use core::borrow;
24 use core::fmt;
25 use core::cmp::Ordering;
26 use core::mem::{align_of_val, size_of_val};
27 use core::intrinsics::abort;
28 use core::mem;
29 use core::mem::uninitialized;
30 use core::ops::Deref;
31 use core::ops::CoerceUnsized;
32 use core::ptr::{self, Shared};
33 use core::marker::Unsize;
34 use core::hash::{Hash, Hasher};
35 use core::{isize, usize};
36 use core::convert::From;
37 use heap::deallocate;
38
39 /// A soft limit on the amount of references that may be made to an `Arc`.
40 ///
41 /// Going above this limit will abort your program (although not
42 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
43 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
44
45 /// A thread-safe reference-counting pointer.
46 ///
47 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
48 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
49 /// a new pointer to the same value in the heap. When the last `Arc`
50 /// pointer to a given value is destroyed, the pointed-to value is
51 /// also destroyed.
52 ///
53 /// Shared references in Rust disallow mutation by default, and `Arc` is no
54 /// exception. If you need to mutate through an `Arc`, use [`Mutex`][mutex],
55 /// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types.
56 ///
57 /// `Arc` uses atomic operations for reference counting, so `Arc`s can be
58 /// sent between threads. In other words, `Arc<T>` implements [`Send`]
59 /// as long as `T` implements [`Send`] and [`Sync`][sync]. The disadvantage is
60 /// that atomic operations are more expensive than ordinary memory accesses.
61 /// If you are not sharing reference-counted values between threads, consider
62 /// using [`rc::Rc`][`Rc`] for lower overhead. [`Rc`] is a safe default, because
63 /// the compiler will catch any attempt to send an [`Rc`] between threads.
64 /// However, a library might choose `Arc` in order to give library consumers
65 /// more flexibility.
66 ///
67 /// The [`downgrade`][downgrade] method can be used to create a non-owning
68 /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d
69 /// to an `Arc`, but this will return [`None`] if the value has already been
70 /// dropped.
71 ///
72 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
73 /// [`Weak`][weak] is used to break cycles. For example, a tree could have
74 /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak]
75 /// pointers from children back to their parents.
76 ///
77 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
78 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
79 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are [associated
80 /// functions][assoc], called using function-like syntax:
81 ///
82 /// ```
83 /// use std::sync::Arc;
84 /// let my_arc = Arc::new(());
85 ///
86 /// Arc::downgrade(&my_arc);
87 /// ```
88 ///
89 /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have
90 /// already been destroyed.
91 ///
92 /// [arc]: struct.Arc.html
93 /// [weak]: struct.Weak.html
94 /// [`Rc`]: ../../std/rc/struct.Rc.html
95 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
96 /// [mutex]: ../../std/sync/struct.Mutex.html
97 /// [rwlock]: ../../std/sync/struct.RwLock.html
98 /// [atomic]: ../../std/sync/atomic/index.html
99 /// [`Send`]: ../../std/marker/trait.Send.html
100 /// [sync]: ../../std/marker/trait.Sync.html
101 /// [deref]: ../../std/ops/trait.Deref.html
102 /// [downgrade]: struct.Arc.html#method.downgrade
103 /// [upgrade]: struct.Weak.html#method.upgrade
104 /// [`None`]: ../../std/option/enum.Option.html#variant.None
105 /// [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
106 ///
107 /// # Examples
108 ///
109 /// Sharing some immutable data between threads:
110 ///
111 // Note that we **do not** run these tests here. The windows builders get super
112 // unhappy if a thread outlives the main thread and then exits at the same time
113 // (something deadlocks) so we just avoid this entirely by not running these
114 // tests.
115 /// ```no_run
116 /// use std::sync::Arc;
117 /// use std::thread;
118 ///
119 /// let five = Arc::new(5);
120 ///
121 /// for _ in 0..10 {
122 ///     let five = five.clone();
123 ///
124 ///     thread::spawn(move || {
125 ///         println!("{:?}", five);
126 ///     });
127 /// }
128 /// ```
129 ///
130 /// Sharing a mutable [`AtomicUsize`]:
131 ///
132 /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html
133 ///
134 /// ```no_run
135 /// use std::sync::Arc;
136 /// use std::sync::atomic::{AtomicUsize, Ordering};
137 /// use std::thread;
138 ///
139 /// let val = Arc::new(AtomicUsize::new(5));
140 ///
141 /// for _ in 0..10 {
142 ///     let val = val.clone();
143 ///
144 ///     thread::spawn(move || {
145 ///         let v = val.fetch_add(1, Ordering::SeqCst);
146 ///         println!("{:?}", v);
147 ///     });
148 /// }
149 /// ```
150 ///
151 /// See the [`rc` documentation][rc_examples] for more examples of reference
152 /// counting in general.
153 ///
154 /// [rc_examples]: ../../std/rc/index.html#examples
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub struct Arc<T: ?Sized> {
157     ptr: Shared<ArcInner<T>>,
158 }
159
160 #[stable(feature = "rust1", since = "1.0.0")]
161 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
162 #[stable(feature = "rust1", since = "1.0.0")]
163 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
164
165 #[unstable(feature = "coerce_unsized", issue = "27732")]
166 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
167
168 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
169 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
170 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
171 ///
172 /// Since a `Weak` reference does not count towards ownership, it will not
173 /// prevent the inner value from being dropped, and `Weak` itself makes no
174 /// guarantees about the value still being present and may return [`None`]
175 /// when [`upgrade`]d.
176 ///
177 /// A `Weak` pointer is useful for keeping a temporary reference to the value
178 /// within [`Arc`] without extending its lifetime. It is also used to prevent
179 /// circular references between [`Arc`] pointers, since mutual owning references
180 /// would never allow either [`Arc`] to be dropped. For example, a tree could
181 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
182 /// pointers from children back to their parents.
183 ///
184 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
185 ///
186 /// [`Arc`]: struct.Arc.html
187 /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade
188 /// [`upgrade`]: struct.Weak.html#method.upgrade
189 /// [`Option`]: ../../std/option/enum.Option.html
190 /// [`None`]: ../../std/option/enum.Option.html#variant.None
191 #[stable(feature = "arc_weak", since = "1.4.0")]
192 pub struct Weak<T: ?Sized> {
193     ptr: Shared<ArcInner<T>>,
194 }
195
196 #[stable(feature = "arc_weak", since = "1.4.0")]
197 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
198 #[stable(feature = "arc_weak", since = "1.4.0")]
199 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
200
201 #[unstable(feature = "coerce_unsized", issue = "27732")]
202 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
203
204 #[stable(feature = "arc_weak", since = "1.4.0")]
205 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
206     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207         write!(f, "(Weak)")
208     }
209 }
210
211 struct ArcInner<T: ?Sized> {
212     strong: atomic::AtomicUsize,
213
214     // the value usize::MAX acts as a sentinel for temporarily "locking" the
215     // ability to upgrade weak pointers or downgrade strong ones; this is used
216     // to avoid races in `make_mut` and `get_mut`.
217     weak: atomic::AtomicUsize,
218
219     data: T,
220 }
221
222 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
223 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
224
225 impl<T> Arc<T> {
226     /// Constructs a new `Arc<T>`.
227     ///
228     /// # Examples
229     ///
230     /// ```
231     /// use std::sync::Arc;
232     ///
233     /// let five = Arc::new(5);
234     /// ```
235     #[inline]
236     #[stable(feature = "rust1", since = "1.0.0")]
237     pub fn new(data: T) -> Arc<T> {
238         // Start the weak pointer count as 1 which is the weak pointer that's
239         // held by all the strong pointers (kinda), see std/rc.rs for more info
240         let x: Box<_> = box ArcInner {
241             strong: atomic::AtomicUsize::new(1),
242             weak: atomic::AtomicUsize::new(1),
243             data: data,
244         };
245         Arc { ptr: unsafe { Shared::new(Box::into_raw(x)) } }
246     }
247
248     /// Returns the contained value, if the `Arc` has exactly one strong reference.
249     ///
250     /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was
251     /// passed in.
252     ///
253     /// This will succeed even if there are outstanding weak references.
254     ///
255     /// [result]: ../../std/result/enum.Result.html
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// use std::sync::Arc;
261     ///
262     /// let x = Arc::new(3);
263     /// assert_eq!(Arc::try_unwrap(x), Ok(3));
264     ///
265     /// let x = Arc::new(4);
266     /// let _y = x.clone();
267     /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
268     /// ```
269     #[inline]
270     #[stable(feature = "arc_unique", since = "1.4.0")]
271     pub fn try_unwrap(this: Self) -> Result<T, Self> {
272         // See `drop` for why all these atomics are like this
273         if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() {
274             return Err(this);
275         }
276
277         atomic::fence(Acquire);
278
279         unsafe {
280             let ptr = *this.ptr;
281             let elem = ptr::read(&(*ptr).data);
282
283             // Make a weak pointer to clean up the implicit strong-weak reference
284             let _weak = Weak { ptr: this.ptr };
285             mem::forget(this);
286
287             Ok(elem)
288         }
289     }
290
291     /// Consumes the `Arc`, returning the wrapped pointer.
292     ///
293     /// To avoid a memory leak the pointer must be converted back to an `Arc` using
294     /// [`Arc::from_raw`][from_raw].
295     ///
296     /// [from_raw]: struct.Arc.html#method.from_raw
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use std::sync::Arc;
302     ///
303     /// let x = Arc::new(10);
304     /// let x_ptr = Arc::into_raw(x);
305     /// assert_eq!(unsafe { *x_ptr }, 10);
306     /// ```
307     #[stable(feature = "rc_raw", since = "1.17.0")]
308     pub fn into_raw(this: Self) -> *const T {
309         let ptr = unsafe { &(**this.ptr).data as *const _ };
310         mem::forget(this);
311         ptr
312     }
313
314     /// Constructs an `Arc` from a raw pointer.
315     ///
316     /// The raw pointer must have been previously returned by a call to a
317     /// [`Arc::into_raw`][into_raw].
318     ///
319     /// This function is unsafe because improper use may lead to memory problems. For example, a
320     /// double-free may occur if the function is called twice on the same raw pointer.
321     ///
322     /// [into_raw]: struct.Arc.html#method.into_raw
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::sync::Arc;
328     ///
329     /// let x = Arc::new(10);
330     /// let x_ptr = Arc::into_raw(x);
331     ///
332     /// unsafe {
333     ///     // Convert back to an `Arc` to prevent leak.
334     ///     let x = Arc::from_raw(x_ptr);
335     ///     assert_eq!(*x, 10);
336     ///
337     ///     // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe.
338     /// }
339     ///
340     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
341     /// ```
342     #[stable(feature = "rc_raw", since = "1.17.0")]
343     pub unsafe fn from_raw(ptr: *const T) -> Self {
344         // To find the corresponding pointer to the `ArcInner` we need to subtract the offset of the
345         // `data` field from the pointer.
346         let ptr = (ptr as *const u8).offset(-offset_of!(ArcInner<T>, data));
347         Arc {
348             ptr: Shared::new(ptr as *const _),
349         }
350     }
351 }
352
353 impl<T: ?Sized> Arc<T> {
354     /// Creates a new [`Weak`][weak] pointer to this value.
355     ///
356     /// [weak]: struct.Weak.html
357     ///
358     /// # Examples
359     ///
360     /// ```
361     /// use std::sync::Arc;
362     ///
363     /// let five = Arc::new(5);
364     ///
365     /// let weak_five = Arc::downgrade(&five);
366     /// ```
367     #[stable(feature = "arc_weak", since = "1.4.0")]
368     pub fn downgrade(this: &Self) -> Weak<T> {
369         // This Relaxed is OK because we're checking the value in the CAS
370         // below.
371         let mut cur = this.inner().weak.load(Relaxed);
372
373         loop {
374             // check if the weak counter is currently "locked"; if so, spin.
375             if cur == usize::MAX {
376                 cur = this.inner().weak.load(Relaxed);
377                 continue;
378             }
379
380             // NOTE: this code currently ignores the possibility of overflow
381             // into usize::MAX; in general both Rc and Arc need to be adjusted
382             // to deal with overflow.
383
384             // Unlike with Clone(), we need this to be an Acquire read to
385             // synchronize with the write coming from `is_unique`, so that the
386             // events prior to that write happen before this read.
387             match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
388                 Ok(_) => return Weak { ptr: this.ptr },
389                 Err(old) => cur = old,
390             }
391         }
392     }
393
394     /// Gets the number of [`Weak`][weak] pointers to this value.
395     ///
396     /// [weak]: struct.Weak.html
397     ///
398     /// # Safety
399     ///
400     /// This method by itself is safe, but using it correctly requires extra care.
401     /// Another thread can change the weak count at any time,
402     /// including potentially between calling this method and acting on the result.
403     ///
404     /// # Examples
405     ///
406     /// ```
407     /// use std::sync::Arc;
408     ///
409     /// let five = Arc::new(5);
410     /// let _weak_five = Arc::downgrade(&five);
411     ///
412     /// // This assertion is deterministic because we haven't shared
413     /// // the `Arc` or `Weak` between threads.
414     /// assert_eq!(1, Arc::weak_count(&five));
415     /// ```
416     #[inline]
417     #[stable(feature = "arc_counts", since = "1.15.0")]
418     pub fn weak_count(this: &Self) -> usize {
419         this.inner().weak.load(SeqCst) - 1
420     }
421
422     /// Gets the number of strong (`Arc`) pointers to this value.
423     ///
424     /// # Safety
425     ///
426     /// This method by itself is safe, but using it correctly requires extra care.
427     /// Another thread can change the strong count at any time,
428     /// including potentially between calling this method and acting on the result.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// use std::sync::Arc;
434     ///
435     /// let five = Arc::new(5);
436     /// let _also_five = five.clone();
437     ///
438     /// // This assertion is deterministic because we haven't shared
439     /// // the `Arc` between threads.
440     /// assert_eq!(2, Arc::strong_count(&five));
441     /// ```
442     #[inline]
443     #[stable(feature = "arc_counts", since = "1.15.0")]
444     pub fn strong_count(this: &Self) -> usize {
445         this.inner().strong.load(SeqCst)
446     }
447
448     #[inline]
449     fn inner(&self) -> &ArcInner<T> {
450         // This unsafety is ok because while this arc is alive we're guaranteed
451         // that the inner pointer is valid. Furthermore, we know that the
452         // `ArcInner` structure itself is `Sync` because the inner data is
453         // `Sync` as well, so we're ok loaning out an immutable pointer to these
454         // contents.
455         unsafe { &**self.ptr }
456     }
457
458     // Non-inlined part of `drop`.
459     #[inline(never)]
460     unsafe fn drop_slow(&mut self) {
461         let ptr = self.ptr.as_mut_ptr();
462
463         // Destroy the data at this time, even though we may not free the box
464         // allocation itself (there may still be weak pointers lying around).
465         ptr::drop_in_place(&mut (*ptr).data);
466
467         if self.inner().weak.fetch_sub(1, Release) == 1 {
468             atomic::fence(Acquire);
469             deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
470         }
471     }
472
473     #[inline]
474     #[stable(feature = "ptr_eq", since = "1.17.0")]
475     /// Returns true if the two `Arc`s point to the same value (not
476     /// just values that compare as equal).
477     ///
478     /// # Examples
479     ///
480     /// ```
481     /// use std::sync::Arc;
482     ///
483     /// let five = Arc::new(5);
484     /// let same_five = five.clone();
485     /// let other_five = Arc::new(5);
486     ///
487     /// assert!(Arc::ptr_eq(&five, &same_five));
488     /// assert!(!Arc::ptr_eq(&five, &other_five));
489     /// ```
490     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
491         let this_ptr: *const ArcInner<T> = *this.ptr;
492         let other_ptr: *const ArcInner<T> = *other.ptr;
493         this_ptr == other_ptr
494     }
495 }
496
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: ?Sized> Clone for Arc<T> {
499     /// Makes a clone of the `Arc` pointer.
500     ///
501     /// This creates another pointer to the same inner value, increasing the
502     /// strong reference count.
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// use std::sync::Arc;
508     ///
509     /// let five = Arc::new(5);
510     ///
511     /// five.clone();
512     /// ```
513     #[inline]
514     fn clone(&self) -> Arc<T> {
515         // Using a relaxed ordering is alright here, as knowledge of the
516         // original reference prevents other threads from erroneously deleting
517         // the object.
518         //
519         // As explained in the [Boost documentation][1], Increasing the
520         // reference counter can always be done with memory_order_relaxed: New
521         // references to an object can only be formed from an existing
522         // reference, and passing an existing reference from one thread to
523         // another must already provide any required synchronization.
524         //
525         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
526         let old_size = self.inner().strong.fetch_add(1, Relaxed);
527
528         // However we need to guard against massive refcounts in case someone
529         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
530         // and users will use-after free. We racily saturate to `isize::MAX` on
531         // the assumption that there aren't ~2 billion threads incrementing
532         // the reference count at once. This branch will never be taken in
533         // any realistic program.
534         //
535         // We abort because such a program is incredibly degenerate, and we
536         // don't care to support it.
537         if old_size > MAX_REFCOUNT {
538             unsafe {
539                 abort();
540             }
541         }
542
543         Arc { ptr: self.ptr }
544     }
545 }
546
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl<T: ?Sized> Deref for Arc<T> {
549     type Target = T;
550
551     #[inline]
552     fn deref(&self) -> &T {
553         &self.inner().data
554     }
555 }
556
557 impl<T: Clone> Arc<T> {
558     /// Makes a mutable reference into the given `Arc`.
559     ///
560     /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
561     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
562     /// ensure unique ownership. This is also referred to as clone-on-write.
563     ///
564     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
565     ///
566     /// [weak]: struct.Weak.html
567     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
568     /// [get_mut]: struct.Arc.html#method.get_mut
569     ///
570     /// # Examples
571     ///
572     /// ```
573     /// use std::sync::Arc;
574     ///
575     /// let mut data = Arc::new(5);
576     ///
577     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
578     /// let mut other_data = data.clone();      // Won't clone inner data
579     /// *Arc::make_mut(&mut data) += 1;         // Clones inner data
580     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
581     /// *Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything
582     ///
583     /// // Now `data` and `other_data` point to different values.
584     /// assert_eq!(*data, 8);
585     /// assert_eq!(*other_data, 12);
586     /// ```
587     #[inline]
588     #[stable(feature = "arc_unique", since = "1.4.0")]
589     pub fn make_mut(this: &mut Self) -> &mut T {
590         // Note that we hold both a strong reference and a weak reference.
591         // Thus, releasing our strong reference only will not, by itself, cause
592         // the memory to be deallocated.
593         //
594         // Use Acquire to ensure that we see any writes to `weak` that happen
595         // before release writes (i.e., decrements) to `strong`. Since we hold a
596         // weak count, there's no chance the ArcInner itself could be
597         // deallocated.
598         if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
599             // Another strong pointer exists; clone
600             *this = Arc::new((**this).clone());
601         } else if this.inner().weak.load(Relaxed) != 1 {
602             // Relaxed suffices in the above because this is fundamentally an
603             // optimization: we are always racing with weak pointers being
604             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
605
606             // We removed the last strong ref, but there are additional weak
607             // refs remaining. We'll move the contents to a new Arc, and
608             // invalidate the other weak refs.
609
610             // Note that it is not possible for the read of `weak` to yield
611             // usize::MAX (i.e., locked), since the weak count can only be
612             // locked by a thread with a strong reference.
613
614             // Materialize our own implicit weak pointer, so that it can clean
615             // up the ArcInner as needed.
616             let weak = Weak { ptr: this.ptr };
617
618             // mark the data itself as already deallocated
619             unsafe {
620                 // there is no data race in the implicit write caused by `read`
621                 // here (due to zeroing) because data is no longer accessed by
622                 // other threads (due to there being no more strong refs at this
623                 // point).
624                 let mut swap = Arc::new(ptr::read(&(**weak.ptr).data));
625                 mem::swap(this, &mut swap);
626                 mem::forget(swap);
627             }
628         } else {
629             // We were the sole reference of either kind; bump back up the
630             // strong ref count.
631             this.inner().strong.store(1, Release);
632         }
633
634         // As with `get_mut()`, the unsafety is ok because our reference was
635         // either unique to begin with, or became one upon cloning the contents.
636         unsafe {
637             let inner = &mut *this.ptr.as_mut_ptr();
638             &mut inner.data
639         }
640     }
641 }
642
643 impl<T: ?Sized> Arc<T> {
644     /// Returns a mutable reference to the inner value, if there are
645     /// no other `Arc` or [`Weak`][weak] pointers to the same value.
646     ///
647     /// Returns [`None`][option] otherwise, because it is not safe to
648     /// mutate a shared value.
649     ///
650     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
651     /// the inner value when it's shared.
652     ///
653     /// [weak]: struct.Weak.html
654     /// [option]: ../../std/option/enum.Option.html
655     /// [make_mut]: struct.Arc.html#method.make_mut
656     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// use std::sync::Arc;
662     ///
663     /// let mut x = Arc::new(3);
664     /// *Arc::get_mut(&mut x).unwrap() = 4;
665     /// assert_eq!(*x, 4);
666     ///
667     /// let _y = x.clone();
668     /// assert!(Arc::get_mut(&mut x).is_none());
669     /// ```
670     #[inline]
671     #[stable(feature = "arc_unique", since = "1.4.0")]
672     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
673         if this.is_unique() {
674             // This unsafety is ok because we're guaranteed that the pointer
675             // returned is the *only* pointer that will ever be returned to T. Our
676             // reference count is guaranteed to be 1 at this point, and we required
677             // the Arc itself to be `mut`, so we're returning the only possible
678             // reference to the inner data.
679             unsafe {
680                 let inner = &mut *this.ptr.as_mut_ptr();
681                 Some(&mut inner.data)
682             }
683         } else {
684             None
685         }
686     }
687
688     /// Determine whether this is the unique reference (including weak refs) to
689     /// the underlying data.
690     ///
691     /// Note that this requires locking the weak ref count.
692     fn is_unique(&mut self) -> bool {
693         // lock the weak pointer count if we appear to be the sole weak pointer
694         // holder.
695         //
696         // The acquire label here ensures a happens-before relationship with any
697         // writes to `strong` prior to decrements of the `weak` count (via drop,
698         // which uses Release).
699         if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
700             // Due to the previous acquire read, this will observe any writes to
701             // `strong` that were due to upgrading weak pointers; only strong
702             // clones remain, which require that the strong count is > 1 anyway.
703             let unique = self.inner().strong.load(Relaxed) == 1;
704
705             // The release write here synchronizes with a read in `downgrade`,
706             // effectively preventing the above read of `strong` from happening
707             // after the write.
708             self.inner().weak.store(1, Release); // release the lock
709             unique
710         } else {
711             false
712         }
713     }
714 }
715
716 #[stable(feature = "rust1", since = "1.0.0")]
717 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
718     /// Drops the `Arc`.
719     ///
720     /// This will decrement the strong reference count. If the strong reference
721     /// count reaches zero then the only other references (if any) are
722     /// [`Weak`][weak], so we `drop` the inner value.
723     ///
724     /// [weak]: struct.Weak.html
725     ///
726     /// # Examples
727     ///
728     /// ```
729     /// use std::sync::Arc;
730     ///
731     /// struct Foo;
732     ///
733     /// impl Drop for Foo {
734     ///     fn drop(&mut self) {
735     ///         println!("dropped!");
736     ///     }
737     /// }
738     ///
739     /// let foo  = Arc::new(Foo);
740     /// let foo2 = foo.clone();
741     ///
742     /// drop(foo);    // Doesn't print anything
743     /// drop(foo2);   // Prints "dropped!"
744     /// ```
745     #[inline]
746     fn drop(&mut self) {
747         // Because `fetch_sub` is already atomic, we do not need to synchronize
748         // with other threads unless we are going to delete the object. This
749         // same logic applies to the below `fetch_sub` to the `weak` count.
750         if self.inner().strong.fetch_sub(1, Release) != 1 {
751             return;
752         }
753
754         // This fence is needed to prevent reordering of use of the data and
755         // deletion of the data.  Because it is marked `Release`, the decreasing
756         // of the reference count synchronizes with this `Acquire` fence. This
757         // means that use of the data happens before decreasing the reference
758         // count, which happens before this fence, which happens before the
759         // deletion of the data.
760         //
761         // As explained in the [Boost documentation][1],
762         //
763         // > It is important to enforce any possible access to the object in one
764         // > thread (through an existing reference) to *happen before* deleting
765         // > the object in a different thread. This is achieved by a "release"
766         // > operation after dropping a reference (any access to the object
767         // > through this reference must obviously happened before), and an
768         // > "acquire" operation before deleting the object.
769         //
770         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
771         atomic::fence(Acquire);
772
773         unsafe {
774             self.drop_slow();
775         }
776     }
777 }
778
779 impl<T> Weak<T> {
780     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
781     /// it. Calling [`upgrade`] on the return value always gives [`None`].
782     ///
783     /// [`upgrade`]: struct.Weak.html#method.upgrade
784     /// [`None`]: ../../std/option/enum.Option.html#variant.None
785     ///
786     /// # Examples
787     ///
788     /// ```
789     /// use std::sync::Weak;
790     ///
791     /// let empty: Weak<i64> = Weak::new();
792     /// assert!(empty.upgrade().is_none());
793     /// ```
794     #[stable(feature = "downgraded_weak", since = "1.10.0")]
795     pub fn new() -> Weak<T> {
796         unsafe {
797             Weak {
798                 ptr: Shared::new(Box::into_raw(box ArcInner {
799                     strong: atomic::AtomicUsize::new(0),
800                     weak: atomic::AtomicUsize::new(1),
801                     data: uninitialized(),
802                 })),
803             }
804         }
805     }
806 }
807
808 impl<T: ?Sized> Weak<T> {
809     /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
810     /// the lifetime of the value if successful.
811     ///
812     /// Returns [`None`] if the value has since been dropped.
813     ///
814     /// [`Arc`]: struct.Arc.html
815     /// [`None`]: ../../std/option/enum.Option.html#variant.None
816     ///
817     /// # Examples
818     ///
819     /// ```
820     /// use std::sync::Arc;
821     ///
822     /// let five = Arc::new(5);
823     ///
824     /// let weak_five = Arc::downgrade(&five);
825     ///
826     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
827     /// assert!(strong_five.is_some());
828     ///
829     /// // Destroy all strong pointers.
830     /// drop(strong_five);
831     /// drop(five);
832     ///
833     /// assert!(weak_five.upgrade().is_none());
834     /// ```
835     #[stable(feature = "arc_weak", since = "1.4.0")]
836     pub fn upgrade(&self) -> Option<Arc<T>> {
837         // We use a CAS loop to increment the strong count instead of a
838         // fetch_add because once the count hits 0 it must never be above 0.
839         let inner = self.inner();
840
841         // Relaxed load because any write of 0 that we can observe
842         // leaves the field in a permanently zero state (so a
843         // "stale" read of 0 is fine), and any other value is
844         // confirmed via the CAS below.
845         let mut n = inner.strong.load(Relaxed);
846
847         loop {
848             if n == 0 {
849                 return None;
850             }
851
852             // See comments in `Arc::clone` for why we do this (for `mem::forget`).
853             if n > MAX_REFCOUNT {
854                 unsafe {
855                     abort();
856                 }
857             }
858
859             // Relaxed is valid for the same reason it is on Arc's Clone impl
860             match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
861                 Ok(_) => return Some(Arc { ptr: self.ptr }),
862                 Err(old) => n = old,
863             }
864         }
865     }
866
867     #[inline]
868     fn inner(&self) -> &ArcInner<T> {
869         // See comments above for why this is "safe"
870         unsafe { &**self.ptr }
871     }
872 }
873
874 #[stable(feature = "arc_weak", since = "1.4.0")]
875 impl<T: ?Sized> Clone for Weak<T> {
876     /// Makes a clone of the `Weak` pointer that points to the same value.
877     ///
878     /// # Examples
879     ///
880     /// ```
881     /// use std::sync::Arc;
882     ///
883     /// let weak_five = Arc::downgrade(&Arc::new(5));
884     ///
885     /// weak_five.clone();
886     /// ```
887     #[inline]
888     fn clone(&self) -> Weak<T> {
889         // See comments in Arc::clone() for why this is relaxed.  This can use a
890         // fetch_add (ignoring the lock) because the weak count is only locked
891         // where are *no other* weak pointers in existence. (So we can't be
892         // running this code in that case).
893         let old_size = self.inner().weak.fetch_add(1, Relaxed);
894
895         // See comments in Arc::clone() for why we do this (for mem::forget).
896         if old_size > MAX_REFCOUNT {
897             unsafe {
898                 abort();
899             }
900         }
901
902         return Weak { ptr: self.ptr };
903     }
904 }
905
906 #[stable(feature = "downgraded_weak", since = "1.10.0")]
907 impl<T> Default for Weak<T> {
908     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
909     /// it. Calling [`upgrade`] on the return value always gives [`None`].
910     ///
911     /// [`upgrade`]: struct.Weak.html#method.upgrade
912     /// [`None`]: ../../std/option/enum.Option.html#variant.None
913     ///
914     /// # Examples
915     ///
916     /// ```
917     /// use std::sync::Weak;
918     ///
919     /// let empty: Weak<i64> = Default::default();
920     /// assert!(empty.upgrade().is_none());
921     /// ```
922     fn default() -> Weak<T> {
923         Weak::new()
924     }
925 }
926
927 #[stable(feature = "arc_weak", since = "1.4.0")]
928 impl<T: ?Sized> Drop for Weak<T> {
929     /// Drops the `Weak` pointer.
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// use std::sync::Arc;
935     ///
936     /// struct Foo;
937     ///
938     /// impl Drop for Foo {
939     ///     fn drop(&mut self) {
940     ///         println!("dropped!");
941     ///     }
942     /// }
943     ///
944     /// let foo = Arc::new(Foo);
945     /// let weak_foo = Arc::downgrade(&foo);
946     /// let other_weak_foo = weak_foo.clone();
947     ///
948     /// drop(weak_foo);   // Doesn't print anything
949     /// drop(foo);        // Prints "dropped!"
950     ///
951     /// assert!(other_weak_foo.upgrade().is_none());
952     /// ```
953     fn drop(&mut self) {
954         let ptr = *self.ptr;
955
956         // If we find out that we were the last weak pointer, then its time to
957         // deallocate the data entirely. See the discussion in Arc::drop() about
958         // the memory orderings
959         //
960         // It's not necessary to check for the locked state here, because the
961         // weak count can only be locked if there was precisely one weak ref,
962         // meaning that drop could only subsequently run ON that remaining weak
963         // ref, which can only happen after the lock is released.
964         if self.inner().weak.fetch_sub(1, Release) == 1 {
965             atomic::fence(Acquire);
966             unsafe { deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) }
967         }
968     }
969 }
970
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
973     /// Equality for two `Arc`s.
974     ///
975     /// Two `Arc`s are equal if their inner values are equal.
976     ///
977     /// # Examples
978     ///
979     /// ```
980     /// use std::sync::Arc;
981     ///
982     /// let five = Arc::new(5);
983     ///
984     /// assert!(five == Arc::new(5));
985     /// ```
986     fn eq(&self, other: &Arc<T>) -> bool {
987         *(*self) == *(*other)
988     }
989
990     /// Inequality for two `Arc`s.
991     ///
992     /// Two `Arc`s are unequal if their inner values are unequal.
993     ///
994     /// # Examples
995     ///
996     /// ```
997     /// use std::sync::Arc;
998     ///
999     /// let five = Arc::new(5);
1000     ///
1001     /// assert!(five != Arc::new(6));
1002     /// ```
1003     fn ne(&self, other: &Arc<T>) -> bool {
1004         *(*self) != *(*other)
1005     }
1006 }
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1009     /// Partial comparison for two `Arc`s.
1010     ///
1011     /// The two are compared by calling `partial_cmp()` on their inner values.
1012     ///
1013     /// # Examples
1014     ///
1015     /// ```
1016     /// use std::sync::Arc;
1017     /// use std::cmp::Ordering;
1018     ///
1019     /// let five = Arc::new(5);
1020     ///
1021     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1022     /// ```
1023     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1024         (**self).partial_cmp(&**other)
1025     }
1026
1027     /// Less-than comparison for two `Arc`s.
1028     ///
1029     /// The two are compared by calling `<` on their inner values.
1030     ///
1031     /// # Examples
1032     ///
1033     /// ```
1034     /// use std::sync::Arc;
1035     ///
1036     /// let five = Arc::new(5);
1037     ///
1038     /// assert!(five < Arc::new(6));
1039     /// ```
1040     fn lt(&self, other: &Arc<T>) -> bool {
1041         *(*self) < *(*other)
1042     }
1043
1044     /// 'Less than or equal to' comparison for two `Arc`s.
1045     ///
1046     /// The two are compared by calling `<=` on their inner values.
1047     ///
1048     /// # Examples
1049     ///
1050     /// ```
1051     /// use std::sync::Arc;
1052     ///
1053     /// let five = Arc::new(5);
1054     ///
1055     /// assert!(five <= Arc::new(5));
1056     /// ```
1057     fn le(&self, other: &Arc<T>) -> bool {
1058         *(*self) <= *(*other)
1059     }
1060
1061     /// Greater-than comparison for two `Arc`s.
1062     ///
1063     /// The two are compared by calling `>` on their inner values.
1064     ///
1065     /// # Examples
1066     ///
1067     /// ```
1068     /// use std::sync::Arc;
1069     ///
1070     /// let five = Arc::new(5);
1071     ///
1072     /// assert!(five > Arc::new(4));
1073     /// ```
1074     fn gt(&self, other: &Arc<T>) -> bool {
1075         *(*self) > *(*other)
1076     }
1077
1078     /// 'Greater than or equal to' comparison for two `Arc`s.
1079     ///
1080     /// The two are compared by calling `>=` on their inner values.
1081     ///
1082     /// # Examples
1083     ///
1084     /// ```
1085     /// use std::sync::Arc;
1086     ///
1087     /// let five = Arc::new(5);
1088     ///
1089     /// assert!(five >= Arc::new(5));
1090     /// ```
1091     fn ge(&self, other: &Arc<T>) -> bool {
1092         *(*self) >= *(*other)
1093     }
1094 }
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<T: ?Sized + Ord> Ord for Arc<T> {
1097     /// Comparison for two `Arc`s.
1098     ///
1099     /// The two are compared by calling `cmp()` on their inner values.
1100     ///
1101     /// # Examples
1102     ///
1103     /// ```
1104     /// use std::sync::Arc;
1105     /// use std::cmp::Ordering;
1106     ///
1107     /// let five = Arc::new(5);
1108     ///
1109     /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1110     /// ```
1111     fn cmp(&self, other: &Arc<T>) -> Ordering {
1112         (**self).cmp(&**other)
1113     }
1114 }
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1117
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1120     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1121         fmt::Display::fmt(&**self, f)
1122     }
1123 }
1124
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1127     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128         fmt::Debug::fmt(&**self, f)
1129     }
1130 }
1131
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1134     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1135         fmt::Pointer::fmt(&*self.ptr, f)
1136     }
1137 }
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T: Default> Default for Arc<T> {
1141     /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1142     ///
1143     /// # Examples
1144     ///
1145     /// ```
1146     /// use std::sync::Arc;
1147     ///
1148     /// let x: Arc<i32> = Default::default();
1149     /// assert_eq!(*x, 0);
1150     /// ```
1151     fn default() -> Arc<T> {
1152         Arc::new(Default::default())
1153     }
1154 }
1155
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<T: ?Sized + Hash> Hash for Arc<T> {
1158     fn hash<H: Hasher>(&self, state: &mut H) {
1159         (**self).hash(state)
1160     }
1161 }
1162
1163 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1164 impl<T> From<T> for Arc<T> {
1165     fn from(t: T) -> Self {
1166         Arc::new(t)
1167     }
1168 }
1169
1170 #[cfg(test)]
1171 mod tests {
1172     use std::clone::Clone;
1173     use std::sync::mpsc::channel;
1174     use std::mem::drop;
1175     use std::ops::Drop;
1176     use std::option::Option;
1177     use std::option::Option::{None, Some};
1178     use std::sync::atomic;
1179     use std::sync::atomic::Ordering::{Acquire, SeqCst};
1180     use std::thread;
1181     use std::vec::Vec;
1182     use super::{Arc, Weak};
1183     use std::sync::Mutex;
1184     use std::convert::From;
1185
1186     struct Canary(*mut atomic::AtomicUsize);
1187
1188     impl Drop for Canary {
1189         fn drop(&mut self) {
1190             unsafe {
1191                 match *self {
1192                     Canary(c) => {
1193                         (*c).fetch_add(1, SeqCst);
1194                     }
1195                 }
1196             }
1197         }
1198     }
1199
1200     #[test]
1201     #[cfg_attr(target_os = "emscripten", ignore)]
1202     fn manually_share_arc() {
1203         let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1204         let arc_v = Arc::new(v);
1205
1206         let (tx, rx) = channel();
1207
1208         let _t = thread::spawn(move || {
1209             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
1210             assert_eq!((*arc_v)[3], 4);
1211         });
1212
1213         tx.send(arc_v.clone()).unwrap();
1214
1215         assert_eq!((*arc_v)[2], 3);
1216         assert_eq!((*arc_v)[4], 5);
1217     }
1218
1219     #[test]
1220     fn test_arc_get_mut() {
1221         let mut x = Arc::new(3);
1222         *Arc::get_mut(&mut x).unwrap() = 4;
1223         assert_eq!(*x, 4);
1224         let y = x.clone();
1225         assert!(Arc::get_mut(&mut x).is_none());
1226         drop(y);
1227         assert!(Arc::get_mut(&mut x).is_some());
1228         let _w = Arc::downgrade(&x);
1229         assert!(Arc::get_mut(&mut x).is_none());
1230     }
1231
1232     #[test]
1233     fn try_unwrap() {
1234         let x = Arc::new(3);
1235         assert_eq!(Arc::try_unwrap(x), Ok(3));
1236         let x = Arc::new(4);
1237         let _y = x.clone();
1238         assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1239         let x = Arc::new(5);
1240         let _w = Arc::downgrade(&x);
1241         assert_eq!(Arc::try_unwrap(x), Ok(5));
1242     }
1243
1244     #[test]
1245     fn into_from_raw() {
1246         let x = Arc::new(box "hello");
1247         let y = x.clone();
1248
1249         let x_ptr = Arc::into_raw(x);
1250         drop(y);
1251         unsafe {
1252             assert_eq!(**x_ptr, "hello");
1253
1254             let x = Arc::from_raw(x_ptr);
1255             assert_eq!(**x, "hello");
1256
1257             assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
1258         }
1259     }
1260
1261     #[test]
1262     fn test_cowarc_clone_make_mut() {
1263         let mut cow0 = Arc::new(75);
1264         let mut cow1 = cow0.clone();
1265         let mut cow2 = cow1.clone();
1266
1267         assert!(75 == *Arc::make_mut(&mut cow0));
1268         assert!(75 == *Arc::make_mut(&mut cow1));
1269         assert!(75 == *Arc::make_mut(&mut cow2));
1270
1271         *Arc::make_mut(&mut cow0) += 1;
1272         *Arc::make_mut(&mut cow1) += 2;
1273         *Arc::make_mut(&mut cow2) += 3;
1274
1275         assert!(76 == *cow0);
1276         assert!(77 == *cow1);
1277         assert!(78 == *cow2);
1278
1279         // none should point to the same backing memory
1280         assert!(*cow0 != *cow1);
1281         assert!(*cow0 != *cow2);
1282         assert!(*cow1 != *cow2);
1283     }
1284
1285     #[test]
1286     fn test_cowarc_clone_unique2() {
1287         let mut cow0 = Arc::new(75);
1288         let cow1 = cow0.clone();
1289         let cow2 = cow1.clone();
1290
1291         assert!(75 == *cow0);
1292         assert!(75 == *cow1);
1293         assert!(75 == *cow2);
1294
1295         *Arc::make_mut(&mut cow0) += 1;
1296         assert!(76 == *cow0);
1297         assert!(75 == *cow1);
1298         assert!(75 == *cow2);
1299
1300         // cow1 and cow2 should share the same contents
1301         // cow0 should have a unique reference
1302         assert!(*cow0 != *cow1);
1303         assert!(*cow0 != *cow2);
1304         assert!(*cow1 == *cow2);
1305     }
1306
1307     #[test]
1308     fn test_cowarc_clone_weak() {
1309         let mut cow0 = Arc::new(75);
1310         let cow1_weak = Arc::downgrade(&cow0);
1311
1312         assert!(75 == *cow0);
1313         assert!(75 == *cow1_weak.upgrade().unwrap());
1314
1315         *Arc::make_mut(&mut cow0) += 1;
1316
1317         assert!(76 == *cow0);
1318         assert!(cow1_weak.upgrade().is_none());
1319     }
1320
1321     #[test]
1322     fn test_live() {
1323         let x = Arc::new(5);
1324         let y = Arc::downgrade(&x);
1325         assert!(y.upgrade().is_some());
1326     }
1327
1328     #[test]
1329     fn test_dead() {
1330         let x = Arc::new(5);
1331         let y = Arc::downgrade(&x);
1332         drop(x);
1333         assert!(y.upgrade().is_none());
1334     }
1335
1336     #[test]
1337     fn weak_self_cyclic() {
1338         struct Cycle {
1339             x: Mutex<Option<Weak<Cycle>>>,
1340         }
1341
1342         let a = Arc::new(Cycle { x: Mutex::new(None) });
1343         let b = Arc::downgrade(&a.clone());
1344         *a.x.lock().unwrap() = Some(b);
1345
1346         // hopefully we don't double-free (or leak)...
1347     }
1348
1349     #[test]
1350     fn drop_arc() {
1351         let mut canary = atomic::AtomicUsize::new(0);
1352         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1353         drop(x);
1354         assert!(canary.load(Acquire) == 1);
1355     }
1356
1357     #[test]
1358     fn drop_arc_weak() {
1359         let mut canary = atomic::AtomicUsize::new(0);
1360         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1361         let arc_weak = Arc::downgrade(&arc);
1362         assert!(canary.load(Acquire) == 0);
1363         drop(arc);
1364         assert!(canary.load(Acquire) == 1);
1365         drop(arc_weak);
1366     }
1367
1368     #[test]
1369     fn test_strong_count() {
1370         let a = Arc::new(0);
1371         assert!(Arc::strong_count(&a) == 1);
1372         let w = Arc::downgrade(&a);
1373         assert!(Arc::strong_count(&a) == 1);
1374         let b = w.upgrade().expect("");
1375         assert!(Arc::strong_count(&b) == 2);
1376         assert!(Arc::strong_count(&a) == 2);
1377         drop(w);
1378         drop(a);
1379         assert!(Arc::strong_count(&b) == 1);
1380         let c = b.clone();
1381         assert!(Arc::strong_count(&b) == 2);
1382         assert!(Arc::strong_count(&c) == 2);
1383     }
1384
1385     #[test]
1386     fn test_weak_count() {
1387         let a = Arc::new(0);
1388         assert!(Arc::strong_count(&a) == 1);
1389         assert!(Arc::weak_count(&a) == 0);
1390         let w = Arc::downgrade(&a);
1391         assert!(Arc::strong_count(&a) == 1);
1392         assert!(Arc::weak_count(&a) == 1);
1393         let x = w.clone();
1394         assert!(Arc::weak_count(&a) == 2);
1395         drop(w);
1396         drop(x);
1397         assert!(Arc::strong_count(&a) == 1);
1398         assert!(Arc::weak_count(&a) == 0);
1399         let c = a.clone();
1400         assert!(Arc::strong_count(&a) == 2);
1401         assert!(Arc::weak_count(&a) == 0);
1402         let d = Arc::downgrade(&c);
1403         assert!(Arc::weak_count(&c) == 1);
1404         assert!(Arc::strong_count(&c) == 2);
1405
1406         drop(a);
1407         drop(c);
1408         drop(d);
1409     }
1410
1411     #[test]
1412     fn show_arc() {
1413         let a = Arc::new(5);
1414         assert_eq!(format!("{:?}", a), "5");
1415     }
1416
1417     // Make sure deriving works with Arc<T>
1418     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1419     struct Foo {
1420         inner: Arc<i32>,
1421     }
1422
1423     #[test]
1424     fn test_unsized() {
1425         let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1426         assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1427         let y = Arc::downgrade(&x.clone());
1428         drop(x);
1429         assert!(y.upgrade().is_none());
1430     }
1431
1432     #[test]
1433     fn test_from_owned() {
1434         let foo = 123;
1435         let foo_arc = Arc::from(foo);
1436         assert!(123 == *foo_arc);
1437     }
1438
1439     #[test]
1440     fn test_new_weak() {
1441         let foo: Weak<usize> = Weak::new();
1442         assert!(foo.upgrade().is_none());
1443     }
1444
1445     #[test]
1446     fn test_ptr_eq() {
1447         let five = Arc::new(5);
1448         let same_five = five.clone();
1449         let other_five = Arc::new(5);
1450
1451         assert!(Arc::ptr_eq(&five, &same_five));
1452         assert!(!Arc::ptr_eq(&five, &other_five));
1453     }
1454 }
1455
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
1458     fn borrow(&self) -> &T {
1459         &**self
1460     }
1461 }
1462
1463 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1464 impl<T: ?Sized> AsRef<T> for Arc<T> {
1465     fn as_ref(&self) -> &T {
1466         &**self
1467     }
1468 }