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