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