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