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