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