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