]> git.lizzy.rs Git - rust.git/blob - src/liballoc/sync.rs
Implement Weak::{strong_count, weak_count}
[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::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     /// Creates a new [`Weak`][weak] pointer to this value.
417     ///
418     /// [weak]: struct.Weak.html
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// use std::sync::Arc;
424     ///
425     /// let five = Arc::new(5);
426     ///
427     /// let weak_five = Arc::downgrade(&five);
428     /// ```
429     #[stable(feature = "arc_weak", since = "1.4.0")]
430     pub fn downgrade(this: &Self) -> Weak<T> {
431         // This Relaxed is OK because we're checking the value in the CAS
432         // below.
433         let mut cur = this.inner().weak.load(Relaxed);
434
435         loop {
436             // check if the weak counter is currently "locked"; if so, spin.
437             if cur == usize::MAX {
438                 cur = this.inner().weak.load(Relaxed);
439                 continue;
440             }
441
442             // NOTE: this code currently ignores the possibility of overflow
443             // into usize::MAX; in general both Rc and Arc need to be adjusted
444             // to deal with overflow.
445
446             // Unlike with Clone(), we need this to be an Acquire read to
447             // synchronize with the write coming from `is_unique`, so that the
448             // events prior to that write happen before this read.
449             match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
450                 Ok(_) => {
451                     // Make sure we do not create a dangling Weak
452                     debug_assert!(!is_dangling(this.ptr));
453                     return Weak { ptr: this.ptr };
454                 }
455                 Err(old) => cur = old,
456             }
457         }
458     }
459
460     /// Gets the number of [`Weak`][weak] pointers to this value.
461     ///
462     /// [weak]: struct.Weak.html
463     ///
464     /// # Safety
465     ///
466     /// This method by itself is safe, but using it correctly requires extra care.
467     /// Another thread can change the weak count at any time,
468     /// including potentially between calling this method and acting on the result.
469     ///
470     /// # Examples
471     ///
472     /// ```
473     /// use std::sync::Arc;
474     ///
475     /// let five = Arc::new(5);
476     /// let _weak_five = Arc::downgrade(&five);
477     ///
478     /// // This assertion is deterministic because we haven't shared
479     /// // the `Arc` or `Weak` between threads.
480     /// assert_eq!(1, Arc::weak_count(&five));
481     /// ```
482     #[inline]
483     #[stable(feature = "arc_counts", since = "1.15.0")]
484     pub fn weak_count(this: &Self) -> usize {
485         let cnt = this.inner().weak.load(SeqCst);
486         // If the weak count is currently locked, the value of the
487         // count was 0 just before taking the lock.
488         if cnt == usize::MAX { 0 } else { cnt - 1 }
489     }
490
491     /// Gets the number of strong (`Arc`) pointers to this value.
492     ///
493     /// # Safety
494     ///
495     /// This method by itself is safe, but using it correctly requires extra care.
496     /// Another thread can change the strong count at any time,
497     /// including potentially between calling this method and acting on the result.
498     ///
499     /// # Examples
500     ///
501     /// ```
502     /// use std::sync::Arc;
503     ///
504     /// let five = Arc::new(5);
505     /// let _also_five = Arc::clone(&five);
506     ///
507     /// // This assertion is deterministic because we haven't shared
508     /// // the `Arc` between threads.
509     /// assert_eq!(2, Arc::strong_count(&five));
510     /// ```
511     #[inline]
512     #[stable(feature = "arc_counts", since = "1.15.0")]
513     pub fn strong_count(this: &Self) -> usize {
514         this.inner().strong.load(SeqCst)
515     }
516
517     #[inline]
518     fn inner(&self) -> &ArcInner<T> {
519         // This unsafety is ok because while this arc is alive we're guaranteed
520         // that the inner pointer is valid. Furthermore, we know that the
521         // `ArcInner` structure itself is `Sync` because the inner data is
522         // `Sync` as well, so we're ok loaning out an immutable pointer to these
523         // contents.
524         unsafe { self.ptr.as_ref() }
525     }
526
527     // Non-inlined part of `drop`.
528     #[inline(never)]
529     unsafe fn drop_slow(&mut self) {
530         // Destroy the data at this time, even though we may not free the box
531         // allocation itself (there may still be weak pointers lying around).
532         ptr::drop_in_place(&mut self.ptr.as_mut().data);
533
534         if self.inner().weak.fetch_sub(1, Release) == 1 {
535             atomic::fence(Acquire);
536             Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
537         }
538     }
539
540     #[inline]
541     #[stable(feature = "ptr_eq", since = "1.17.0")]
542     /// Returns true if the two `Arc`s point to the same value (not
543     /// just values that compare as equal).
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use std::sync::Arc;
549     ///
550     /// let five = Arc::new(5);
551     /// let same_five = Arc::clone(&five);
552     /// let other_five = Arc::new(5);
553     ///
554     /// assert!(Arc::ptr_eq(&five, &same_five));
555     /// assert!(!Arc::ptr_eq(&five, &other_five));
556     /// ```
557     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
558         this.ptr.as_ptr() == other.ptr.as_ptr()
559     }
560 }
561
562 impl<T: ?Sized> Arc<T> {
563     // Allocates an `ArcInner<T>` with sufficient space for an unsized value
564     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
565         // Calculate layout using the given value.
566         // Previously, layout was calculated on the expression
567         // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
568         // reference (see #54908).
569         let layout = Layout::new::<ArcInner<()>>()
570             .extend(Layout::for_value(&*ptr)).unwrap().0
571             .pad_to_align().unwrap();
572
573         let mem = Global.alloc(layout)
574             .unwrap_or_else(|_| handle_alloc_error(layout));
575
576         // Initialize the ArcInner
577         let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
578         debug_assert_eq!(Layout::for_value(&*inner), layout);
579
580         ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
581         ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
582
583         inner
584     }
585
586     fn from_box(v: Box<T>) -> Arc<T> {
587         unsafe {
588             let box_unique = Box::into_unique(v);
589             let bptr = box_unique.as_ptr();
590
591             let value_size = size_of_val(&*bptr);
592             let ptr = Self::allocate_for_ptr(bptr);
593
594             // Copy value as bytes
595             ptr::copy_nonoverlapping(
596                 bptr as *const T as *const u8,
597                 &mut (*ptr).data as *mut _ as *mut u8,
598                 value_size);
599
600             // Free the allocation without dropping its contents
601             box_free(box_unique);
602
603             Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
604         }
605     }
606 }
607
608 // Sets the data pointer of a `?Sized` raw pointer.
609 //
610 // For a slice/trait object, this sets the `data` field and leaves the rest
611 // unchanged. For a sized raw pointer, this simply sets the pointer.
612 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
613     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
614     ptr
615 }
616
617 impl<T> Arc<[T]> {
618     // Copy elements from slice into newly allocated Arc<[T]>
619     //
620     // Unsafe because the caller must either take ownership or bind `T: Copy`
621     unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
622         let v_ptr = v as *const [T];
623         let ptr = Self::allocate_for_ptr(v_ptr);
624
625         ptr::copy_nonoverlapping(
626             v.as_ptr(),
627             &mut (*ptr).data as *mut [T] as *mut T,
628             v.len());
629
630         Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
631     }
632 }
633
634 // Specialization trait used for From<&[T]>
635 trait ArcFromSlice<T> {
636     fn from_slice(slice: &[T]) -> Self;
637 }
638
639 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
640     #[inline]
641     default fn from_slice(v: &[T]) -> Self {
642         // Panic guard while cloning T elements.
643         // In the event of a panic, elements that have been written
644         // into the new ArcInner will be dropped, then the memory freed.
645         struct Guard<T> {
646             mem: NonNull<u8>,
647             elems: *mut T,
648             layout: Layout,
649             n_elems: usize,
650         }
651
652         impl<T> Drop for Guard<T> {
653             fn drop(&mut self) {
654                 use core::slice::from_raw_parts_mut;
655
656                 unsafe {
657                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
658                     ptr::drop_in_place(slice);
659
660                     Global.dealloc(self.mem.cast(), self.layout.clone());
661                 }
662             }
663         }
664
665         unsafe {
666             let v_ptr = v as *const [T];
667             let ptr = Self::allocate_for_ptr(v_ptr);
668
669             let mem = ptr as *mut _ as *mut u8;
670             let layout = Layout::for_value(&*ptr);
671
672             // Pointer to first element
673             let elems = &mut (*ptr).data as *mut [T] as *mut T;
674
675             let mut guard = Guard{
676                 mem: NonNull::new_unchecked(mem),
677                 elems: elems,
678                 layout: layout,
679                 n_elems: 0,
680             };
681
682             for (i, item) in v.iter().enumerate() {
683                 ptr::write(elems.add(i), item.clone());
684                 guard.n_elems += 1;
685             }
686
687             // All clear. Forget the guard so it doesn't free the new ArcInner.
688             mem::forget(guard);
689
690             Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
691         }
692     }
693 }
694
695 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
696     #[inline]
697     fn from_slice(v: &[T]) -> Self {
698         unsafe { Arc::copy_from_slice(v) }
699     }
700 }
701
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<T: ?Sized> Clone for Arc<T> {
704     /// Makes a clone of the `Arc` pointer.
705     ///
706     /// This creates another pointer to the same inner value, increasing the
707     /// strong reference count.
708     ///
709     /// # Examples
710     ///
711     /// ```
712     /// use std::sync::Arc;
713     ///
714     /// let five = Arc::new(5);
715     ///
716     /// let _ = Arc::clone(&five);
717     /// ```
718     #[inline]
719     fn clone(&self) -> Arc<T> {
720         // Using a relaxed ordering is alright here, as knowledge of the
721         // original reference prevents other threads from erroneously deleting
722         // the object.
723         //
724         // As explained in the [Boost documentation][1], Increasing the
725         // reference counter can always be done with memory_order_relaxed: New
726         // references to an object can only be formed from an existing
727         // reference, and passing an existing reference from one thread to
728         // another must already provide any required synchronization.
729         //
730         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
731         let old_size = self.inner().strong.fetch_add(1, Relaxed);
732
733         // However we need to guard against massive refcounts in case someone
734         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
735         // and users will use-after free. We racily saturate to `isize::MAX` on
736         // the assumption that there aren't ~2 billion threads incrementing
737         // the reference count at once. This branch will never be taken in
738         // any realistic program.
739         //
740         // We abort because such a program is incredibly degenerate, and we
741         // don't care to support it.
742         if old_size > MAX_REFCOUNT {
743             unsafe {
744                 abort();
745             }
746         }
747
748         Arc { ptr: self.ptr, phantom: PhantomData }
749     }
750 }
751
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<T: ?Sized> Deref for Arc<T> {
754     type Target = T;
755
756     #[inline]
757     fn deref(&self) -> &T {
758         &self.inner().data
759     }
760 }
761
762 #[unstable(feature = "receiver_trait", issue = "0")]
763 impl<T: ?Sized> Receiver for Arc<T> {}
764
765 impl<T: Clone> Arc<T> {
766     /// Makes a mutable reference into the given `Arc`.
767     ///
768     /// If there are other `Arc` or [`Weak`][weak] pointers to the same value,
769     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
770     /// ensure unique ownership. This is also referred to as clone-on-write.
771     ///
772     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
773     ///
774     /// [weak]: struct.Weak.html
775     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
776     /// [get_mut]: struct.Arc.html#method.get_mut
777     ///
778     /// # Examples
779     ///
780     /// ```
781     /// use std::sync::Arc;
782     ///
783     /// let mut data = Arc::new(5);
784     ///
785     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
786     /// let mut other_data = Arc::clone(&data); // Won't clone inner data
787     /// *Arc::make_mut(&mut data) += 1;         // Clones inner data
788     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
789     /// *Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything
790     ///
791     /// // Now `data` and `other_data` point to different values.
792     /// assert_eq!(*data, 8);
793     /// assert_eq!(*other_data, 12);
794     /// ```
795     #[inline]
796     #[stable(feature = "arc_unique", since = "1.4.0")]
797     pub fn make_mut(this: &mut Self) -> &mut T {
798         // Note that we hold both a strong reference and a weak reference.
799         // Thus, releasing our strong reference only will not, by itself, cause
800         // the memory to be deallocated.
801         //
802         // Use Acquire to ensure that we see any writes to `weak` that happen
803         // before release writes (i.e., decrements) to `strong`. Since we hold a
804         // weak count, there's no chance the ArcInner itself could be
805         // deallocated.
806         if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
807             // Another strong pointer exists; clone
808             *this = Arc::new((**this).clone());
809         } else if this.inner().weak.load(Relaxed) != 1 {
810             // Relaxed suffices in the above because this is fundamentally an
811             // optimization: we are always racing with weak pointers being
812             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
813
814             // We removed the last strong ref, but there are additional weak
815             // refs remaining. We'll move the contents to a new Arc, and
816             // invalidate the other weak refs.
817
818             // Note that it is not possible for the read of `weak` to yield
819             // usize::MAX (i.e., locked), since the weak count can only be
820             // locked by a thread with a strong reference.
821
822             // Materialize our own implicit weak pointer, so that it can clean
823             // up the ArcInner as needed.
824             let weak = Weak { ptr: this.ptr };
825
826             // mark the data itself as already deallocated
827             unsafe {
828                 // there is no data race in the implicit write caused by `read`
829                 // here (due to zeroing) because data is no longer accessed by
830                 // other threads (due to there being no more strong refs at this
831                 // point).
832                 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
833                 mem::swap(this, &mut swap);
834                 mem::forget(swap);
835             }
836         } else {
837             // We were the sole reference of either kind; bump back up the
838             // strong ref count.
839             this.inner().strong.store(1, Release);
840         }
841
842         // As with `get_mut()`, the unsafety is ok because our reference was
843         // either unique to begin with, or became one upon cloning the contents.
844         unsafe {
845             &mut this.ptr.as_mut().data
846         }
847     }
848 }
849
850 impl<T: ?Sized> Arc<T> {
851     /// Returns a mutable reference to the inner value, if there are
852     /// no other `Arc` or [`Weak`][weak] pointers to the same value.
853     ///
854     /// Returns [`None`][option] otherwise, because it is not safe to
855     /// mutate a shared value.
856     ///
857     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
858     /// the inner value when it's shared.
859     ///
860     /// [weak]: struct.Weak.html
861     /// [option]: ../../std/option/enum.Option.html
862     /// [make_mut]: struct.Arc.html#method.make_mut
863     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
864     ///
865     /// # Examples
866     ///
867     /// ```
868     /// use std::sync::Arc;
869     ///
870     /// let mut x = Arc::new(3);
871     /// *Arc::get_mut(&mut x).unwrap() = 4;
872     /// assert_eq!(*x, 4);
873     ///
874     /// let _y = Arc::clone(&x);
875     /// assert!(Arc::get_mut(&mut x).is_none());
876     /// ```
877     #[inline]
878     #[stable(feature = "arc_unique", since = "1.4.0")]
879     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
880         if this.is_unique() {
881             // This unsafety is ok because we're guaranteed that the pointer
882             // returned is the *only* pointer that will ever be returned to T. Our
883             // reference count is guaranteed to be 1 at this point, and we required
884             // the Arc itself to be `mut`, so we're returning the only possible
885             // reference to the inner data.
886             unsafe {
887                 Some(&mut this.ptr.as_mut().data)
888             }
889         } else {
890             None
891         }
892     }
893
894     /// Determine whether this is the unique reference (including weak refs) to
895     /// the underlying data.
896     ///
897     /// Note that this requires locking the weak ref count.
898     fn is_unique(&mut self) -> bool {
899         // lock the weak pointer count if we appear to be the sole weak pointer
900         // holder.
901         //
902         // The acquire label here ensures a happens-before relationship with any
903         // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
904         // of the `weak` count (via `Weak::drop`, which uses release).  If the upgraded
905         // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
906         if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
907             // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
908             // counter in `drop` -- the only access that happens when any but the last reference
909             // is being dropped.
910             let unique = self.inner().strong.load(Acquire) == 1;
911
912             // The release write here synchronizes with a read in `downgrade`,
913             // effectively preventing the above read of `strong` from happening
914             // after the write.
915             self.inner().weak.store(1, Release); // release the lock
916             unique
917         } else {
918             false
919         }
920     }
921 }
922
923 #[stable(feature = "rust1", since = "1.0.0")]
924 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
925     /// Drops the `Arc`.
926     ///
927     /// This will decrement the strong reference count. If the strong reference
928     /// count reaches zero then the only other references (if any) are
929     /// [`Weak`], so we `drop` the inner value.
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// use std::sync::Arc;
935     ///
936     /// struct Foo;
937     ///
938     /// impl Drop for Foo {
939     ///     fn drop(&mut self) {
940     ///         println!("dropped!");
941     ///     }
942     /// }
943     ///
944     /// let foo  = Arc::new(Foo);
945     /// let foo2 = Arc::clone(&foo);
946     ///
947     /// drop(foo);    // Doesn't print anything
948     /// drop(foo2);   // Prints "dropped!"
949     /// ```
950     ///
951     /// [`Weak`]: ../../std/sync/struct.Weak.html
952     #[inline]
953     fn drop(&mut self) {
954         // Because `fetch_sub` is already atomic, we do not need to synchronize
955         // with other threads unless we are going to delete the object. This
956         // same logic applies to the below `fetch_sub` to the `weak` count.
957         if self.inner().strong.fetch_sub(1, Release) != 1 {
958             return;
959         }
960
961         // This fence is needed to prevent reordering of use of the data and
962         // deletion of the data.  Because it is marked `Release`, the decreasing
963         // of the reference count synchronizes with this `Acquire` fence. This
964         // means that use of the data happens before decreasing the reference
965         // count, which happens before this fence, which happens before the
966         // deletion of the data.
967         //
968         // As explained in the [Boost documentation][1],
969         //
970         // > It is important to enforce any possible access to the object in one
971         // > thread (through an existing reference) to *happen before* deleting
972         // > the object in a different thread. This is achieved by a "release"
973         // > operation after dropping a reference (any access to the object
974         // > through this reference must obviously happened before), and an
975         // > "acquire" operation before deleting the object.
976         //
977         // In particular, while the contents of an Arc are usually immutable, it's
978         // possible to have interior writes to something like a Mutex<T>. Since a
979         // Mutex is not acquired when it is deleted, we can't rely on its
980         // synchronization logic to make writes in thread A visible to a destructor
981         // running in thread B.
982         //
983         // Also note that the Acquire fence here could probably be replaced with an
984         // Acquire load, which could improve performance in highly-contended
985         // situations. See [2].
986         //
987         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
988         // [2]: (https://github.com/rust-lang/rust/pull/41714)
989         atomic::fence(Acquire);
990
991         unsafe {
992             self.drop_slow();
993         }
994     }
995 }
996
997 impl Arc<dyn Any + Send + Sync> {
998     #[inline]
999     #[stable(feature = "rc_downcast", since = "1.29.0")]
1000     /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1001     ///
1002     /// # Examples
1003     ///
1004     /// ```
1005     /// use std::any::Any;
1006     /// use std::sync::Arc;
1007     ///
1008     /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1009     ///     if let Ok(string) = value.downcast::<String>() {
1010     ///         println!("String ({}): {}", string.len(), string);
1011     ///     }
1012     /// }
1013     ///
1014     /// fn main() {
1015     ///     let my_string = "Hello World".to_string();
1016     ///     print_if_string(Arc::new(my_string));
1017     ///     print_if_string(Arc::new(0i8));
1018     /// }
1019     /// ```
1020     pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1021     where
1022         T: Any + Send + Sync + 'static,
1023     {
1024         if (*self).is::<T>() {
1025             let ptr = self.ptr.cast::<ArcInner<T>>();
1026             mem::forget(self);
1027             Ok(Arc { ptr, phantom: PhantomData })
1028         } else {
1029             Err(self)
1030         }
1031     }
1032 }
1033
1034 impl<T> Weak<T> {
1035     /// Constructs a new `Weak<T>`, without allocating any memory.
1036     /// Calling [`upgrade`] on the return value always gives [`None`].
1037     ///
1038     /// [`upgrade`]: struct.Weak.html#method.upgrade
1039     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1040     ///
1041     /// # Examples
1042     ///
1043     /// ```
1044     /// use std::sync::Weak;
1045     ///
1046     /// let empty: Weak<i64> = Weak::new();
1047     /// assert!(empty.upgrade().is_none());
1048     /// ```
1049     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1050     pub fn new() -> Weak<T> {
1051         Weak {
1052             ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0"),
1053         }
1054     }
1055 }
1056
1057 impl<T: ?Sized> Weak<T> {
1058     /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending
1059     /// the lifetime of the value if successful.
1060     ///
1061     /// Returns [`None`] if the value has since been dropped.
1062     ///
1063     /// [`Arc`]: struct.Arc.html
1064     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1065     ///
1066     /// # Examples
1067     ///
1068     /// ```
1069     /// use std::sync::Arc;
1070     ///
1071     /// let five = Arc::new(5);
1072     ///
1073     /// let weak_five = Arc::downgrade(&five);
1074     ///
1075     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1076     /// assert!(strong_five.is_some());
1077     ///
1078     /// // Destroy all strong pointers.
1079     /// drop(strong_five);
1080     /// drop(five);
1081     ///
1082     /// assert!(weak_five.upgrade().is_none());
1083     /// ```
1084     #[stable(feature = "arc_weak", since = "1.4.0")]
1085     pub fn upgrade(&self) -> Option<Arc<T>> {
1086         // We use a CAS loop to increment the strong count instead of a
1087         // fetch_add because once the count hits 0 it must never be above 0.
1088         let inner = self.inner()?;
1089
1090         // Relaxed load because any write of 0 that we can observe
1091         // leaves the field in a permanently zero state (so a
1092         // "stale" read of 0 is fine), and any other value is
1093         // confirmed via the CAS below.
1094         let mut n = inner.strong.load(Relaxed);
1095
1096         loop {
1097             if n == 0 {
1098                 return None;
1099             }
1100
1101             // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1102             if n > MAX_REFCOUNT {
1103                 unsafe {
1104                     abort();
1105                 }
1106             }
1107
1108             // Relaxed is valid for the same reason it is on Arc's Clone impl
1109             match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) {
1110                 Ok(_) => return Some(Arc {
1111                     // null checked above
1112                     ptr: self.ptr,
1113                     phantom: PhantomData,
1114                 }),
1115                 Err(old) => n = old,
1116             }
1117         }
1118     }
1119
1120     /// Gets the number of strong (`Arc`) pointers pointing to this value.
1121     ///
1122     /// If `self` was created using [`Weak::new`], this will return 0.
1123     ///
1124     /// [`Weak::new`]: #method.new
1125     #[unstable(feature = "weak_counts", issue = "0")]
1126     pub fn strong_count(&self) -> usize {
1127         if let Some(inner) = self.inner() {
1128             inner.strong.load(SeqCst)
1129         } else {
1130             0
1131         }
1132     }
1133
1134     // Due to the implicit weak pointer added when any strong pointers are
1135     // around, we cannot implement `weak_count` correctly since it necessarily
1136     // requires accessing the strong count and weak count in an unsynchronized
1137     // fashion.
1138
1139     /// Return `None` when the pointer is dangling and there is no allocated `ArcInner`,
1140     /// i.e., this `Weak` was created by `Weak::new`
1141     #[inline]
1142     fn inner(&self) -> Option<&ArcInner<T>> {
1143         if is_dangling(self.ptr) {
1144             None
1145         } else {
1146             Some(unsafe { self.ptr.as_ref() })
1147         }
1148     }
1149
1150     /// Returns true if the two `Weak`s point to the same value (not just values
1151     /// that compare as equal).
1152     ///
1153     /// # Notes
1154     ///
1155     /// Since this compares pointers it means that `Weak::new()` will equal each
1156     /// other, even though they don't point to any value.
1157     ///
1158     ///
1159     /// # Examples
1160     ///
1161     /// ```
1162     /// #![feature(weak_ptr_eq)]
1163     /// use std::sync::{Arc, Weak};
1164     ///
1165     /// let first_rc = Arc::new(5);
1166     /// let first = Arc::downgrade(&first_rc);
1167     /// let second = Arc::downgrade(&first_rc);
1168     ///
1169     /// assert!(Weak::ptr_eq(&first, &second));
1170     ///
1171     /// let third_rc = Arc::new(5);
1172     /// let third = Arc::downgrade(&third_rc);
1173     ///
1174     /// assert!(!Weak::ptr_eq(&first, &third));
1175     /// ```
1176     ///
1177     /// Comparing `Weak::new`.
1178     ///
1179     /// ```
1180     /// #![feature(weak_ptr_eq)]
1181     /// use std::sync::{Arc, Weak};
1182     ///
1183     /// let first = Weak::new();
1184     /// let second = Weak::new();
1185     /// assert!(Weak::ptr_eq(&first, &second));
1186     ///
1187     /// let third_rc = Arc::new(());
1188     /// let third = Arc::downgrade(&third_rc);
1189     /// assert!(!Weak::ptr_eq(&first, &third));
1190     /// ```
1191     #[inline]
1192     #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1193     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1194         this.ptr.as_ptr() == other.ptr.as_ptr()
1195     }
1196 }
1197
1198 #[stable(feature = "arc_weak", since = "1.4.0")]
1199 impl<T: ?Sized> Clone for Weak<T> {
1200     /// Makes a clone of the `Weak` pointer that points to the same value.
1201     ///
1202     /// # Examples
1203     ///
1204     /// ```
1205     /// use std::sync::{Arc, Weak};
1206     ///
1207     /// let weak_five = Arc::downgrade(&Arc::new(5));
1208     ///
1209     /// let _ = Weak::clone(&weak_five);
1210     /// ```
1211     #[inline]
1212     fn clone(&self) -> Weak<T> {
1213         let inner = if let Some(inner) = self.inner() {
1214             inner
1215         } else {
1216             return Weak { ptr: self.ptr };
1217         };
1218         // See comments in Arc::clone() for why this is relaxed.  This can use a
1219         // fetch_add (ignoring the lock) because the weak count is only locked
1220         // where are *no other* weak pointers in existence. (So we can't be
1221         // running this code in that case).
1222         let old_size = inner.weak.fetch_add(1, Relaxed);
1223
1224         // See comments in Arc::clone() for why we do this (for mem::forget).
1225         if old_size > MAX_REFCOUNT {
1226             unsafe {
1227                 abort();
1228             }
1229         }
1230
1231         return Weak { ptr: self.ptr };
1232     }
1233 }
1234
1235 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1236 impl<T> Default for Weak<T> {
1237     /// Constructs a new `Weak<T>`, without allocating memory.
1238     /// Calling [`upgrade`] on the return value always
1239     /// gives [`None`].
1240     ///
1241     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1242     /// [`upgrade`]: ../../std/sync/struct.Weak.html#method.upgrade
1243     ///
1244     /// # Examples
1245     ///
1246     /// ```
1247     /// use std::sync::Weak;
1248     ///
1249     /// let empty: Weak<i64> = Default::default();
1250     /// assert!(empty.upgrade().is_none());
1251     /// ```
1252     fn default() -> Weak<T> {
1253         Weak::new()
1254     }
1255 }
1256
1257 #[stable(feature = "arc_weak", since = "1.4.0")]
1258 impl<T: ?Sized> Drop for Weak<T> {
1259     /// Drops the `Weak` pointer.
1260     ///
1261     /// # Examples
1262     ///
1263     /// ```
1264     /// use std::sync::{Arc, Weak};
1265     ///
1266     /// struct Foo;
1267     ///
1268     /// impl Drop for Foo {
1269     ///     fn drop(&mut self) {
1270     ///         println!("dropped!");
1271     ///     }
1272     /// }
1273     ///
1274     /// let foo = Arc::new(Foo);
1275     /// let weak_foo = Arc::downgrade(&foo);
1276     /// let other_weak_foo = Weak::clone(&weak_foo);
1277     ///
1278     /// drop(weak_foo);   // Doesn't print anything
1279     /// drop(foo);        // Prints "dropped!"
1280     ///
1281     /// assert!(other_weak_foo.upgrade().is_none());
1282     /// ```
1283     fn drop(&mut self) {
1284         // If we find out that we were the last weak pointer, then its time to
1285         // deallocate the data entirely. See the discussion in Arc::drop() about
1286         // the memory orderings
1287         //
1288         // It's not necessary to check for the locked state here, because the
1289         // weak count can only be locked if there was precisely one weak ref,
1290         // meaning that drop could only subsequently run ON that remaining weak
1291         // ref, which can only happen after the lock is released.
1292         let inner = if let Some(inner) = self.inner() {
1293             inner
1294         } else {
1295             return
1296         };
1297
1298         if inner.weak.fetch_sub(1, Release) == 1 {
1299             atomic::fence(Acquire);
1300             unsafe {
1301                 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()))
1302             }
1303         }
1304     }
1305 }
1306
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 trait ArcEqIdent<T: ?Sized + PartialEq> {
1309     fn eq(&self, other: &Arc<T>) -> bool;
1310     fn ne(&self, other: &Arc<T>) -> bool;
1311 }
1312
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1315     #[inline]
1316     default fn eq(&self, other: &Arc<T>) -> bool {
1317         **self == **other
1318     }
1319     #[inline]
1320     default fn ne(&self, other: &Arc<T>) -> bool {
1321         **self != **other
1322     }
1323 }
1324
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<T: ?Sized + Eq> ArcEqIdent<T> for Arc<T> {
1327     #[inline]
1328     fn eq(&self, other: &Arc<T>) -> bool {
1329         Arc::ptr_eq(self, other) || **self == **other
1330     }
1331
1332     #[inline]
1333     fn ne(&self, other: &Arc<T>) -> bool {
1334         !Arc::ptr_eq(self, other) && **self != **other
1335     }
1336 }
1337
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1340     /// Equality for two `Arc`s.
1341     ///
1342     /// Two `Arc`s are equal if their inner values are equal.
1343     ///
1344     /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1345     /// always equal.
1346     ///
1347     /// # Examples
1348     ///
1349     /// ```
1350     /// use std::sync::Arc;
1351     ///
1352     /// let five = Arc::new(5);
1353     ///
1354     /// assert!(five == Arc::new(5));
1355     /// ```
1356     #[inline]
1357     fn eq(&self, other: &Arc<T>) -> bool {
1358         ArcEqIdent::eq(self, other)
1359     }
1360
1361     /// Inequality for two `Arc`s.
1362     ///
1363     /// Two `Arc`s are unequal if their inner values are unequal.
1364     ///
1365     /// If `T` also implements `Eq`, two `Arc`s that point to the same value are
1366     /// never unequal.
1367     ///
1368     /// # Examples
1369     ///
1370     /// ```
1371     /// use std::sync::Arc;
1372     ///
1373     /// let five = Arc::new(5);
1374     ///
1375     /// assert!(five != Arc::new(6));
1376     /// ```
1377     #[inline]
1378     fn ne(&self, other: &Arc<T>) -> bool {
1379         ArcEqIdent::ne(self, other)
1380     }
1381 }
1382
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
1385     /// Partial comparison for two `Arc`s.
1386     ///
1387     /// The two are compared by calling `partial_cmp()` on their inner values.
1388     ///
1389     /// # Examples
1390     ///
1391     /// ```
1392     /// use std::sync::Arc;
1393     /// use std::cmp::Ordering;
1394     ///
1395     /// let five = Arc::new(5);
1396     ///
1397     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
1398     /// ```
1399     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
1400         (**self).partial_cmp(&**other)
1401     }
1402
1403     /// Less-than comparison for two `Arc`s.
1404     ///
1405     /// The two are compared by calling `<` on their inner values.
1406     ///
1407     /// # Examples
1408     ///
1409     /// ```
1410     /// use std::sync::Arc;
1411     ///
1412     /// let five = Arc::new(5);
1413     ///
1414     /// assert!(five < Arc::new(6));
1415     /// ```
1416     fn lt(&self, other: &Arc<T>) -> bool {
1417         *(*self) < *(*other)
1418     }
1419
1420     /// 'Less than or equal to' comparison for two `Arc`s.
1421     ///
1422     /// The two are compared by calling `<=` on their inner values.
1423     ///
1424     /// # Examples
1425     ///
1426     /// ```
1427     /// use std::sync::Arc;
1428     ///
1429     /// let five = Arc::new(5);
1430     ///
1431     /// assert!(five <= Arc::new(5));
1432     /// ```
1433     fn le(&self, other: &Arc<T>) -> bool {
1434         *(*self) <= *(*other)
1435     }
1436
1437     /// Greater-than comparison for two `Arc`s.
1438     ///
1439     /// The two are compared by calling `>` on their inner values.
1440     ///
1441     /// # Examples
1442     ///
1443     /// ```
1444     /// use std::sync::Arc;
1445     ///
1446     /// let five = Arc::new(5);
1447     ///
1448     /// assert!(five > Arc::new(4));
1449     /// ```
1450     fn gt(&self, other: &Arc<T>) -> bool {
1451         *(*self) > *(*other)
1452     }
1453
1454     /// 'Greater than or equal to' comparison for two `Arc`s.
1455     ///
1456     /// The two are compared by calling `>=` on their inner values.
1457     ///
1458     /// # Examples
1459     ///
1460     /// ```
1461     /// use std::sync::Arc;
1462     ///
1463     /// let five = Arc::new(5);
1464     ///
1465     /// assert!(five >= Arc::new(5));
1466     /// ```
1467     fn ge(&self, other: &Arc<T>) -> bool {
1468         *(*self) >= *(*other)
1469     }
1470 }
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<T: ?Sized + Ord> Ord for Arc<T> {
1473     /// Comparison for two `Arc`s.
1474     ///
1475     /// The two are compared by calling `cmp()` on their inner values.
1476     ///
1477     /// # Examples
1478     ///
1479     /// ```
1480     /// use std::sync::Arc;
1481     /// use std::cmp::Ordering;
1482     ///
1483     /// let five = Arc::new(5);
1484     ///
1485     /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
1486     /// ```
1487     fn cmp(&self, other: &Arc<T>) -> Ordering {
1488         (**self).cmp(&**other)
1489     }
1490 }
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<T: ?Sized + Eq> Eq for Arc<T> {}
1493
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
1496     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497         fmt::Display::fmt(&**self, f)
1498     }
1499 }
1500
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
1503     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504         fmt::Debug::fmt(&**self, f)
1505     }
1506 }
1507
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 impl<T: ?Sized> fmt::Pointer for Arc<T> {
1510     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511         fmt::Pointer::fmt(&(&**self as *const T), f)
1512     }
1513 }
1514
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<T: Default> Default for Arc<T> {
1517     /// Creates a new `Arc<T>`, with the `Default` value for `T`.
1518     ///
1519     /// # Examples
1520     ///
1521     /// ```
1522     /// use std::sync::Arc;
1523     ///
1524     /// let x: Arc<i32> = Default::default();
1525     /// assert_eq!(*x, 0);
1526     /// ```
1527     fn default() -> Arc<T> {
1528         Arc::new(Default::default())
1529     }
1530 }
1531
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<T: ?Sized + Hash> Hash for Arc<T> {
1534     fn hash<H: Hasher>(&self, state: &mut H) {
1535         (**self).hash(state)
1536     }
1537 }
1538
1539 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1540 impl<T> From<T> for Arc<T> {
1541     fn from(t: T) -> Self {
1542         Arc::new(t)
1543     }
1544 }
1545
1546 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1547 impl<'a, T: Clone> From<&'a [T]> for Arc<[T]> {
1548     #[inline]
1549     fn from(v: &[T]) -> Arc<[T]> {
1550         <Self as ArcFromSlice<T>>::from_slice(v)
1551     }
1552 }
1553
1554 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1555 impl<'a> From<&'a str> for Arc<str> {
1556     #[inline]
1557     fn from(v: &str) -> Arc<str> {
1558         let arc = Arc::<[u8]>::from(v.as_bytes());
1559         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
1560     }
1561 }
1562
1563 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1564 impl From<String> for Arc<str> {
1565     #[inline]
1566     fn from(v: String) -> Arc<str> {
1567         Arc::from(&v[..])
1568     }
1569 }
1570
1571 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1572 impl<T: ?Sized> From<Box<T>> for Arc<T> {
1573     #[inline]
1574     fn from(v: Box<T>) -> Arc<T> {
1575         Arc::from_box(v)
1576     }
1577 }
1578
1579 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1580 impl<T> From<Vec<T>> for Arc<[T]> {
1581     #[inline]
1582     fn from(mut v: Vec<T>) -> Arc<[T]> {
1583         unsafe {
1584             let arc = Arc::copy_from_slice(&v);
1585
1586             // Allow the Vec to free its memory, but not destroy its contents
1587             v.set_len(0);
1588
1589             arc
1590         }
1591     }
1592 }
1593
1594 #[cfg(test)]
1595 mod tests {
1596     use std::boxed::Box;
1597     use std::clone::Clone;
1598     use std::sync::mpsc::channel;
1599     use std::mem::drop;
1600     use std::ops::Drop;
1601     use std::option::Option;
1602     use std::option::Option::{None, Some};
1603     use std::sync::atomic;
1604     use std::sync::atomic::Ordering::{Acquire, SeqCst};
1605     use std::thread;
1606     use std::sync::Mutex;
1607     use std::convert::From;
1608
1609     use super::{Arc, Weak};
1610     use vec::Vec;
1611
1612     struct Canary(*mut atomic::AtomicUsize);
1613
1614     impl Drop for Canary {
1615         fn drop(&mut self) {
1616             unsafe {
1617                 match *self {
1618                     Canary(c) => {
1619                         (*c).fetch_add(1, SeqCst);
1620                     }
1621                 }
1622             }
1623         }
1624     }
1625
1626     #[test]
1627     #[cfg_attr(target_os = "emscripten", ignore)]
1628     fn manually_share_arc() {
1629         let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1630         let arc_v = Arc::new(v);
1631
1632         let (tx, rx) = channel();
1633
1634         let _t = thread::spawn(move || {
1635             let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
1636             assert_eq!((*arc_v)[3], 4);
1637         });
1638
1639         tx.send(arc_v.clone()).unwrap();
1640
1641         assert_eq!((*arc_v)[2], 3);
1642         assert_eq!((*arc_v)[4], 5);
1643     }
1644
1645     #[test]
1646     fn test_arc_get_mut() {
1647         let mut x = Arc::new(3);
1648         *Arc::get_mut(&mut x).unwrap() = 4;
1649         assert_eq!(*x, 4);
1650         let y = x.clone();
1651         assert!(Arc::get_mut(&mut x).is_none());
1652         drop(y);
1653         assert!(Arc::get_mut(&mut x).is_some());
1654         let _w = Arc::downgrade(&x);
1655         assert!(Arc::get_mut(&mut x).is_none());
1656     }
1657
1658     #[test]
1659     fn try_unwrap() {
1660         let x = Arc::new(3);
1661         assert_eq!(Arc::try_unwrap(x), Ok(3));
1662         let x = Arc::new(4);
1663         let _y = x.clone();
1664         assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
1665         let x = Arc::new(5);
1666         let _w = Arc::downgrade(&x);
1667         assert_eq!(Arc::try_unwrap(x), Ok(5));
1668     }
1669
1670     #[test]
1671     fn into_from_raw() {
1672         let x = Arc::new(box "hello");
1673         let y = x.clone();
1674
1675         let x_ptr = Arc::into_raw(x);
1676         drop(y);
1677         unsafe {
1678             assert_eq!(**x_ptr, "hello");
1679
1680             let x = Arc::from_raw(x_ptr);
1681             assert_eq!(**x, "hello");
1682
1683             assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
1684         }
1685     }
1686
1687     #[test]
1688     fn test_into_from_raw_unsized() {
1689         use std::fmt::Display;
1690         use std::string::ToString;
1691
1692         let arc: Arc<str> = Arc::from("foo");
1693
1694         let ptr = Arc::into_raw(arc.clone());
1695         let arc2 = unsafe { Arc::from_raw(ptr) };
1696
1697         assert_eq!(unsafe { &*ptr }, "foo");
1698         assert_eq!(arc, arc2);
1699
1700         let arc: Arc<dyn Display> = Arc::new(123);
1701
1702         let ptr = Arc::into_raw(arc.clone());
1703         let arc2 = unsafe { Arc::from_raw(ptr) };
1704
1705         assert_eq!(unsafe { &*ptr }.to_string(), "123");
1706         assert_eq!(arc2.to_string(), "123");
1707     }
1708
1709     #[test]
1710     fn test_cowarc_clone_make_mut() {
1711         let mut cow0 = Arc::new(75);
1712         let mut cow1 = cow0.clone();
1713         let mut cow2 = cow1.clone();
1714
1715         assert!(75 == *Arc::make_mut(&mut cow0));
1716         assert!(75 == *Arc::make_mut(&mut cow1));
1717         assert!(75 == *Arc::make_mut(&mut cow2));
1718
1719         *Arc::make_mut(&mut cow0) += 1;
1720         *Arc::make_mut(&mut cow1) += 2;
1721         *Arc::make_mut(&mut cow2) += 3;
1722
1723         assert!(76 == *cow0);
1724         assert!(77 == *cow1);
1725         assert!(78 == *cow2);
1726
1727         // none should point to the same backing memory
1728         assert!(*cow0 != *cow1);
1729         assert!(*cow0 != *cow2);
1730         assert!(*cow1 != *cow2);
1731     }
1732
1733     #[test]
1734     fn test_cowarc_clone_unique2() {
1735         let mut cow0 = Arc::new(75);
1736         let cow1 = cow0.clone();
1737         let cow2 = cow1.clone();
1738
1739         assert!(75 == *cow0);
1740         assert!(75 == *cow1);
1741         assert!(75 == *cow2);
1742
1743         *Arc::make_mut(&mut cow0) += 1;
1744         assert!(76 == *cow0);
1745         assert!(75 == *cow1);
1746         assert!(75 == *cow2);
1747
1748         // cow1 and cow2 should share the same contents
1749         // cow0 should have a unique reference
1750         assert!(*cow0 != *cow1);
1751         assert!(*cow0 != *cow2);
1752         assert!(*cow1 == *cow2);
1753     }
1754
1755     #[test]
1756     fn test_cowarc_clone_weak() {
1757         let mut cow0 = Arc::new(75);
1758         let cow1_weak = Arc::downgrade(&cow0);
1759
1760         assert!(75 == *cow0);
1761         assert!(75 == *cow1_weak.upgrade().unwrap());
1762
1763         *Arc::make_mut(&mut cow0) += 1;
1764
1765         assert!(76 == *cow0);
1766         assert!(cow1_weak.upgrade().is_none());
1767     }
1768
1769     #[test]
1770     fn test_live() {
1771         let x = Arc::new(5);
1772         let y = Arc::downgrade(&x);
1773         assert!(y.upgrade().is_some());
1774     }
1775
1776     #[test]
1777     fn test_dead() {
1778         let x = Arc::new(5);
1779         let y = Arc::downgrade(&x);
1780         drop(x);
1781         assert!(y.upgrade().is_none());
1782     }
1783
1784     #[test]
1785     fn weak_self_cyclic() {
1786         struct Cycle {
1787             x: Mutex<Option<Weak<Cycle>>>,
1788         }
1789
1790         let a = Arc::new(Cycle { x: Mutex::new(None) });
1791         let b = Arc::downgrade(&a.clone());
1792         *a.x.lock().unwrap() = Some(b);
1793
1794         // hopefully we don't double-free (or leak)...
1795     }
1796
1797     #[test]
1798     fn drop_arc() {
1799         let mut canary = atomic::AtomicUsize::new(0);
1800         let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1801         drop(x);
1802         assert!(canary.load(Acquire) == 1);
1803     }
1804
1805     #[test]
1806     fn drop_arc_weak() {
1807         let mut canary = atomic::AtomicUsize::new(0);
1808         let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
1809         let arc_weak = Arc::downgrade(&arc);
1810         assert!(canary.load(Acquire) == 0);
1811         drop(arc);
1812         assert!(canary.load(Acquire) == 1);
1813         drop(arc_weak);
1814     }
1815
1816     #[test]
1817     fn test_strong_count() {
1818         let a = Arc::new(0);
1819         assert!(Arc::strong_count(&a) == 1);
1820         let w = Arc::downgrade(&a);
1821         assert!(Arc::strong_count(&a) == 1);
1822         let b = w.upgrade().expect("");
1823         assert!(Arc::strong_count(&b) == 2);
1824         assert!(Arc::strong_count(&a) == 2);
1825         drop(w);
1826         drop(a);
1827         assert!(Arc::strong_count(&b) == 1);
1828         let c = b.clone();
1829         assert!(Arc::strong_count(&b) == 2);
1830         assert!(Arc::strong_count(&c) == 2);
1831     }
1832
1833     #[test]
1834     fn test_weak_count() {
1835         let a = Arc::new(0);
1836         assert!(Arc::strong_count(&a) == 1);
1837         assert!(Arc::weak_count(&a) == 0);
1838         let w = Arc::downgrade(&a);
1839         assert!(Arc::strong_count(&a) == 1);
1840         assert!(Arc::weak_count(&a) == 1);
1841         let x = w.clone();
1842         assert!(Arc::weak_count(&a) == 2);
1843         drop(w);
1844         drop(x);
1845         assert!(Arc::strong_count(&a) == 1);
1846         assert!(Arc::weak_count(&a) == 0);
1847         let c = a.clone();
1848         assert!(Arc::strong_count(&a) == 2);
1849         assert!(Arc::weak_count(&a) == 0);
1850         let d = Arc::downgrade(&c);
1851         assert!(Arc::weak_count(&c) == 1);
1852         assert!(Arc::strong_count(&c) == 2);
1853
1854         drop(a);
1855         drop(c);
1856         drop(d);
1857     }
1858
1859     #[test]
1860     fn show_arc() {
1861         let a = Arc::new(5);
1862         assert_eq!(format!("{:?}", a), "5");
1863     }
1864
1865     // Make sure deriving works with Arc<T>
1866     #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
1867     struct Foo {
1868         inner: Arc<i32>,
1869     }
1870
1871     #[test]
1872     fn test_unsized() {
1873         let x: Arc<[i32]> = Arc::new([1, 2, 3]);
1874         assert_eq!(format!("{:?}", x), "[1, 2, 3]");
1875         let y = Arc::downgrade(&x.clone());
1876         drop(x);
1877         assert!(y.upgrade().is_none());
1878     }
1879
1880     #[test]
1881     fn test_from_owned() {
1882         let foo = 123;
1883         let foo_arc = Arc::from(foo);
1884         assert!(123 == *foo_arc);
1885     }
1886
1887     #[test]
1888     fn test_new_weak() {
1889         let foo: Weak<usize> = Weak::new();
1890         assert!(foo.upgrade().is_none());
1891     }
1892
1893     #[test]
1894     fn test_ptr_eq() {
1895         let five = Arc::new(5);
1896         let same_five = five.clone();
1897         let other_five = Arc::new(5);
1898
1899         assert!(Arc::ptr_eq(&five, &same_five));
1900         assert!(!Arc::ptr_eq(&five, &other_five));
1901     }
1902
1903     #[test]
1904     #[cfg_attr(target_os = "emscripten", ignore)]
1905     fn test_weak_count_locked() {
1906         let mut a = Arc::new(atomic::AtomicBool::new(false));
1907         let a2 = a.clone();
1908         let t = thread::spawn(move || {
1909             for _i in 0..1000000 {
1910                 Arc::get_mut(&mut a);
1911             }
1912             a.store(true, SeqCst);
1913         });
1914
1915         while !a2.load(SeqCst) {
1916             let n = Arc::weak_count(&a2);
1917             assert!(n < 2, "bad weak count: {}", n);
1918         }
1919         t.join().unwrap();
1920     }
1921
1922     #[test]
1923     fn test_from_str() {
1924         let r: Arc<str> = Arc::from("foo");
1925
1926         assert_eq!(&r[..], "foo");
1927     }
1928
1929     #[test]
1930     fn test_copy_from_slice() {
1931         let s: &[u32] = &[1, 2, 3];
1932         let r: Arc<[u32]> = Arc::from(s);
1933
1934         assert_eq!(&r[..], [1, 2, 3]);
1935     }
1936
1937     #[test]
1938     fn test_clone_from_slice() {
1939         #[derive(Clone, Debug, Eq, PartialEq)]
1940         struct X(u32);
1941
1942         let s: &[X] = &[X(1), X(2), X(3)];
1943         let r: Arc<[X]> = Arc::from(s);
1944
1945         assert_eq!(&r[..], s);
1946     }
1947
1948     #[test]
1949     #[should_panic]
1950     fn test_clone_from_slice_panic() {
1951         use std::string::{String, ToString};
1952
1953         struct Fail(u32, String);
1954
1955         impl Clone for Fail {
1956             fn clone(&self) -> Fail {
1957                 if self.0 == 2 {
1958                     panic!();
1959                 }
1960                 Fail(self.0, self.1.clone())
1961             }
1962         }
1963
1964         let s: &[Fail] = &[
1965             Fail(0, "foo".to_string()),
1966             Fail(1, "bar".to_string()),
1967             Fail(2, "baz".to_string()),
1968         ];
1969
1970         // Should panic, but not cause memory corruption
1971         let _r: Arc<[Fail]> = Arc::from(s);
1972     }
1973
1974     #[test]
1975     fn test_from_box() {
1976         let b: Box<u32> = box 123;
1977         let r: Arc<u32> = Arc::from(b);
1978
1979         assert_eq!(*r, 123);
1980     }
1981
1982     #[test]
1983     fn test_from_box_str() {
1984         use std::string::String;
1985
1986         let s = String::from("foo").into_boxed_str();
1987         let r: Arc<str> = Arc::from(s);
1988
1989         assert_eq!(&r[..], "foo");
1990     }
1991
1992     #[test]
1993     fn test_from_box_slice() {
1994         let s = vec![1, 2, 3].into_boxed_slice();
1995         let r: Arc<[u32]> = Arc::from(s);
1996
1997         assert_eq!(&r[..], [1, 2, 3]);
1998     }
1999
2000     #[test]
2001     fn test_from_box_trait() {
2002         use std::fmt::Display;
2003         use std::string::ToString;
2004
2005         let b: Box<dyn Display> = box 123;
2006         let r: Arc<dyn Display> = Arc::from(b);
2007
2008         assert_eq!(r.to_string(), "123");
2009     }
2010
2011     #[test]
2012     fn test_from_box_trait_zero_sized() {
2013         use std::fmt::Debug;
2014
2015         let b: Box<dyn Debug> = box ();
2016         let r: Arc<dyn Debug> = Arc::from(b);
2017
2018         assert_eq!(format!("{:?}", r), "()");
2019     }
2020
2021     #[test]
2022     fn test_from_vec() {
2023         let v = vec![1, 2, 3];
2024         let r: Arc<[u32]> = Arc::from(v);
2025
2026         assert_eq!(&r[..], [1, 2, 3]);
2027     }
2028
2029     #[test]
2030     fn test_downcast() {
2031         use std::any::Any;
2032
2033         let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::max_value());
2034         let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
2035
2036         assert!(r1.clone().downcast::<u32>().is_err());
2037
2038         let r1i32 = r1.downcast::<i32>();
2039         assert!(r1i32.is_ok());
2040         assert_eq!(r1i32.unwrap(), Arc::new(i32::max_value()));
2041
2042         assert!(r2.clone().downcast::<i32>().is_err());
2043
2044         let r2str = r2.downcast::<&'static str>();
2045         assert!(r2str.is_ok());
2046         assert_eq!(r2str.unwrap(), Arc::new("abc"));
2047     }
2048 }
2049
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2052     fn borrow(&self) -> &T {
2053         &**self
2054     }
2055 }
2056
2057 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2058 impl<T: ?Sized> AsRef<T> for Arc<T> {
2059     fn as_ref(&self) -> &T {
2060         &**self
2061     }
2062 }
2063
2064 #[stable(feature = "pin", since = "1.33.0")]
2065 impl<T: ?Sized> Unpin for Arc<T> { }