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