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