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