]> git.lizzy.rs Git - rust.git/blob - src/liballoc/sync.rs
submodule: update rls from c9d25b667a to f331ff7
[rust.git] / src / liballoc / sync.rs
1 #![stable(feature = "rust1", since = "1.0.0")]
2
3 //! Thread-safe reference-counting pointers.
4 //!
5 //! See the [`Arc<T>`][arc] documentation for more details.
6 //!
7 //! [arc]: struct.Arc.html
8
9 use core::any::Any;
10 use core::sync::atomic;
11 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
12 use core::borrow;
13 use core::fmt;
14 use core::cmp::{self, Ordering};
15 use core::intrinsics::abort;
16 use core::mem::{self, align_of_val, size_of_val};
17 use core::ops::{Deref, Receiver};
18 use core::ops::{CoerceUnsized, DispatchFromDyn};
19 use core::pin::Pin;
20 use core::ptr::{self, NonNull};
21 use core::marker::{Unpin, Unsize, PhantomData};
22 use core::hash::{Hash, Hasher};
23 use core::{isize, usize};
24 use core::convert::From;
25
26 use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
27 use boxed::Box;
28 use rc::is_dangling;
29 use string::String;
30 use vec::Vec;
31
32 /// A soft limit on the amount of references that may be made to an `Arc`.
33 ///
34 /// Going above this limit will abort your program (although not
35 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
36 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
37
38 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
39 /// Reference Counted'.
40 ///
41 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
42 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
43 /// a new `Arc` instance, which points to the same value on the heap as the
44 /// source `Arc`, while increasing a reference count. When the last `Arc`
45 /// pointer to a given value is destroyed, the pointed-to value is also
46 /// destroyed.
47 ///
48 /// Shared references in Rust disallow mutation by default, and `Arc` is no
49 /// exception: you cannot generally obtain a mutable reference to something
50 /// inside an `Arc`. If you need to mutate through an `Arc`, use
51 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
52 /// types.
53 ///
54 /// ## Thread Safety
55 ///
56 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
57 /// counting. This means that it is thread-safe. The disadvantage is that
58 /// atomic operations are more expensive than ordinary memory accesses. If you
59 /// are not sharing reference-counted values between threads, consider using
60 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
61 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
62 /// However, a library might choose `Arc<T>` in order to give library consumers
63 /// more flexibility.
64 ///
65 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
66 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
67 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
68 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
69 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
70 /// data, but it  doesn't add thread safety to its data. Consider
71 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
72 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
73 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
74 /// non-atomic operations.
75 ///
76 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
77 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
78 ///
79 /// ## Breaking cycles with `Weak`
80 ///
81 /// The [`downgrade`][downgrade] method can be used to create a non-owning
82 /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d
83 /// to an `Arc`, but this will return [`None`] if the value has already been
84 /// dropped.
85 ///
86 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
87 /// [`Weak`][weak] is used to break cycles. For example, a tree could have
88 /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak]
89 /// pointers from children back to their parents.
90 ///
91 /// # Cloning references
92 ///
93 /// Creating a new reference from an existing reference counted pointer is done using the
94 /// `Clone` trait implemented for [`Arc<T>`][arc] and [`Weak<T>`][weak].
95 ///
96 /// ```
97 /// use std::sync::Arc;
98 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
99 /// // The two syntaxes below are equivalent.
100 /// let a = foo.clone();
101 /// let b = Arc::clone(&foo);
102 /// // a, b, and foo are all Arcs that point to the same memory location
103 /// ```
104 ///
105 /// The [`Arc::clone(&from)`] syntax is the most idiomatic because it conveys more explicitly
106 /// the meaning of the code. In the example above, this syntax makes it easier to see that
107 /// this code is creating a new reference rather than copying the whole content of foo.
108 ///
109 /// ## `Deref` behavior
110 ///
111 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
112 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
113 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are associated
114 /// functions, called using function-like syntax:
115 ///
116 /// ```
117 /// use std::sync::Arc;
118 /// let my_arc = Arc::new(());
119 ///
120 /// Arc::downgrade(&my_arc);
121 /// ```
122 ///
123 /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have
124 /// already been destroyed.
125 ///
126 /// [arc]: struct.Arc.html
127 /// [weak]: struct.Weak.html
128 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
129 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
130 /// [mutex]: ../../std/sync/struct.Mutex.html
131 /// [rwlock]: ../../std/sync/struct.RwLock.html
132 /// [atomic]: ../../std/sync/atomic/index.html
133 /// [`Send`]: ../../std/marker/trait.Send.html
134 /// [`Sync`]: ../../std/marker/trait.Sync.html
135 /// [deref]: ../../std/ops/trait.Deref.html
136 /// [downgrade]: struct.Arc.html#method.downgrade
137 /// [upgrade]: struct.Weak.html#method.upgrade
138 /// [`None`]: ../../std/option/enum.Option.html#variant.None
139 /// [`RefCell<T>`]: ../../std/cell/struct.RefCell.html
140 /// [`std::sync`]: ../../std/sync/index.html
141 /// [`Arc::clone(&from)`]: #method.clone
142 ///
143 /// # Examples
144 ///
145 /// Sharing some immutable data between threads:
146 ///
147 // Note that we **do not** run these tests here. The windows builders get super
148 // unhappy if a thread outlives the main thread and then exits at the same time
149 // (something deadlocks) so we just avoid this entirely by not running these
150 // tests.
151 /// ```no_run
152 /// use std::sync::Arc;
153 /// use std::thread;
154 ///
155 /// let five = Arc::new(5);
156 ///
157 /// for _ in 0..10 {
158 ///     let five = Arc::clone(&five);
159 ///
160 ///     thread::spawn(move || {
161 ///         println!("{:?}", five);
162 ///     });
163 /// }
164 /// ```
165 ///
166 /// Sharing a mutable [`AtomicUsize`]:
167 ///
168 /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html
169 ///
170 /// ```no_run
171 /// use std::sync::Arc;
172 /// use std::sync::atomic::{AtomicUsize, Ordering};
173 /// use std::thread;
174 ///
175 /// let val = Arc::new(AtomicUsize::new(5));
176 ///
177 /// for _ in 0..10 {
178 ///     let val = Arc::clone(&val);
179 ///
180 ///     thread::spawn(move || {
181 ///         let v = val.fetch_add(1, Ordering::SeqCst);
182 ///         println!("{:?}", v);
183 ///     });
184 /// }
185 /// ```
186 ///
187 /// See the [`rc` documentation][rc_examples] for more examples of reference
188 /// counting in general.
189 ///
190 /// [rc_examples]: ../../std/rc/index.html#examples
191 #[cfg_attr(not(test), lang = "arc")]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub struct Arc<T: ?Sized> {
194     ptr: NonNull<ArcInner<T>>,
195     phantom: PhantomData<T>,
196 }
197
198 #[stable(feature = "rust1", since = "1.0.0")]
199 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
200 #[stable(feature = "rust1", since = "1.0.0")]
201 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
202
203 #[unstable(feature = "coerce_unsized", issue = "27732")]
204 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
205
206 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
207 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}
208
209 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
210 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
211 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
212 ///
213 /// Since a `Weak` reference does not count towards ownership, it will not
214 /// prevent the inner value from being dropped, and `Weak` itself makes no
215 /// guarantees about the value still being present and may return [`None`]
216 /// when [`upgrade`]d.
217 ///
218 /// A `Weak` pointer is useful for keeping a temporary reference to the value
219 /// within [`Arc`] without extending its lifetime. It is also used to prevent
220 /// circular references between [`Arc`] pointers, since mutual owning references
221 /// would never allow either [`Arc`] to be dropped. For example, a tree could
222 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
223 /// pointers from children back to their parents.
224 ///
225 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
226 ///
227 /// [`Arc`]: struct.Arc.html
228 /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade
229 /// [`upgrade`]: struct.Weak.html#method.upgrade
230 /// [`Option`]: ../../std/option/enum.Option.html
231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
232 #[stable(feature = "arc_weak", since = "1.4.0")]
233 pub struct Weak<T: ?Sized> {
234     // This is a `NonNull` to allow optimizing the size of this type in enums,
235     // but it is not necessarily a valid pointer.
236     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
237     // to allocate space on the heap.  That's not a value a real pointer
238     // will ever have because RcBox has alignment at least 2.
239     ptr: NonNull<ArcInner<T>>,
240 }
241
242 #[stable(feature = "arc_weak", since = "1.4.0")]
243 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
244 #[stable(feature = "arc_weak", since = "1.4.0")]
245 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
246
247 #[unstable(feature = "coerce_unsized", issue = "27732")]
248 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
249 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
250 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
251
252 #[stable(feature = "arc_weak", since = "1.4.0")]
253 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
254     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255         write!(f, "(Weak)")
256     }
257 }
258
259 struct ArcInner<T: ?Sized> {
260     strong: atomic::AtomicUsize,
261
262     // the value usize::MAX acts as a sentinel for temporarily "locking" the
263     // ability to upgrade weak pointers or downgrade strong ones; this is used
264     // to avoid races in `make_mut` and `get_mut`.
265     weak: atomic::AtomicUsize,
266
267     data: T,
268 }
269
270 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
271 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
272
273 impl<T> Arc<T> {
274     /// Constructs a new `Arc<T>`.
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use std::sync::Arc;
280     ///
281     /// let five = Arc::new(5);
282     /// ```
283     #[inline]
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn new(data: T) -> Arc<T> {
286         // Start the weak pointer count as 1 which is the weak pointer that's
287         // held by all the strong pointers (kinda), see std/rc.rs for more info
288         let x: Box<_> = box ArcInner {
289             strong: atomic::AtomicUsize::new(1),
290             weak: atomic::AtomicUsize::new(1),
291             data,
292         };
293         Arc { ptr: Box::into_raw_non_null(x), phantom: PhantomData }
294     }
295
296     /// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
297     /// `data` will be pinned in memory and unable to be moved.
298     #[stable(feature = "pin", since = "1.33.0")]
299     pub fn pin(data: T) -> Pin<Arc<T>> {
300         unsafe { Pin::new_unchecked(Arc::new(data)) }
301     }
302
303     /// Returns the contained value, if the `Arc` has exactly one strong reference.
304     ///
305     /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was
306     /// passed in.
307     ///
308     /// This will succeed even if there are outstanding weak references.
309     ///
310     /// [result]: ../../std/result/enum.Result.html
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// use std::sync::Arc;
316     ///
317     /// let x = Arc::new(3);
318     /// assert_eq!(Arc::try_unwrap(x), Ok(3));
319     ///
320     /// let x = Arc::new(4);
321     /// let _y = Arc::clone(&x);
322     /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
323     /// ```
324     #[inline]
325     #[stable(feature = "arc_unique", since = "1.4.0")]
326     pub fn try_unwrap(this: Self) -> Result<T, Self> {
327         // See `drop` for why all these atomics are like this
328         if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() {
329             return Err(this);
330         }
331
332         atomic::fence(Acquire);
333
334         unsafe {
335             let elem = ptr::read(&this.ptr.as_ref().data);
336
337             // Make a weak pointer to clean up the implicit strong-weak reference
338             let _weak = Weak { ptr: this.ptr };
339             mem::forget(this);
340
341             Ok(elem)
342         }
343     }
344 }
345
346 impl<T: ?Sized> Arc<T> {
347     /// Consumes the `Arc`, returning the wrapped pointer.
348     ///
349     /// To avoid a memory leak the pointer must be converted back to an `Arc` using
350     /// [`Arc::from_raw`][from_raw].
351     ///
352     /// [from_raw]: struct.Arc.html#method.from_raw
353     ///
354     /// # Examples
355     ///
356     /// ```
357     /// use std::sync::Arc;
358     ///
359     /// let x = Arc::new(10);
360     /// let x_ptr = Arc::into_raw(x);
361     /// assert_eq!(unsafe { *x_ptr }, 10);
362     /// ```
363     #[stable(feature = "rc_raw", since = "1.17.0")]
364     pub fn into_raw(this: Self) -> *const T {
365         let ptr: *const T = &*this;
366         mem::forget(this);
367         ptr
368     }
369
370     /// Constructs an `Arc` from a raw pointer.
371     ///
372     /// The raw pointer must have been previously returned by a call to a
373     /// [`Arc::into_raw`][into_raw].
374     ///
375     /// This function is unsafe because improper use may lead to memory problems. For example, a
376     /// double-free may occur if the function is called twice on the same raw pointer.
377     ///
378     /// [into_raw]: struct.Arc.html#method.into_raw
379     ///
380     /// # Examples
381     ///
382     /// ```
383     /// use std::sync::Arc;
384     ///
385     /// let x = Arc::new(10);
386     /// let x_ptr = Arc::into_raw(x);
387     ///
388     /// unsafe {
389     ///     // Convert back to an `Arc` to prevent leak.
390     ///     let x = Arc::from_raw(x_ptr);
391     ///     assert_eq!(*x, 10);
392     ///
393     ///     // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe.
394     /// }
395     ///
396     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
397     /// ```
398     #[stable(feature = "rc_raw", since = "1.17.0")]
399     pub unsafe fn from_raw(ptr: *const T) -> Self {
400         // Align the unsized value to the end of the ArcInner.
401         // Because it is ?Sized, it will always be the last field in memory.
402         let align = align_of_val(&*ptr);
403         let layout = Layout::new::<ArcInner<()>>();
404         let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
405
406         // Reverse the offset to find the original ArcInner.
407         let fake_ptr = ptr as *mut ArcInner<T>;
408         let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
409
410         Arc {
411             ptr: NonNull::new_unchecked(arc_ptr),
412             phantom: PhantomData,
413         }
414     }
415
416     /// Consumes the `Arc`, returning the wrapped pointer as `NonNull<T>`.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// #![feature(rc_into_raw_non_null)]
422     ///
423     /// use std::sync::Arc;
424     ///
425     /// let x = Arc::new(10);
426     /// let ptr = Arc::into_raw_non_null(x);
427     /// let deref = unsafe { *ptr.as_ref() };
428     /// assert_eq!(deref, 10);
429     /// ```
430     #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
431     #[inline]
432     pub fn into_raw_non_null(this: Self) -> NonNull<T> {
433         // safe because Arc guarantees its pointer is non-null
434         unsafe { NonNull::new_unchecked(Arc::into_raw(this) as *mut _) }
435     }
436
437     /// Creates a new [`Weak`][weak] pointer to this value.
438     ///
439     /// [weak]: struct.Weak.html
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::sync::Arc;
445     ///
446     /// let five = Arc::new(5);
447     ///
448     /// let weak_five = Arc::downgrade(&five);
449     /// ```
450     #[stable(feature = "arc_weak", since = "1.4.0")]
451     pub fn downgrade(this: &Self) -> Weak<T> {
452         // This Relaxed is OK because we're checking the value in the CAS
453         // below.
454         let mut cur = this.inner().weak.load(Relaxed);
455
456         loop {
457             // check if the weak counter is currently "locked"; if so, spin.
458             if cur == usize::MAX {
459                 cur = this.inner().weak.load(Relaxed);
460                 continue;
461             }
462
463             // NOTE: this code currently ignores the possibility of overflow
464             // into usize::MAX; in general both Rc and Arc need to be adjusted
465             // to deal with overflow.
466
467             // Unlike with Clone(), we need this to be an Acquire read to
468             // synchronize with the write coming from `is_unique`, so that the
469             // events prior to that write happen before this read.
470             match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
471                 Ok(_) => {
472                     // Make sure we do not create a dangling Weak
473                     debug_assert!(!is_dangling(this.ptr));
474                     return Weak { ptr: this.ptr };
475                 }
476                 Err(old) => cur = old,
477             }
478         }
479     }
480
481     /// Gets the number of [`Weak`][weak] pointers to this value.
482     ///
483     /// [weak]: struct.Weak.html
484     ///
485     /// # Safety
486     ///
487     /// This method by itself is safe, but using it correctly requires extra care.
488     /// Another thread can change the weak count at any time,
489     /// including potentially between calling this method and acting on the result.
490     ///
491     /// # Examples
492     ///
493     /// ```
494     /// use std::sync::Arc;
495     ///
496     /// let five = Arc::new(5);
497     /// let _weak_five = Arc::downgrade(&five);
498     ///
499     /// // This assertion is deterministic because we haven't shared
500     /// // the `Arc` or `Weak` between threads.
501     /// assert_eq!(1, Arc::weak_count(&five));
502     /// ```
503     #[inline]
504     #[stable(feature = "arc_counts", since = "1.15.0")]
505     pub fn weak_count(this: &Self) -> usize {
506         let cnt = this.inner().weak.load(SeqCst);
507         // If the weak count is currently locked, the value of the
508         // count was 0 just before taking the lock.
509         if cnt == usize::MAX { 0 } else { cnt - 1 }
510     }
511
512     /// Gets the number of strong (`Arc`) pointers to this value.
513     ///
514     /// # Safety
515     ///
516     /// This method by itself is safe, but using it correctly requires extra care.
517     /// Another thread can change the strong count at any time,
518     /// including potentially between calling this method and acting on the result.
519     ///
520     /// # Examples
521     ///
522     /// ```
523     /// use std::sync::Arc;
524     ///
525     /// let five = Arc::new(5);
526     /// let _also_five = Arc::clone(&five);
527     ///
528     /// // This assertion is deterministic because we haven't shared
529     /// // the `Arc` between threads.
530     /// assert_eq!(2, Arc::strong_count(&five));
531     /// ```
532     #[inline]
533     #[stable(feature = "arc_counts", since = "1.15.0")]
534     pub fn strong_count(this: &Self) -> usize {
535         this.inner().strong.load(SeqCst)
536     }
537
538     #[inline]
539     fn inner(&self) -> &ArcInner<T> {
540         // This unsafety is ok because while this arc is alive we're guaranteed
541         // that the inner pointer is valid. Furthermore, we know that the
542         // `ArcInner` structure itself is `Sync` because the inner data is
543         // `Sync` as well, so we're ok loaning out an immutable pointer to these
544         // contents.
545         unsafe { self.ptr.as_ref() }
546     }
547
548     // Non-inlined part of `drop`.
549     #[inline(never)]
550     unsafe fn drop_slow(&mut self) {
551         // Destroy the data at this time, even though we may not free the box
552         // allocation itself (there may still be weak pointers lying around).
553         ptr::drop_in_place(&mut self.ptr.as_mut().data);
554
555         if self.inner().weak.fetch_sub(1, Release) == 1 {
556             atomic::fence(Acquire);
557             Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
558         }
559     }
560
561     #[inline]
562     #[stable(feature = "ptr_eq", since = "1.17.0")]
563     /// Returns true if the two `Arc`s point to the same value (not
564     /// just values that compare as equal).
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// use std::sync::Arc;
570     ///
571     /// let five = Arc::new(5);
572     /// let same_five = Arc::clone(&five);
573     /// let other_five = Arc::new(5);
574     ///
575     /// assert!(Arc::ptr_eq(&five, &same_five));
576     /// assert!(!Arc::ptr_eq(&five, &other_five));
577     /// ```
578     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
579         this.ptr.as_ptr() == other.ptr.as_ptr()
580     }
581 }
582
583 impl<T: ?Sized> Arc<T> {
584     // Allocates an `ArcInner<T>` with sufficient space for an unsized value
585     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
586         // Calculate layout using the given value.
587         // Previously, layout was calculated on the expression
588         // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
589         // reference (see #54908).
590         let layout = Layout::new::<ArcInner<()>>()
591             .extend(Layout::for_value(&*ptr)).unwrap().0
592             .pad_to_align().unwrap();
593
594         let mem = Global.alloc(layout)
595             .unwrap_or_else(|_| handle_alloc_error(layout));
596
597         // Initialize the ArcInner
598         let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
599         debug_assert_eq!(Layout::for_value(&*inner), layout);
600
601         ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
602         ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
603
604         inner
605     }
606
607     fn from_box(v: Box<T>) -> Arc<T> {
608         unsafe {
609             let box_unique = Box::into_unique(v);
610             let bptr = box_unique.as_ptr();
611
612             let value_size = size_of_val(&*bptr);
613             let ptr = Self::allocate_for_ptr(bptr);
614
615             // Copy value as bytes
616             ptr::copy_nonoverlapping(
617                 bptr as *const T as *const u8,
618                 &mut (*ptr).data as *mut _ as *mut u8,
619                 value_size);
620
621             // Free the allocation without dropping its contents
622             box_free(box_unique);
623
624             Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
625         }
626     }
627 }
628
629 // Sets the data pointer of a `?Sized` raw pointer.
630 //
631 // For a slice/trait object, this sets the `data` field and leaves the rest
632 // unchanged. For a sized raw pointer, this simply sets the pointer.
633 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
634     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
635     ptr
636 }
637
638 impl<T> Arc<[T]> {
639     // Copy elements from slice into newly allocated Arc<[T]>
640     //
641     // Unsafe because the caller must either take ownership or bind `T: Copy`
642     unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
643         let v_ptr = v as *const [T];
644         let ptr = Self::allocate_for_ptr(v_ptr);
645
646         ptr::copy_nonoverlapping(
647             v.as_ptr(),
648             &mut (*ptr).data as *mut [T] as *mut T,
649             v.len());
650
651         Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
652     }
653 }
654
655 // Specialization trait used for From<&[T]>
656 trait ArcFromSlice<T> {
657     fn from_slice(slice: &[T]) -> Self;
658 }
659
660 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
661     #[inline]
662     default fn from_slice(v: &[T]) -> Self {
663         // Panic guard while cloning T elements.
664         // In the event of a panic, elements that have been written
665         // into the new ArcInner will be dropped, then the memory freed.
666         struct Guard<T> {
667             mem: NonNull<u8>,
668             elems: *mut T,
669             layout: Layout,
670             n_elems: usize,
671         }
672
673         impl<T> Drop for Guard<T> {
674             fn drop(&mut self) {
675                 use core::slice::from_raw_parts_mut;
676
677                 unsafe {
678                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
679                     ptr::drop_in_place(slice);
680
681                     Global.dealloc(self.mem.cast(), self.layout.clone());
682                 }
683             }
684         }
685
686         unsafe {
687             let v_ptr = v as *const [T];
688             let ptr = Self::allocate_for_ptr(v_ptr);
689
690             let mem = ptr as *mut _ as *mut u8;
691             let layout = Layout::for_value(&*ptr);
692
693             // Pointer to first element
694             let elems = &mut (*ptr).data as *mut [T] as *mut T;
695
696             let mut guard = Guard{
697                 mem: NonNull::new_unchecked(mem),
698                 elems: elems,
699                 layout: layout,
700                 n_elems: 0,
701             };
702
703             for (i, item) in v.iter().enumerate() {
704                 ptr::write(elems.add(i), item.clone());
705                 guard.n_elems += 1;
706             }
707
708             // All clear. Forget the guard so it doesn't free the new ArcInner.
709             mem::forget(guard);
710
711             Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
712         }
713     }
714 }
715
716 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
717     #[inline]
718     fn from_slice(v: &[T]) -> Self {
719         unsafe { Arc::copy_from_slice(v) }
720     }
721 }
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<T: ?Sized> Clone for Arc<T> {
725     /// Makes a clone of the `Arc` pointer.
726     ///
727     /// This creates another pointer to the same inner value, increasing the
728     /// strong reference count.
729     ///
730     /// # Examples
731     ///
732     /// ```
733     /// use std::sync::Arc;
734     ///
735     /// let five = Arc::new(5);
736     ///
737     /// let _ = Arc::clone(&five);
738     /// ```
739     #[inline]
740     fn clone(&self) -> Arc<T> {
741         // Using a relaxed ordering is alright here, as knowledge of the
742         // original reference prevents other threads from erroneously deleting
743         // the object.
744         //
745         // As explained in the [Boost documentation][1], Increasing the
746         // reference counter can always be done with memory_order_relaxed: New
747         // references to an object can only be formed from an existing
748         // reference, and passing an existing reference from one thread to
749         // another must already provide any required synchronization.
750         //
751         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
752         let old_size = self.inner().strong.fetch_add(1, Relaxed);
753
754         // However we need to guard against massive refcounts in case someone
755         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
756         // and users will use-after free. We racily saturate to `isize::MAX` on
757         // the assumption that there aren't ~2 billion threads incrementing
758         // the reference count at once. This branch will never be taken in
759         // any realistic program.
760         //
761         // We abort because such a program is incredibly degenerate, and we
762         // don't care to support it.
763         if old_size > MAX_REFCOUNT {
764             unsafe {
765                 abort();
766             }
767         }
768
769         Arc { ptr: self.ptr, phantom: PhantomData }
770     }
771 }
772
773 #[stable(feature = "rust1", since = "1.0.0")]
774 impl<T: ?Sized> Deref for Arc<T> {
775     type Target = T;
776
777     #[inline]
778     fn deref(&self) -> &T {
779         &self.inner().data
780     }
781 }
782
783 #[unstable(feature = "receiver_trait", issue = "0")]
784 impl<T: ?Sized> Receiver for Arc<T> {}
785
786 impl<T: Clone> Arc<T> {
787     /// Makes a mutable reference into the given `Arc`.
788     ///
789     /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
790     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
791     /// ensure unique ownership. This is also referred to as clone-on-write.
792     ///
793     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
794     ///
795     /// [weak]: struct.Weak.html
796     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
797     /// [get_mut]: struct.Arc.html#method.get_mut
798     ///
799     /// # Examples
800     ///
801     /// ```
802     /// use std::sync::Arc;
803     ///
804     /// let mut data = Arc::new(5);
805     ///
806     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
807     /// let mut other_data = Arc::clone(&data); // Won't clone inner data
808     /// *Arc::make_mut(&mut data) += 1;         // Clones inner data
809     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
810     /// *Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything
811     ///
812     /// // Now `data` and `other_data` point to different values.
813     /// assert_eq!(*data, 8);
814     /// assert_eq!(*other_data, 12);
815     /// ```
816     #[inline]
817     #[stable(feature = "arc_unique", since = "1.4.0")]
818     pub fn make_mut(this: &mut Self) -> &mut T {
819         // Note that we hold both a strong reference and a weak reference.
820         // Thus, releasing our strong reference only will not, by itself, cause
821         // the memory to be deallocated.
822         //
823         // Use Acquire to ensure that we see any writes to `weak` that happen
824         // before release writes (i.e., decrements) to `strong`. Since we hold a
825         // weak count, there's no chance the ArcInner itself could be
826         // deallocated.
827         if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
828             // Another strong pointer exists; clone
829             *this = Arc::new((**this).clone());
830         } else if this.inner().weak.load(Relaxed) != 1 {
831             // Relaxed suffices in the above because this is fundamentally an
832             // optimization: we are always racing with weak pointers being
833             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
834
835             // We removed the last strong ref, but there are additional weak
836             // refs remaining. We'll move the contents to a new Arc, and
837             // invalidate the other weak refs.
838
839             // Note that it is not possible for the read of `weak` to yield
840             // usize::MAX (i.e., locked), since the weak count can only be
841             // locked by a thread with a strong reference.
842
843             // Materialize our own implicit weak pointer, so that it can clean
844             // up the ArcInner as needed.
845             let weak = Weak { ptr: this.ptr };
846
847             // mark the data itself as already deallocated
848             unsafe {
849                 // there is no data race in the implicit write caused by `read`
850                 // here (due to zeroing) because data is no longer accessed by
851                 // other threads (due to there being no more strong refs at this
852                 // point).
853                 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
854                 mem::swap(this, &mut swap);
855                 mem::forget(swap);
856             }
857         } else {
858             // We were the sole reference of either kind; bump back up the
859             // strong ref count.
860             this.inner().strong.store(1, Release);
861         }
862
863         // As with `get_mut()`, the unsafety is ok because our reference was
864         // either unique to begin with, or became one upon cloning the contents.
865         unsafe {
866             &mut this.ptr.as_mut().data
867         }
868     }
869 }
870
871 impl<T: ?Sized> Arc<T> {
872     /// Returns a mutable reference to the inner value, if there are
873     /// no other `Arc` or [`Weak`][weak] pointers to the same value.
874     ///
875     /// Returns [`None`][option] otherwise, because it is not safe to
876     /// mutate a shared value.
877     ///
878     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
879     /// the inner value when it's shared.
880     ///
881     /// [weak]: struct.Weak.html
882     /// [option]: ../../std/option/enum.Option.html
883     /// [make_mut]: struct.Arc.html#method.make_mut
884     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
885     ///
886     /// # Examples
887     ///
888     /// ```
889     /// use std::sync::Arc;
890     ///
891     /// let mut x = Arc::new(3);
892     /// *Arc::get_mut(&mut x).unwrap() = 4;
893     /// assert_eq!(*x, 4);
894     ///
895     /// let _y = Arc::clone(&x);
896     /// assert!(Arc::get_mut(&mut x).is_none());
897     /// ```
898     #[inline]
899     #[stable(feature = "arc_unique", since = "1.4.0")]
900     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
901         if this.is_unique() {
902             // This unsafety is ok because we're guaranteed that the pointer
903             // returned is the *only* pointer that will ever be returned to T. Our
904             // reference count is guaranteed to be 1 at this point, and we required
905             // the Arc itself to be `mut`, so we're returning the only possible
906             // reference to the inner data.
907             unsafe {
908                 Some(&mut this.ptr.as_mut().data)
909             }
910         } else {
911             None
912         }
913     }
914
915     /// Determine whether this is the unique reference (including weak refs) to
916     /// the underlying data.
917     ///
918     /// Note that this requires locking the weak ref count.
919     fn is_unique(&mut self) -> bool {
920         // lock the weak pointer count if we appear to be the sole weak pointer
921         // holder.
922         //
923         // The acquire label here ensures a happens-before relationship with any
924         // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
925         // of the `weak` count (via `Weak::drop`, which uses release).  If the upgraded
926         // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
927         if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
928             // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
929             // counter in `drop` -- the only access that happens when any but the last reference
930             // is being dropped.
931             let unique = self.inner().strong.load(Acquire) == 1;
932
933             // The release write here synchronizes with a read in `downgrade`,
934             // effectively preventing the above read of `strong` from happening
935             // after the write.
936             self.inner().weak.store(1, Release); // release the lock
937             unique
938         } else {
939             false
940         }
941     }
942 }
943
944 #[stable(feature = "rust1", since = "1.0.0")]
945 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
946     /// Drops the `Arc`.
947     ///
948     /// This will decrement the strong reference count. If the strong reference
949     /// count reaches zero then the only other references (if any) are
950     /// [`Weak`], so we `drop` the inner value.
951     ///
952     /// # Examples
953     ///
954     /// ```
955     /// use std::sync::Arc;
956     ///
957     /// struct Foo;
958     ///
959     /// impl Drop for Foo {
960     ///     fn drop(&mut self) {
961     ///         println!("dropped!");
962     ///     }
963     /// }
964     ///
965     /// let foo  = Arc::new(Foo);
966     /// let foo2 = Arc::clone(&foo);
967     ///
968     /// drop(foo);    // Doesn't print anything
969     /// drop(foo2);   // Prints "dropped!"
970     /// ```
971     ///
972     /// [`Weak`]: ../../std/sync/struct.Weak.html
973     #[inline]
974     fn drop(&mut self) {
975         // Because `fetch_sub` is already atomic, we do not need to synchronize
976         // with other threads unless we are going to delete the object. This
977         // same logic applies to the below `fetch_sub` to the `weak` count.
978         if self.inner().strong.fetch_sub(1, Release) != 1 {
979             return;
980         }
981
982         // This fence is needed to prevent reordering of use of the data and
983         // deletion of the data.  Because it is marked `Release`, the decreasing
984         // of the reference count synchronizes with this `Acquire` fence. This
985         // means that use of the data happens before decreasing the reference
986         // count, which happens before this fence, which happens before the
987         // deletion of the data.
988         //
989         // As explained in the [Boost documentation][1],
990         //
991         // > It is important to enforce any possible access to the object in one
992         // > thread (through an existing reference) to *happen before* deleting
993         // > the object in a different thread. This is achieved by a "release"
994         // > operation after dropping a reference (any access to the object
995         // > through this reference must obviously happened before), and an
996         // > "acquire" operation before deleting the object.
997         //
998         // In particular, while the contents of an Arc are usually immutable, it's
999         // possible to have interior writes to something like a Mutex<T>. Since a
1000         // Mutex is not acquired when it is deleted, we can't rely on its
1001         // synchronization logic to make writes in thread A visible to a destructor
1002         // running in thread B.
1003         //
1004         // Also note that the Acquire fence here could probably be replaced with an
1005         // Acquire load, which could improve performance in highly-contended
1006         // situations. See [2].
1007         //
1008         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1009         // [2]: (https://github.com/rust-lang/rust/pull/41714)
1010         atomic::fence(Acquire);
1011
1012         unsafe {
1013             self.drop_slow();
1014         }
1015     }
1016 }
1017
1018 impl Arc<dyn Any + Send + Sync> {
1019     #[inline]
1020     #[stable(feature = "rc_downcast", since = "1.29.0")]
1021     /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1022     ///
1023     /// # Examples
1024     ///
1025     /// ```
1026     /// use std::any::Any;
1027     /// use std::sync::Arc;
1028     ///
1029     /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1030     ///     if let Ok(string) = value.downcast::<String>() {
1031     ///         println!("String ({}): {}", string.len(), string);
1032     ///     }
1033     /// }
1034     ///
1035     /// fn main() {
1036     ///     let my_string = "Hello World".to_string();
1037     ///     print_if_string(Arc::new(my_string));
1038     ///     print_if_string(Arc::new(0i8));
1039     /// }
1040     /// ```
1041     pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1042     where
1043         T: Any + Send + Sync + 'static,
1044     {
1045         if (*self).is::<T>() {
1046             let ptr = self.ptr.cast::<ArcInner<T>>();
1047             mem::forget(self);
1048             Ok(Arc { ptr, phantom: PhantomData })
1049         } else {
1050             Err(self)
1051         }
1052     }
1053 }
1054
1055 impl<T> Weak<T> {
1056     /// Constructs a new `Weak<T>`, without allocating any memory.
1057     /// Calling [`upgrade`] on the return value always gives [`None`].
1058     ///
1059     /// [`upgrade`]: struct.Weak.html#method.upgrade
1060     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1061     ///
1062     /// # Examples
1063     ///
1064     /// ```
1065     /// use std::sync::Weak;
1066     ///
1067     /// let empty: Weak<i64> = Weak::new();
1068     /// assert!(empty.upgrade().is_none());
1069     /// ```
1070     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1071     pub fn new() -> Weak<T> {
1072         Weak {
1073             ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0"),
1074         }
1075     }
1076 }
1077
1078 impl<T: ?Sized> Weak<T> {
1079     /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
1080     /// the lifetime of the value if successful.
1081     ///
1082     /// Returns [`None`] if the value has since been dropped.
1083     ///
1084     /// [`Arc`]: struct.Arc.html
1085     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1086     ///
1087     /// # Examples
1088     ///
1089     /// ```
1090     /// use std::sync::Arc;
1091     ///
1092     /// let five = Arc::new(5);
1093     ///
1094     /// let weak_five = Arc::downgrade(&five);
1095     ///
1096     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1097     /// assert!(strong_five.is_some());
1098     ///
1099     /// // Destroy all strong pointers.
1100     /// drop(strong_five);
1101     /// drop(five);
1102     ///
1103     /// assert!(weak_five.upgrade().is_none());
1104     /// ```
1105     #[stable(feature = "arc_weak", since = "1.4.0")]
1106     pub fn upgrade(&self) -> Option<Arc<T>> {
1107         // We use a CAS loop to increment the strong count instead of a
1108         // fetch_add because once the count hits 0 it must never be above 0.
1109         let inner = self.inner()?;
1110
1111         // Relaxed load because any write of 0 that we can observe
1112         // leaves the field in a permanently zero state (so a
1113         // "stale" read of 0 is fine), and any other value is
1114         // confirmed via the CAS below.
1115         let mut n = inner.strong.load(Relaxed);
1116
1117         loop {
1118             if n == 0 {
1119                 return None;
1120             }
1121
1122             // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1123             if n > MAX_REFCOUNT {
1124                 unsafe {
1125                     abort();
1126                 }
1127             }
1128
1129             // Relaxed is valid for the same reason it is on Arc's Clone impl
1130             match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
1131                 Ok(_) => return Some(Arc {
1132                     // null checked above
1133                     ptr: self.ptr,
1134                     phantom: PhantomData,
1135                 }),
1136                 Err(old) => n = old,
1137             }
1138         }
1139     }
1140
1141     /// Gets the number of strong (`Arc`) pointers pointing to this value.
1142     ///
1143     /// If `self` was created using [`Weak::new`], this will return 0.
1144     ///
1145     /// [`Weak::new`]: #method.new
1146     #[unstable(feature = "weak_counts", issue = "57977")]
1147     pub fn strong_count(&self) -> usize {
1148         if let Some(inner) = self.inner() {
1149             inner.strong.load(SeqCst)
1150         } else {
1151             0
1152         }
1153     }
1154
1155     /// Gets an approximation of the number of `Weak` pointers pointing to this
1156     /// value.
1157     ///
1158     /// If `self` was created using [`Weak::new`], this will return 0. If not,
1159     /// the returned value is at least 1, since `self` still points to the
1160     /// value.
1161     ///
1162     /// # Accuracy
1163     ///
1164     /// Due to implementation details, the returned value can be off by 1 in
1165     /// either direction when other threads are manipulating any `Arc`s or
1166     /// `Weak`s pointing to the same value.
1167     ///
1168     /// [`Weak::new`]: #method.new
1169     #[unstable(feature = "weak_counts", issue = "57977")]
1170     pub fn weak_count(&self) -> Option<usize> {
1171         // Due to the implicit weak pointer added when any strong pointers are
1172         // around, we cannot implement `weak_count` correctly since it
1173         // necessarily requires accessing the strong count and weak count in an
1174         // unsynchronized fashion. So this version is a bit racy.
1175         self.inner().map(|inner| {
1176             let strong = inner.strong.load(SeqCst);
1177             let weak = inner.weak.load(SeqCst);
1178             if strong == 0 {
1179                 // If the last `Arc` has *just* been dropped, it might not yet
1180                 // have removed the implicit weak count, so the value we get
1181                 // here might be 1 too high.
1182                 weak
1183             } else {
1184                 // As long as there's still at least 1 `Arc` around, subtract
1185                 // the implicit weak pointer.
1186                 // Note that the last `Arc` might get dropped between the 2
1187                 // loads we do above, removing the implicit weak pointer. This
1188                 // means that the value might be 1 too low here. In order to not
1189                 // return 0 here (which would happen if we're the only weak
1190                 // pointer), we guard against that specifically.
1191                 cmp::max(1, weak - 1)
1192             }
1193         })
1194     }
1195
1196     /// Return `None` when the pointer is dangling and there is no allocated `ArcInner`,
1197     /// i.e., this `Weak` was created by `Weak::new`
1198     #[inline]
1199     fn inner(&self) -> Option<&ArcInner<T>> {
1200         if is_dangling(self.ptr) {
1201             None
1202         } else {
1203             Some(unsafe { self.ptr.as_ref() })
1204         }
1205     }
1206
1207     /// Returns true if the two `Weak`s point to the same value (not just values
1208     /// that compare as equal).
1209     ///
1210     /// # Notes
1211     ///
1212     /// Since this compares pointers it means that `Weak::new()` will equal each
1213     /// other, even though they don't point to any value.
1214     ///
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```
1219     /// #![feature(weak_ptr_eq)]
1220     /// use std::sync::{Arc, Weak};
1221     ///
1222     /// let first_rc = Arc::new(5);
1223     /// let first = Arc::downgrade(&first_rc);
1224     /// let second = Arc::downgrade(&first_rc);
1225     ///
1226     /// assert!(Weak::ptr_eq(&first, &second));
1227     ///
1228     /// let third_rc = Arc::new(5);
1229     /// let third = Arc::downgrade(&third_rc);
1230     ///
1231     /// assert!(!Weak::ptr_eq(&first, &third));
1232     /// ```
1233     ///
1234     /// Comparing `Weak::new`.
1235     ///
1236     /// ```
1237     /// #![feature(weak_ptr_eq)]
1238     /// use std::sync::{Arc, Weak};
1239     ///
1240     /// let first = Weak::new();
1241     /// let second = Weak::new();
1242     /// assert!(Weak::ptr_eq(&first, &second));
1243     ///
1244     /// let third_rc = Arc::new(());
1245     /// let third = Arc::downgrade(&third_rc);
1246     /// assert!(!Weak::ptr_eq(&first, &third));
1247     /// ```
1248     #[inline]
1249     #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1250     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1251         this.ptr.as_ptr() == other.ptr.as_ptr()
1252     }
1253 }
1254
1255 #[stable(feature = "arc_weak", since = "1.4.0")]
1256 impl<T: ?Sized> Clone for Weak<T> {
1257     /// Makes a clone of the `Weak` pointer that points to the same value.
1258     ///
1259     /// # Examples
1260     ///
1261     /// ```
1262     /// use std::sync::{Arc, Weak};
1263     ///
1264     /// let weak_five = Arc::downgrade(&Arc::new(5));
1265     ///
1266     /// let _ = Weak::clone(&weak_five);
1267     /// ```
1268     #[inline]
1269     fn clone(&self) -> Weak<T> {
1270         let inner = if let Some(inner) = self.inner() {
1271             inner
1272         } else {
1273             return Weak { ptr: self.ptr };
1274         };
1275         // See comments in Arc::clone() for why this is relaxed.  This can use a
1276         // fetch_add (ignoring the lock) because the weak count is only locked
1277         // where are *no other* weak pointers in existence. (So we can't be
1278         // running this code in that case).
1279         let old_size = inner.weak.fetch_add(1, Relaxed);
1280
1281         // See comments in Arc::clone() for why we do this (for mem::forget).
1282         if old_size > MAX_REFCOUNT {
1283             unsafe {
1284                 abort();
1285             }
1286         }
1287
1288         return Weak { ptr: self.ptr };
1289     }
1290 }
1291
1292 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1293 impl<T> Default for Weak<T> {
1294     /// Constructs a new `Weak<T>`, without allocating memory.
1295     /// Calling [`upgrade`] on the return value always
1296     /// gives [`None`].
1297     ///
1298     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1299     /// [`upgrade`]: ../../std/sync/struct.Weak.html#method.upgrade
1300     ///
1301     /// # Examples
1302     ///
1303     /// ```
1304     /// use std::sync::Weak;
1305     ///
1306     /// let empty: Weak<i64> = Default::default();
1307     /// assert!(empty.upgrade().is_none());
1308     /// ```
1309     fn default() -> Weak<T> {
1310         Weak::new()
1311     }
1312 }
1313
1314 #[stable(feature = "arc_weak", since = "1.4.0")]
1315 impl<T: ?Sized> Drop for Weak<T> {
1316     /// Drops the `Weak` pointer.
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```
1321     /// use std::sync::{Arc, Weak};
1322     ///
1323     /// struct Foo;
1324     ///
1325     /// impl Drop for Foo {
1326     ///     fn drop(&mut self) {
1327     ///         println!("dropped!");
1328     ///     }
1329     /// }
1330     ///
1331     /// let foo = Arc::new(Foo);
1332     /// let weak_foo = Arc::downgrade(&foo);
1333     /// let other_weak_foo = Weak::clone(&weak_foo);
1334     ///
1335     /// drop(weak_foo);   // Doesn't print anything
1336     /// drop(foo);        // Prints "dropped!"
1337     ///
1338     /// assert!(other_weak_foo.upgrade().is_none());
1339     /// ```
1340     fn drop(&mut self) {
1341         // If we find out that we were the last weak pointer, then its time to
1342         // deallocate the data entirely. See the discussion in Arc::drop() about
1343         // the memory orderings
1344         //
1345         // It's not necessary to check for the locked state here, because the
1346         // weak count can only be locked if there was precisely one weak ref,
1347         // meaning that drop could only subsequently run ON that remaining weak
1348         // ref, which can only happen after the lock is released.
1349         let inner = if let Some(inner) = self.inner() {
1350             inner
1351         } else {
1352             return
1353         };
1354
1355         if inner.weak.fetch_sub(1, Release) == 1 {
1356             atomic::fence(Acquire);
1357             unsafe {
1358                 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
1359             }
1360         }
1361     }
1362 }
1363
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 trait ArcEqIdent<T: ?Sized + PartialEq> {
1366     fn eq(&self, other: &Arc<T>) -> bool;
1367     fn ne(&self, other: &Arc<T>) -> bool;
1368 }
1369
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1372     #[inline]
1373     default fn eq(&self, other: &Arc<T>) -> bool {
1374         **self == **other
1375     }
1376     #[inline]
1377     default fn ne(&self, other: &Arc<T>) -> bool {
1378         **self != **other
1379     }
1380 }
1381
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<T: ?Sized + Eq> ArcEqIdent<T> for Arc<T> {
1384     #[inline]
1385     fn eq(&self, other: &Arc<T>) -> bool {
1386         Arc::ptr_eq(self, other) || **self == **other
1387     }
1388
1389     #[inline]
1390     fn ne(&self, other: &Arc<T>) -> bool {
1391         !Arc::ptr_eq(self, other) && **self != **other
1392     }
1393 }
1394
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1397     /// Equality for two `Arc`s.
1398     ///
1399     /// Two `Arc`s are equal if their inner values are equal.
1400     ///
1401     /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1402     /// always equal.
1403     ///
1404     /// # Examples
1405     ///
1406     /// ```
1407     /// use std::sync::Arc;
1408     ///
1409     /// let five = Arc::new(5);
1410     ///
1411     /// assert!(five == Arc::new(5));
1412     /// ```
1413     #[inline]
1414     fn eq(&self, other: &Arc<T>) -> bool {
1415         ArcEqIdent::eq(self, other)
1416     }
1417
1418     /// Inequality for two `Arc`s.
1419     ///
1420     /// Two `Arc`s are unequal if their inner values are unequal.
1421     ///
1422     /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1423     /// never unequal.
1424     ///
1425     /// # Examples
1426     ///
1427     /// ```
1428     /// use std::sync::Arc;
1429     ///
1430     /// let five = Arc::new(5);
1431     ///
1432     /// assert!(five != Arc::new(6));
1433     /// ```
1434     #[inline]
1435     fn ne(&self, other: &Arc<T>) -> bool {
1436         ArcEqIdent::ne(self, other)
1437     }
1438 }
1439
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1442     /// Partial comparison for two `Arc`s.
1443     ///
1444     /// The two are compared by calling `partial_cmp()` on their inner values.
1445     ///
1446     /// # Examples
1447     ///
1448     /// ```
1449     /// use std::sync::Arc;
1450     /// use std::cmp::Ordering;
1451     ///
1452     /// let five = Arc::new(5);
1453     ///
1454     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1455     /// ```
1456     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1457         (**self).partial_cmp(&**other)
1458     }
1459
1460     /// Less-than comparison for two `Arc`s.
1461     ///
1462     /// The two are compared by calling `<` on their inner values.
1463     ///
1464     /// # Examples
1465     ///
1466     /// ```
1467     /// use std::sync::Arc;
1468     ///
1469     /// let five = Arc::new(5);
1470     ///
1471     /// assert!(five < Arc::new(6));
1472     /// ```
1473     fn lt(&self, other: &Arc<T>) -> bool {
1474         *(*self) < *(*other)
1475     }
1476
1477     /// 'Less than or equal to' comparison for two `Arc`s.
1478     ///
1479     /// The two are compared by calling `<=` on their inner values.
1480     ///
1481     /// # Examples
1482     ///
1483     /// ```
1484     /// use std::sync::Arc;
1485     ///
1486     /// let five = Arc::new(5);
1487     ///
1488     /// assert!(five <= Arc::new(5));
1489     /// ```
1490     fn le(&self, other: &Arc<T>) -> bool {
1491         *(*self) <= *(*other)
1492     }
1493
1494     /// Greater-than comparison for two `Arc`s.
1495     ///
1496     /// The two are compared by calling `>` on their inner values.
1497     ///
1498     /// # Examples
1499     ///
1500     /// ```
1501     /// use std::sync::Arc;
1502     ///
1503     /// let five = Arc::new(5);
1504     ///
1505     /// assert!(five > Arc::new(4));
1506     /// ```
1507     fn gt(&self, other: &Arc<T>) -> bool {
1508         *(*self) > *(*other)
1509     }
1510
1511     /// 'Greater than or equal to' comparison for two `Arc`s.
1512     ///
1513     /// The two are compared by calling `>=` on their inner values.
1514     ///
1515     /// # Examples
1516     ///
1517     /// ```
1518     /// use std::sync::Arc;
1519     ///
1520     /// let five = Arc::new(5);
1521     ///
1522     /// assert!(five >= Arc::new(5));
1523     /// ```
1524     fn ge(&self, other: &Arc<T>) -> bool {
1525         *(*self) >= *(*other)
1526     }
1527 }
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 impl<T: ?Sized + Ord> Ord for Arc<T> {
1530     /// Comparison for two `Arc`s.
1531     ///
1532     /// The two are compared by calling `cmp()` on their inner values.
1533     ///
1534     /// # Examples
1535     ///
1536     /// ```
1537     /// use std::sync::Arc;
1538     /// use std::cmp::Ordering;
1539     ///
1540     /// let five = Arc::new(5);
1541     ///
1542     /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1543     /// ```
1544     fn cmp(&self, other: &Arc<T>) -> Ordering {
1545         (**self).cmp(&**other)
1546     }
1547 }
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1550
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1553     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1554         fmt::Display::fmt(&**self, f)
1555     }
1556 }
1557
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1560     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561         fmt::Debug::fmt(&**self, f)
1562     }
1563 }
1564
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1567     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568         fmt::Pointer::fmt(&(&**self as *const T), f)
1569     }
1570 }
1571
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<T: Default> Default for Arc<T> {
1574     /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1575     ///
1576     /// # Examples
1577     ///
1578     /// ```
1579     /// use std::sync::Arc;
1580     ///
1581     /// let x: Arc<i32> = Default::default();
1582     /// assert_eq!(*x, 0);
1583     /// ```
1584     fn default() -> Arc<T> {
1585         Arc::new(Default::default())
1586     }
1587 }
1588
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<T: ?Sized + Hash> Hash for Arc<T> {
1591     fn hash<H: Hasher>(&self, state: &mut H) {
1592         (**self).hash(state)
1593     }
1594 }
1595
1596 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1597 impl<T> From<T> for Arc<T> {
1598     fn from(t: T) -> Self {
1599         Arc::new(t)
1600     }
1601 }
1602
1603 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1604 impl<'a, T: Clone> From<&'a [T]> for Arc<[T]> {
1605     #[inline]
1606     fn from(v: &[T]) -> Arc<[T]> {
1607         <Self as ArcFromSlice<T>>::from_slice(v)
1608     }
1609 }
1610
1611 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1612 impl<'a> From<&'a str> for Arc<str> {
1613     #[inline]
1614     fn from(v: &str) -> Arc<str> {
1615         let arc = Arc::<[u8]>::from(v.as_bytes());
1616         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
1617     }
1618 }
1619
1620 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1621 impl From<String> for Arc<str> {
1622     #[inline]
1623     fn from(v: String) -> Arc<str> {
1624         Arc::from(&v[..])
1625     }
1626 }
1627
1628 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1629 impl<T: ?Sized> From<Box<T>> for Arc<T> {
1630     #[inline]
1631     fn from(v: Box<T>) -> Arc<T> {
1632         Arc::from_box(v)
1633     }
1634 }
1635
1636 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1637 impl<T> From<Vec<T>> for Arc<[T]> {
1638     #[inline]
1639     fn from(mut v: Vec<T>) -> Arc<[T]> {
1640         unsafe {
1641             let arc = Arc::copy_from_slice(&v);
1642
1643             // Allow the Vec to free its memory, but not destroy its contents
1644             v.set_len(0);
1645
1646             arc
1647         }
1648     }
1649 }
1650
1651 #[cfg(test)]
1652 mod tests {
1653     use std::boxed::Box;
1654     use std::clone::Clone;
1655     use std::sync::mpsc::channel;
1656     use std::mem::drop;
1657     use std::ops::Drop;
1658     use std::option::Option;
1659     use std::option::Option::{None, Some};
1660     use std::sync::atomic;
1661     use std::sync::atomic::Ordering::{Acquire, SeqCst};
1662     use std::thread;
1663     use std::sync::Mutex;
1664     use std::convert::From;
1665
1666     use super::{Arc, Weak};
1667     use vec::Vec;
1668
1669     struct Canary(*mut atomic::AtomicUsize);
1670
1671     impl Drop for Canary {
1672         fn drop(&mut self) {
1673             unsafe {
1674                 match *self {
1675                     Canary(c) => {
1676                         (*c).fetch_add(1, SeqCst);
1677                     }
1678                 }
1679             }
1680         }
1681     }
1682
1683     #[test]
1684     #[cfg_attr(target_os = "emscripten", ignore)]
1685     fn manually_share_arc() {
1686         let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1687         let arc_v = Arc::new(v);
1688
1689         let (tx, rx) = channel();
1690
1691         let _t = thread::spawn(move || {
1692             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
1693             assert_eq!((*arc_v)[3], 4);
1694         });
1695
1696         tx.send(arc_v.clone()).unwrap();
1697
1698         assert_eq!((*arc_v)[2], 3);
1699         assert_eq!((*arc_v)[4], 5);
1700     }
1701
1702     #[test]
1703     fn test_arc_get_mut() {
1704         let mut x = Arc::new(3);
1705         *Arc::get_mut(&mut x).unwrap() = 4;
1706         assert_eq!(*x, 4);
1707         let y = x.clone();
1708         assert!(Arc::get_mut(&mut x).is_none());
1709         drop(y);
1710         assert!(Arc::get_mut(&mut x).is_some());
1711         let _w = Arc::downgrade(&x);
1712         assert!(Arc::get_mut(&mut x).is_none());
1713     }
1714
1715     #[test]
1716     fn weak_counts() {
1717         assert_eq!(Weak::weak_count(&Weak::<u64>::new()), None);
1718         assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
1719
1720         let a = Arc::new(0);
1721         let w = Arc::downgrade(&a);
1722         assert_eq!(Weak::strong_count(&w), 1);
1723         assert_eq!(Weak::weak_count(&w), Some(1));
1724         let w2 = w.clone();
1725         assert_eq!(Weak::strong_count(&w), 1);
1726         assert_eq!(Weak::weak_count(&w), Some(2));
1727         assert_eq!(Weak::strong_count(&w2), 1);
1728         assert_eq!(Weak::weak_count(&w2), Some(2));
1729         drop(w);
1730         assert_eq!(Weak::strong_count(&w2), 1);
1731         assert_eq!(Weak::weak_count(&w2), Some(1));
1732         let a2 = a.clone();
1733         assert_eq!(Weak::strong_count(&w2), 2);
1734         assert_eq!(Weak::weak_count(&w2), Some(1));
1735         drop(a2);
1736         drop(a);
1737         assert_eq!(Weak::strong_count(&w2), 0);
1738         assert_eq!(Weak::weak_count(&w2), Some(1));
1739         drop(w2);
1740     }
1741
1742     #[test]
1743     fn try_unwrap() {
1744         let x = Arc::new(3);
1745         assert_eq!(Arc::try_unwrap(x), Ok(3));
1746         let x = Arc::new(4);
1747         let _y = x.clone();
1748         assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1749         let x = Arc::new(5);
1750         let _w = Arc::downgrade(&x);
1751         assert_eq!(Arc::try_unwrap(x), Ok(5));
1752     }
1753
1754     #[test]
1755     fn into_from_raw() {
1756         let x = Arc::new(box "hello");
1757         let y = x.clone();
1758
1759         let x_ptr = Arc::into_raw(x);
1760         drop(y);
1761         unsafe {
1762             assert_eq!(**x_ptr, "hello");
1763
1764             let x = Arc::from_raw(x_ptr);
1765             assert_eq!(**x, "hello");
1766
1767             assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
1768         }
1769     }
1770
1771     #[test]
1772     fn test_into_from_raw_unsized() {
1773         use std::fmt::Display;
1774         use std::string::ToString;
1775
1776         let arc: Arc<str> = Arc::from("foo");
1777
1778         let ptr = Arc::into_raw(arc.clone());
1779         let arc2 = unsafe { Arc::from_raw(ptr) };
1780
1781         assert_eq!(unsafe { &*ptr }, "foo");
1782         assert_eq!(arc, arc2);
1783
1784         let arc: Arc<dyn Display> = Arc::new(123);
1785
1786         let ptr = Arc::into_raw(arc.clone());
1787         let arc2 = unsafe { Arc::from_raw(ptr) };
1788
1789         assert_eq!(unsafe { &*ptr }.to_string(), "123");
1790         assert_eq!(arc2.to_string(), "123");
1791     }
1792
1793     #[test]
1794     fn test_cowarc_clone_make_mut() {
1795         let mut cow0 = Arc::new(75);
1796         let mut cow1 = cow0.clone();
1797         let mut cow2 = cow1.clone();
1798
1799         assert!(75 == *Arc::make_mut(&mut cow0));
1800         assert!(75 == *Arc::make_mut(&mut cow1));
1801         assert!(75 == *Arc::make_mut(&mut cow2));
1802
1803         *Arc::make_mut(&mut cow0) += 1;
1804         *Arc::make_mut(&mut cow1) += 2;
1805         *Arc::make_mut(&mut cow2) += 3;
1806
1807         assert!(76 == *cow0);
1808         assert!(77 == *cow1);
1809         assert!(78 == *cow2);
1810
1811         // none should point to the same backing memory
1812         assert!(*cow0 != *cow1);
1813         assert!(*cow0 != *cow2);
1814         assert!(*cow1 != *cow2);
1815     }
1816
1817     #[test]
1818     fn test_cowarc_clone_unique2() {
1819         let mut cow0 = Arc::new(75);
1820         let cow1 = cow0.clone();
1821         let cow2 = cow1.clone();
1822
1823         assert!(75 == *cow0);
1824         assert!(75 == *cow1);
1825         assert!(75 == *cow2);
1826
1827         *Arc::make_mut(&mut cow0) += 1;
1828         assert!(76 == *cow0);
1829         assert!(75 == *cow1);
1830         assert!(75 == *cow2);
1831
1832         // cow1 and cow2 should share the same contents
1833         // cow0 should have a unique reference
1834         assert!(*cow0 != *cow1);
1835         assert!(*cow0 != *cow2);
1836         assert!(*cow1 == *cow2);
1837     }
1838
1839     #[test]
1840     fn test_cowarc_clone_weak() {
1841         let mut cow0 = Arc::new(75);
1842         let cow1_weak = Arc::downgrade(&cow0);
1843
1844         assert!(75 == *cow0);
1845         assert!(75 == *cow1_weak.upgrade().unwrap());
1846
1847         *Arc::make_mut(&mut cow0) += 1;
1848
1849         assert!(76 == *cow0);
1850         assert!(cow1_weak.upgrade().is_none());
1851     }
1852
1853     #[test]
1854     fn test_live() {
1855         let x = Arc::new(5);
1856         let y = Arc::downgrade(&x);
1857         assert!(y.upgrade().is_some());
1858     }
1859
1860     #[test]
1861     fn test_dead() {
1862         let x = Arc::new(5);
1863         let y = Arc::downgrade(&x);
1864         drop(x);
1865         assert!(y.upgrade().is_none());
1866     }
1867
1868     #[test]
1869     fn weak_self_cyclic() {
1870         struct Cycle {
1871             x: Mutex<Option<Weak<Cycle>>>,
1872         }
1873
1874         let a = Arc::new(Cycle { x: Mutex::new(None) });
1875         let b = Arc::downgrade(&a.clone());
1876         *a.x.lock().unwrap() = Some(b);
1877
1878         // hopefully we don't double-free (or leak)...
1879     }
1880
1881     #[test]
1882     fn drop_arc() {
1883         let mut canary = atomic::AtomicUsize::new(0);
1884         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1885         drop(x);
1886         assert!(canary.load(Acquire) == 1);
1887     }
1888
1889     #[test]
1890     fn drop_arc_weak() {
1891         let mut canary = atomic::AtomicUsize::new(0);
1892         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1893         let arc_weak = Arc::downgrade(&arc);
1894         assert!(canary.load(Acquire) == 0);
1895         drop(arc);
1896         assert!(canary.load(Acquire) == 1);
1897         drop(arc_weak);
1898     }
1899
1900     #[test]
1901     fn test_strong_count() {
1902         let a = Arc::new(0);
1903         assert!(Arc::strong_count(&a) == 1);
1904         let w = Arc::downgrade(&a);
1905         assert!(Arc::strong_count(&a) == 1);
1906         let b = w.upgrade().expect("");
1907         assert!(Arc::strong_count(&b) == 2);
1908         assert!(Arc::strong_count(&a) == 2);
1909         drop(w);
1910         drop(a);
1911         assert!(Arc::strong_count(&b) == 1);
1912         let c = b.clone();
1913         assert!(Arc::strong_count(&b) == 2);
1914         assert!(Arc::strong_count(&c) == 2);
1915     }
1916
1917     #[test]
1918     fn test_weak_count() {
1919         let a = Arc::new(0);
1920         assert!(Arc::strong_count(&a) == 1);
1921         assert!(Arc::weak_count(&a) == 0);
1922         let w = Arc::downgrade(&a);
1923         assert!(Arc::strong_count(&a) == 1);
1924         assert!(Arc::weak_count(&a) == 1);
1925         let x = w.clone();
1926         assert!(Arc::weak_count(&a) == 2);
1927         drop(w);
1928         drop(x);
1929         assert!(Arc::strong_count(&a) == 1);
1930         assert!(Arc::weak_count(&a) == 0);
1931         let c = a.clone();
1932         assert!(Arc::strong_count(&a) == 2);
1933         assert!(Arc::weak_count(&a) == 0);
1934         let d = Arc::downgrade(&c);
1935         assert!(Arc::weak_count(&c) == 1);
1936         assert!(Arc::strong_count(&c) == 2);
1937
1938         drop(a);
1939         drop(c);
1940         drop(d);
1941     }
1942
1943     #[test]
1944     fn show_arc() {
1945         let a = Arc::new(5);
1946         assert_eq!(format!("{:?}", a), "5");
1947     }
1948
1949     // Make sure deriving works with Arc<T>
1950     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1951     struct Foo {
1952         inner: Arc<i32>,
1953     }
1954
1955     #[test]
1956     fn test_unsized() {
1957         let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1958         assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1959         let y = Arc::downgrade(&x.clone());
1960         drop(x);
1961         assert!(y.upgrade().is_none());
1962     }
1963
1964     #[test]
1965     fn test_from_owned() {
1966         let foo = 123;
1967         let foo_arc = Arc::from(foo);
1968         assert!(123 == *foo_arc);
1969     }
1970
1971     #[test]
1972     fn test_new_weak() {
1973         let foo: Weak<usize> = Weak::new();
1974         assert!(foo.upgrade().is_none());
1975     }
1976
1977     #[test]
1978     fn test_ptr_eq() {
1979         let five = Arc::new(5);
1980         let same_five = five.clone();
1981         let other_five = Arc::new(5);
1982
1983         assert!(Arc::ptr_eq(&five, &same_five));
1984         assert!(!Arc::ptr_eq(&five, &other_five));
1985     }
1986
1987     #[test]
1988     #[cfg_attr(target_os = "emscripten", ignore)]
1989     fn test_weak_count_locked() {
1990         let mut a = Arc::new(atomic::AtomicBool::new(false));
1991         let a2 = a.clone();
1992         let t = thread::spawn(move || {
1993             for _i in 0..1000000 {
1994                 Arc::get_mut(&mut a);
1995             }
1996             a.store(true, SeqCst);
1997         });
1998
1999         while !a2.load(SeqCst) {
2000             let n = Arc::weak_count(&a2);
2001             assert!(n < 2, "bad weak count: {}", n);
2002         }
2003         t.join().unwrap();
2004     }
2005
2006     #[test]
2007     fn test_from_str() {
2008         let r: Arc<str> = Arc::from("foo");
2009
2010         assert_eq!(&r[..], "foo");
2011     }
2012
2013     #[test]
2014     fn test_copy_from_slice() {
2015         let s: &[u32] = &[1, 2, 3];
2016         let r: Arc<[u32]> = Arc::from(s);
2017
2018         assert_eq!(&r[..], [1, 2, 3]);
2019     }
2020
2021     #[test]
2022     fn test_clone_from_slice() {
2023         #[derive(Clone, Debug, Eq, PartialEq)]
2024         struct X(u32);
2025
2026         let s: &[X] = &[X(1), X(2), X(3)];
2027         let r: Arc<[X]> = Arc::from(s);
2028
2029         assert_eq!(&r[..], s);
2030     }
2031
2032     #[test]
2033     #[should_panic]
2034     fn test_clone_from_slice_panic() {
2035         use std::string::{String, ToString};
2036
2037         struct Fail(u32, String);
2038
2039         impl Clone for Fail {
2040             fn clone(&self) -> Fail {
2041                 if self.0 == 2 {
2042                     panic!();
2043                 }
2044                 Fail(self.0, self.1.clone())
2045             }
2046         }
2047
2048         let s: &[Fail] = &[
2049             Fail(0, "foo".to_string()),
2050             Fail(1, "bar".to_string()),
2051             Fail(2, "baz".to_string()),
2052         ];
2053
2054         // Should panic, but not cause memory corruption
2055         let _r: Arc<[Fail]> = Arc::from(s);
2056     }
2057
2058     #[test]
2059     fn test_from_box() {
2060         let b: Box<u32> = box 123;
2061         let r: Arc<u32> = Arc::from(b);
2062
2063         assert_eq!(*r, 123);
2064     }
2065
2066     #[test]
2067     fn test_from_box_str() {
2068         use std::string::String;
2069
2070         let s = String::from("foo").into_boxed_str();
2071         let r: Arc<str> = Arc::from(s);
2072
2073         assert_eq!(&r[..], "foo");
2074     }
2075
2076     #[test]
2077     fn test_from_box_slice() {
2078         let s = vec![1, 2, 3].into_boxed_slice();
2079         let r: Arc<[u32]> = Arc::from(s);
2080
2081         assert_eq!(&r[..], [1, 2, 3]);
2082     }
2083
2084     #[test]
2085     fn test_from_box_trait() {
2086         use std::fmt::Display;
2087         use std::string::ToString;
2088
2089         let b: Box<dyn Display> = box 123;
2090         let r: Arc<dyn Display> = Arc::from(b);
2091
2092         assert_eq!(r.to_string(), "123");
2093     }
2094
2095     #[test]
2096     fn test_from_box_trait_zero_sized() {
2097         use std::fmt::Debug;
2098
2099         let b: Box<dyn Debug> = box ();
2100         let r: Arc<dyn Debug> = Arc::from(b);
2101
2102         assert_eq!(format!("{:?}", r), "()");
2103     }
2104
2105     #[test]
2106     fn test_from_vec() {
2107         let v = vec![1, 2, 3];
2108         let r: Arc<[u32]> = Arc::from(v);
2109
2110         assert_eq!(&r[..], [1, 2, 3]);
2111     }
2112
2113     #[test]
2114     fn test_downcast() {
2115         use std::any::Any;
2116
2117         let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::max_value());
2118         let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
2119
2120         assert!(r1.clone().downcast::<u32>().is_err());
2121
2122         let r1i32 = r1.downcast::<i32>();
2123         assert!(r1i32.is_ok());
2124         assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value()));
2125
2126         assert!(r2.clone().downcast::<i32>().is_err());
2127
2128         let r2str = r2.downcast::<&'static str>();
2129         assert!(r2str.is_ok());
2130         assert_eq!(r2str.unwrap(), Arc::new("abc"));
2131     }
2132 }
2133
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2136     fn borrow(&self) -> &T {
2137         &**self
2138     }
2139 }
2140
2141 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2142 impl<T: ?Sized> AsRef<T> for Arc<T> {
2143     fn as_ref(&self) -> &T {
2144         &**self
2145     }
2146 }
2147
2148 #[stable(feature = "pin", since = "1.33.0")]
2149 impl<T: ?Sized> Unpin for Arc<T> { }