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