]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/sync.rs
Convert many files to intra-doc links
[rust.git] / library / alloc / src / sync.rs
1 #![stable(feature = "rust1", since = "1.0.0")]
2
3 //! Thread-safe reference-counting pointers.
4 //!
5 //! See the [`Arc<T>`][Arc] documentation for more details.
6
7 use core::any::Any;
8 use core::borrow;
9 use core::cmp::Ordering;
10 use core::convert::{From, TryFrom};
11 use core::fmt;
12 use core::hash::{Hash, Hasher};
13 use core::intrinsics::abort;
14 use core::iter;
15 use core::marker::{PhantomData, Unpin, Unsize};
16 use core::mem::{self, align_of_val, size_of_val};
17 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
18 use core::pin::Pin;
19 use core::ptr::{self, NonNull};
20 use core::slice::from_raw_parts_mut;
21 use core::sync::atomic;
22 use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
23
24 use crate::alloc::{box_free, handle_alloc_error, AllocErr, AllocRef, Global, Layout};
25 use crate::borrow::{Cow, ToOwned};
26 use crate::boxed::Box;
27 use crate::rc::is_dangling;
28 use crate::string::String;
29 use crate::vec::Vec;
30
31 #[cfg(test)]
32 mod tests;
33
34 /// A soft limit on the amount of references that may be made to an `Arc`.
35 ///
36 /// Going above this limit will abort your program (although not
37 /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
38 const MAX_REFCOUNT: usize = (isize::MAX) as usize;
39
40 #[cfg(not(sanitize = "thread"))]
41 macro_rules! acquire {
42     ($x:expr) => {
43         atomic::fence(Acquire)
44     };
45 }
46
47 // ThreadSanitizer does not support memory fences. To avoid false positive
48 // reports in Arc / Weak implementation use atomic loads for synchronization
49 // instead.
50 #[cfg(sanitize = "thread")]
51 macro_rules! acquire {
52     ($x:expr) => {
53         $x.load(Acquire)
54     };
55 }
56
57 /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically
58 /// Reference Counted'.
59 ///
60 /// The type `Arc<T>` provides shared ownership of a value of type `T`,
61 /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces
62 /// a new `Arc` instance, which points to the same allocation on the heap as the
63 /// source `Arc`, while increasing a reference count. When the last `Arc`
64 /// pointer to a given allocation is destroyed, the value stored in that allocation (often
65 /// referred to as "inner value") is also dropped.
66 ///
67 /// Shared references in Rust disallow mutation by default, and `Arc` is no
68 /// exception: you cannot generally obtain a mutable reference to something
69 /// inside an `Arc`. If you need to mutate through an `Arc`, use
70 /// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
71 /// types.
72 ///
73 /// ## Thread Safety
74 ///
75 /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference
76 /// counting. This means that it is thread-safe. The disadvantage is that
77 /// atomic operations are more expensive than ordinary memory accesses. If you
78 /// are not sharing reference-counted allocations between threads, consider using
79 /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the
80 /// compiler will catch any attempt to send an [`Rc<T>`] between threads.
81 /// However, a library might choose `Arc<T>` in order to give library consumers
82 /// more flexibility.
83 ///
84 /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements
85 /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an
86 /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at
87 /// first: after all, isn't the point of `Arc<T>` thread safety? The key is
88 /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same
89 /// data, but it  doesn't add thread safety to its data. Consider
90 /// `Arc<`[`RefCell<T>`]`>`. [`RefCell<T>`] isn't [`Sync`], and if `Arc<T>` was always
91 /// [`Send`], `Arc<`[`RefCell<T>`]`>` would be as well. But then we'd have a problem:
92 /// [`RefCell<T>`] is not thread safe; it keeps track of the borrowing count using
93 /// non-atomic operations.
94 ///
95 /// In the end, this means that you may need to pair `Arc<T>` with some sort of
96 /// [`std::sync`] type, usually [`Mutex<T>`][mutex].
97 ///
98 /// ## Breaking cycles with `Weak`
99 ///
100 /// The [`downgrade`][downgrade] method can be used to create a non-owning
101 /// [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
102 /// to an `Arc`, but this will return [`None`] if the value stored in the allocation has
103 /// already been dropped. In other words, `Weak` pointers do not keep the value
104 /// inside the allocation alive; however, they *do* keep the allocation
105 /// (the backing store for the value) alive.
106 ///
107 /// A cycle between `Arc` pointers will never be deallocated. For this reason,
108 /// [`Weak`] is used to break cycles. For example, a tree could have
109 /// strong `Arc` pointers from parent nodes to children, and [`Weak`]
110 /// pointers from children back to their parents.
111 ///
112 /// # Cloning references
113 ///
114 /// Creating a new reference from an existing reference-counted pointer is done using the
115 /// `Clone` trait implemented for [`Arc<T>`][Arc] and [`Weak<T>`][Weak].
116 ///
117 /// ```
118 /// use std::sync::Arc;
119 /// let foo = Arc::new(vec![1.0, 2.0, 3.0]);
120 /// // The two syntaxes below are equivalent.
121 /// let a = foo.clone();
122 /// let b = Arc::clone(&foo);
123 /// // a, b, and foo are all Arcs that point to the same memory location
124 /// ```
125 ///
126 /// ## `Deref` behavior
127 ///
128 /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
129 /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name
130 /// clashes with `T`'s methods, the methods of `Arc<T>` itself are associated
131 /// functions, called using function-like syntax:
132 ///
133 /// ```
134 /// use std::sync::Arc;
135 /// let my_arc = Arc::new(());
136 ///
137 /// Arc::downgrade(&my_arc);
138 /// ```
139 ///
140 /// [`Weak<T>`][Weak] does not auto-dereference to `T`, because the inner value may have
141 /// already been dropped.
142 ///
143 /// [`Rc<T>`]: crate::rc::Rc
144 /// [clone]: Clone::clone
145 /// [mutex]: ../../std/sync/struct.Mutex.html
146 /// [rwlock]: ../../std/sync/struct.RwLock.html
147 /// [atomic]: core::sync::atomic
148 /// [`Send`]: core::marker::Send
149 /// [`Sync`]: core::marker::Sync
150 /// [deref]: core::ops::Deref
151 /// [downgrade]: Arc::downgrade
152 /// [upgrade]: Weak::upgrade
153 /// [`RefCell<T>`]: core::cell::RefCell
154 /// [`std::sync`]: ../../std/sync/index.html
155 /// [`Arc::clone(&from)`]: Arc::clone
156 ///
157 /// # Examples
158 ///
159 /// Sharing some immutable data between threads:
160 ///
161 // Note that we **do not** run these tests here. The windows builders get super
162 // unhappy if a thread outlives the main thread and then exits at the same time
163 // (something deadlocks) so we just avoid this entirely by not running these
164 // tests.
165 /// ```no_run
166 /// use std::sync::Arc;
167 /// use std::thread;
168 ///
169 /// let five = Arc::new(5);
170 ///
171 /// for _ in 0..10 {
172 ///     let five = Arc::clone(&five);
173 ///
174 ///     thread::spawn(move || {
175 ///         println!("{:?}", five);
176 ///     });
177 /// }
178 /// ```
179 ///
180 /// Sharing a mutable [`AtomicUsize`]:
181 ///
182 /// [`AtomicUsize`]: core::sync::atomic::AtomicUsize
183 ///
184 /// ```no_run
185 /// use std::sync::Arc;
186 /// use std::sync::atomic::{AtomicUsize, Ordering};
187 /// use std::thread;
188 ///
189 /// let val = Arc::new(AtomicUsize::new(5));
190 ///
191 /// for _ in 0..10 {
192 ///     let val = Arc::clone(&val);
193 ///
194 ///     thread::spawn(move || {
195 ///         let v = val.fetch_add(1, Ordering::SeqCst);
196 ///         println!("{:?}", v);
197 ///     });
198 /// }
199 /// ```
200 ///
201 /// See the [`rc` documentation][rc_examples] for more examples of reference
202 /// counting in general.
203 ///
204 /// [rc_examples]: crate::rc#examples
205 #[cfg_attr(not(test), rustc_diagnostic_item = "Arc")]
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub struct Arc<T: ?Sized> {
208     ptr: NonNull<ArcInner<T>>,
209     phantom: PhantomData<ArcInner<T>>,
210 }
211
212 #[stable(feature = "rust1", since = "1.0.0")]
213 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
214 #[stable(feature = "rust1", since = "1.0.0")]
215 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
216
217 #[unstable(feature = "coerce_unsized", issue = "27732")]
218 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
219
220 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
221 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}
222
223 impl<T: ?Sized> Arc<T> {
224     fn from_inner(ptr: NonNull<ArcInner<T>>) -> Self {
225         Self { ptr, phantom: PhantomData }
226     }
227
228     unsafe fn from_ptr(ptr: *mut ArcInner<T>) -> Self {
229         unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
230     }
231 }
232
233 /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
234 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
235 /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`.
236 ///
237 /// Since a `Weak` reference does not count towards ownership, it will not
238 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
239 /// guarantees about the value still being present. Thus it may return [`None`]
240 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
241 /// itself (the backing store) from being deallocated.
242 ///
243 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
244 /// managed by [`Arc`] without preventing its inner value from being dropped. It is also used to
245 /// prevent circular references between [`Arc`] pointers, since mutual owning references
246 /// would never allow either [`Arc`] to be dropped. For example, a tree could
247 /// have strong [`Arc`] pointers from parent nodes to children, and `Weak`
248 /// pointers from children back to their parents.
249 ///
250 /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`].
251 ///
252 /// [`upgrade`]: Weak::upgrade
253 #[stable(feature = "arc_weak", since = "1.4.0")]
254 pub struct Weak<T: ?Sized> {
255     // This is a `NonNull` to allow optimizing the size of this type in enums,
256     // but it is not necessarily a valid pointer.
257     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
258     // to allocate space on the heap.  That's not a value a real pointer
259     // will ever have because RcBox has alignment at least 2.
260     // This is only possible when `T: Sized`; unsized `T` never dangle.
261     ptr: NonNull<ArcInner<T>>,
262 }
263
264 #[stable(feature = "arc_weak", since = "1.4.0")]
265 unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
266 #[stable(feature = "arc_weak", since = "1.4.0")]
267 unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}
268
269 #[unstable(feature = "coerce_unsized", issue = "27732")]
270 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
271 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
272 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
273
274 #[stable(feature = "arc_weak", since = "1.4.0")]
275 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
276     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277         write!(f, "(Weak)")
278     }
279 }
280
281 // This is repr(C) to future-proof against possible field-reordering, which
282 // would interfere with otherwise safe [into|from]_raw() of transmutable
283 // inner types.
284 #[repr(C)]
285 struct ArcInner<T: ?Sized> {
286     strong: atomic::AtomicUsize,
287
288     // the value usize::MAX acts as a sentinel for temporarily "locking" the
289     // ability to upgrade weak pointers or downgrade strong ones; this is used
290     // to avoid races in `make_mut` and `get_mut`.
291     weak: atomic::AtomicUsize,
292
293     data: T,
294 }
295
296 unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
297 unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
298
299 impl<T> Arc<T> {
300     /// Constructs a new `Arc<T>`.
301     ///
302     /// # Examples
303     ///
304     /// ```
305     /// use std::sync::Arc;
306     ///
307     /// let five = Arc::new(5);
308     /// ```
309     #[inline]
310     #[stable(feature = "rust1", since = "1.0.0")]
311     pub fn new(data: T) -> Arc<T> {
312         // Start the weak pointer count as 1 which is the weak pointer that's
313         // held by all the strong pointers (kinda), see std/rc.rs for more info
314         let x: Box<_> = box ArcInner {
315             strong: atomic::AtomicUsize::new(1),
316             weak: atomic::AtomicUsize::new(1),
317             data,
318         };
319         Self::from_inner(Box::leak(x).into())
320     }
321
322     /// Constructs a new `Arc<T>` using a weak reference to itself. Attempting
323     /// to upgrade the weak reference before this function returns will result
324     /// in a `None` value. However, the weak reference may be cloned freely and
325     /// stored for use at a later time.
326     ///
327     /// # Examples
328     /// ```
329     /// #![feature(arc_new_cyclic)]
330     /// #![allow(dead_code)]
331     ///
332     /// use std::sync::{Arc, Weak};
333     ///
334     /// struct Foo {
335     ///     me: Weak<Foo>,
336     /// }
337     ///
338     /// let foo = Arc::new_cyclic(|me| Foo {
339     ///     me: me.clone(),
340     /// });
341     /// ```
342     #[inline]
343     #[unstable(feature = "arc_new_cyclic", issue = "75861")]
344     pub fn new_cyclic(data_fn: impl FnOnce(&Weak<T>) -> T) -> Arc<T> {
345         // Construct the inner in the "uninitialized" state with a single
346         // weak reference.
347         let uninit_ptr: NonNull<_> = Box::leak(box ArcInner {
348             strong: atomic::AtomicUsize::new(0),
349             weak: atomic::AtomicUsize::new(1),
350             data: mem::MaybeUninit::<T>::uninit(),
351         })
352         .into();
353         let init_ptr: NonNull<ArcInner<T>> = uninit_ptr.cast();
354
355         let weak = Weak { ptr: init_ptr };
356
357         // It's important we don't give up ownership of the weak pointer, or
358         // else the memory might be freed by the time `data_fn` returns. If
359         // we really wanted to pass ownership, we could create an additional
360         // weak pointer for ourselves, but this would result in additional
361         // updates to the weak reference count which might not be necessary
362         // otherwise.
363         let data = data_fn(&weak);
364
365         // Now we can properly initialize the inner value and turn our weak
366         // reference into a strong reference.
367         unsafe {
368             let inner = init_ptr.as_ptr();
369             ptr::write(&raw mut (*inner).data, data);
370
371             // The above write to the data field must be visible to any threads which
372             // observe a non-zero strong count. Therefore we need at least "Release" ordering
373             // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`.
374             //
375             // "Acquire" ordering is not required. When considering the possible behaviours
376             // of `data_fn` we only need to look at what it could do with a reference to a
377             // non-upgradeable `Weak`:
378             // - It can *clone* the `Weak`, increasing the weak reference count.
379             // - It can drop those clones, decreasing the weak reference count (but never to zero).
380             //
381             // These side effects do not impact us in any way, and no other side effects are
382             // possible with safe code alone.
383             let prev_value = (*inner).strong.fetch_add(1, Release);
384             debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
385         }
386
387         let strong = Arc::from_inner(init_ptr);
388
389         // Strong references should collectively own a shared weak reference,
390         // so don't run the destructor for our old weak reference.
391         mem::forget(weak);
392         strong
393     }
394
395     /// Constructs a new `Arc` with uninitialized contents.
396     ///
397     /// # Examples
398     ///
399     /// ```
400     /// #![feature(new_uninit)]
401     /// #![feature(get_mut_unchecked)]
402     ///
403     /// use std::sync::Arc;
404     ///
405     /// let mut five = Arc::<u32>::new_uninit();
406     ///
407     /// let five = unsafe {
408     ///     // Deferred initialization:
409     ///     Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
410     ///
411     ///     five.assume_init()
412     /// };
413     ///
414     /// assert_eq!(*five, 5)
415     /// ```
416     #[unstable(feature = "new_uninit", issue = "63291")]
417     pub fn new_uninit() -> Arc<mem::MaybeUninit<T>> {
418         unsafe {
419             Arc::from_ptr(Arc::allocate_for_layout(
420                 Layout::new::<T>(),
421                 |layout| Global.alloc(layout),
422                 |mem| mem as *mut ArcInner<mem::MaybeUninit<T>>,
423             ))
424         }
425     }
426
427     /// Constructs a new `Arc` with uninitialized contents, with the memory
428     /// being filled with `0` bytes.
429     ///
430     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
431     /// of this method.
432     ///
433     /// # Examples
434     ///
435     /// ```
436     /// #![feature(new_uninit)]
437     ///
438     /// use std::sync::Arc;
439     ///
440     /// let zero = Arc::<u32>::new_zeroed();
441     /// let zero = unsafe { zero.assume_init() };
442     ///
443     /// assert_eq!(*zero, 0)
444     /// ```
445     ///
446     /// [zeroed]: mem::MaybeUninit::zeroed
447     #[unstable(feature = "new_uninit", issue = "63291")]
448     pub fn new_zeroed() -> Arc<mem::MaybeUninit<T>> {
449         unsafe {
450             Arc::from_ptr(Arc::allocate_for_layout(
451                 Layout::new::<T>(),
452                 |layout| Global.alloc_zeroed(layout),
453                 |mem| mem as *mut ArcInner<mem::MaybeUninit<T>>,
454             ))
455         }
456     }
457
458     /// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
459     /// `data` will be pinned in memory and unable to be moved.
460     #[stable(feature = "pin", since = "1.33.0")]
461     pub fn pin(data: T) -> Pin<Arc<T>> {
462         unsafe { Pin::new_unchecked(Arc::new(data)) }
463     }
464
465     /// Returns the inner value, if the `Arc` has exactly one strong reference.
466     ///
467     /// Otherwise, an [`Err`] is returned with the same `Arc` that was
468     /// passed in.
469     ///
470     /// This will succeed even if there are outstanding weak references.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// use std::sync::Arc;
476     ///
477     /// let x = Arc::new(3);
478     /// assert_eq!(Arc::try_unwrap(x), Ok(3));
479     ///
480     /// let x = Arc::new(4);
481     /// let _y = Arc::clone(&x);
482     /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
483     /// ```
484     #[inline]
485     #[stable(feature = "arc_unique", since = "1.4.0")]
486     pub fn try_unwrap(this: Self) -> Result<T, Self> {
487         if this.inner().strong.compare_exchange(1, 0, Relaxed, Relaxed).is_err() {
488             return Err(this);
489         }
490
491         acquire!(this.inner().strong);
492
493         unsafe {
494             let elem = ptr::read(&this.ptr.as_ref().data);
495
496             // Make a weak pointer to clean up the implicit strong-weak reference
497             let _weak = Weak { ptr: this.ptr };
498             mem::forget(this);
499
500             Ok(elem)
501         }
502     }
503 }
504
505 impl<T> Arc<[T]> {
506     /// Constructs a new atomically reference-counted slice with uninitialized contents.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// #![feature(new_uninit)]
512     /// #![feature(get_mut_unchecked)]
513     ///
514     /// use std::sync::Arc;
515     ///
516     /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
517     ///
518     /// let values = unsafe {
519     ///     // Deferred initialization:
520     ///     Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
521     ///     Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
522     ///     Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
523     ///
524     ///     values.assume_init()
525     /// };
526     ///
527     /// assert_eq!(*values, [1, 2, 3])
528     /// ```
529     #[unstable(feature = "new_uninit", issue = "63291")]
530     pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> {
531         unsafe { Arc::from_ptr(Arc::allocate_for_slice(len)) }
532     }
533
534     /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being
535     /// filled with `0` bytes.
536     ///
537     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
538     /// incorrect usage of this method.
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// #![feature(new_uninit)]
544     ///
545     /// use std::sync::Arc;
546     ///
547     /// let values = Arc::<[u32]>::new_zeroed_slice(3);
548     /// let values = unsafe { values.assume_init() };
549     ///
550     /// assert_eq!(*values, [0, 0, 0])
551     /// ```
552     ///
553     /// [zeroed]: mem::MaybeUninit::zeroed
554     #[unstable(feature = "new_uninit", issue = "63291")]
555     pub fn new_zeroed_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> {
556         unsafe {
557             Arc::from_ptr(Arc::allocate_for_layout(
558                 Layout::array::<T>(len).unwrap(),
559                 |layout| Global.alloc_zeroed(layout),
560                 |mem| {
561                     ptr::slice_from_raw_parts_mut(mem as *mut T, len)
562                         as *mut ArcInner<[mem::MaybeUninit<T>]>
563                 },
564             ))
565         }
566     }
567 }
568
569 impl<T> Arc<mem::MaybeUninit<T>> {
570     /// Converts to `Arc<T>`.
571     ///
572     /// # Safety
573     ///
574     /// As with [`MaybeUninit::assume_init`],
575     /// it is up to the caller to guarantee that the inner value
576     /// really is in an initialized state.
577     /// Calling this when the content is not yet fully initialized
578     /// causes immediate undefined behavior.
579     ///
580     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::method.assume_init
581     ///
582     /// # Examples
583     ///
584     /// ```
585     /// #![feature(new_uninit)]
586     /// #![feature(get_mut_unchecked)]
587     ///
588     /// use std::sync::Arc;
589     ///
590     /// let mut five = Arc::<u32>::new_uninit();
591     ///
592     /// let five = unsafe {
593     ///     // Deferred initialization:
594     ///     Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
595     ///
596     ///     five.assume_init()
597     /// };
598     ///
599     /// assert_eq!(*five, 5)
600     /// ```
601     #[unstable(feature = "new_uninit", issue = "63291")]
602     #[inline]
603     pub unsafe fn assume_init(self) -> Arc<T> {
604         Arc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
605     }
606 }
607
608 impl<T> Arc<[mem::MaybeUninit<T>]> {
609     /// Converts to `Arc<[T]>`.
610     ///
611     /// # Safety
612     ///
613     /// As with [`MaybeUninit::assume_init`],
614     /// it is up to the caller to guarantee that the inner value
615     /// really is in an initialized state.
616     /// Calling this when the content is not yet fully initialized
617     /// causes immediate undefined behavior.
618     ///
619     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::method.assume_init
620     ///
621     /// # Examples
622     ///
623     /// ```
624     /// #![feature(new_uninit)]
625     /// #![feature(get_mut_unchecked)]
626     ///
627     /// use std::sync::Arc;
628     ///
629     /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
630     ///
631     /// let values = unsafe {
632     ///     // Deferred initialization:
633     ///     Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
634     ///     Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
635     ///     Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
636     ///
637     ///     values.assume_init()
638     /// };
639     ///
640     /// assert_eq!(*values, [1, 2, 3])
641     /// ```
642     #[unstable(feature = "new_uninit", issue = "63291")]
643     #[inline]
644     pub unsafe fn assume_init(self) -> Arc<[T]> {
645         unsafe { Arc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
646     }
647 }
648
649 impl<T: ?Sized> Arc<T> {
650     /// Consumes the `Arc`, returning the wrapped pointer.
651     ///
652     /// To avoid a memory leak the pointer must be converted back to an `Arc` using
653     /// [`Arc::from_raw`].
654     ///
655     /// # Examples
656     ///
657     /// ```
658     /// use std::sync::Arc;
659     ///
660     /// let x = Arc::new("hello".to_owned());
661     /// let x_ptr = Arc::into_raw(x);
662     /// assert_eq!(unsafe { &*x_ptr }, "hello");
663     /// ```
664     #[stable(feature = "rc_raw", since = "1.17.0")]
665     pub fn into_raw(this: Self) -> *const T {
666         let ptr = Self::as_ptr(&this);
667         mem::forget(this);
668         ptr
669     }
670
671     /// Provides a raw pointer to the data.
672     ///
673     /// The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for
674     /// as long as there are strong counts in the `Arc`.
675     ///
676     /// # Examples
677     ///
678     /// ```
679     /// use std::sync::Arc;
680     ///
681     /// let x = Arc::new("hello".to_owned());
682     /// let y = Arc::clone(&x);
683     /// let x_ptr = Arc::as_ptr(&x);
684     /// assert_eq!(x_ptr, Arc::as_ptr(&y));
685     /// assert_eq!(unsafe { &*x_ptr }, "hello");
686     /// ```
687     #[stable(feature = "rc_as_ptr", since = "1.45.0")]
688     pub fn as_ptr(this: &Self) -> *const T {
689         let ptr: *mut ArcInner<T> = NonNull::as_ptr(this.ptr);
690
691         // SAFETY: This cannot go through Deref::deref or RcBoxPtr::inner because
692         // this is required to retain raw/mut provenance such that e.g. `get_mut` can
693         // write through the pointer after the Rc is recovered through `from_raw`.
694         unsafe { &raw const (*ptr).data }
695     }
696
697     /// Constructs an `Arc<T>` from a raw pointer.
698     ///
699     /// The raw pointer must have been previously returned by a call to
700     /// [`Arc<U>::into_raw`][into_raw] where `U` must have the same size and
701     /// alignment as `T`. This is trivially true if `U` is `T`.
702     /// Note that if `U` is not `T` but has the same size and alignment, this is
703     /// basically like transmuting references of different types. See
704     /// [`mem::transmute`][transmute] for more information on what
705     /// restrictions apply in this case.
706     ///
707     /// The user of `from_raw` has to make sure a specific value of `T` is only
708     /// dropped once.
709     ///
710     /// This function is unsafe because improper use may lead to memory unsafety,
711     /// even if the returned `Arc<T>` is never accessed.
712     ///
713     /// [into_raw]: Arc::into_raw
714     /// [transmute]: core::mem::transmute
715     ///
716     /// # Examples
717     ///
718     /// ```
719     /// use std::sync::Arc;
720     ///
721     /// let x = Arc::new("hello".to_owned());
722     /// let x_ptr = Arc::into_raw(x);
723     ///
724     /// unsafe {
725     ///     // Convert back to an `Arc` to prevent leak.
726     ///     let x = Arc::from_raw(x_ptr);
727     ///     assert_eq!(&*x, "hello");
728     ///
729     ///     // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.
730     /// }
731     ///
732     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
733     /// ```
734     #[stable(feature = "rc_raw", since = "1.17.0")]
735     pub unsafe fn from_raw(ptr: *const T) -> Self {
736         unsafe {
737             let offset = data_offset(ptr);
738
739             // Reverse the offset to find the original ArcInner.
740             let fake_ptr = ptr as *mut ArcInner<T>;
741             let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
742
743             Self::from_ptr(arc_ptr)
744         }
745     }
746
747     /// Creates a new [`Weak`] pointer to this allocation.
748     ///
749     /// # Examples
750     ///
751     /// ```
752     /// use std::sync::Arc;
753     ///
754     /// let five = Arc::new(5);
755     ///
756     /// let weak_five = Arc::downgrade(&five);
757     /// ```
758     #[stable(feature = "arc_weak", since = "1.4.0")]
759     pub fn downgrade(this: &Self) -> Weak<T> {
760         // This Relaxed is OK because we're checking the value in the CAS
761         // below.
762         let mut cur = this.inner().weak.load(Relaxed);
763
764         loop {
765             // check if the weak counter is currently "locked"; if so, spin.
766             if cur == usize::MAX {
767                 cur = this.inner().weak.load(Relaxed);
768                 continue;
769             }
770
771             // NOTE: this code currently ignores the possibility of overflow
772             // into usize::MAX; in general both Rc and Arc need to be adjusted
773             // to deal with overflow.
774
775             // Unlike with Clone(), we need this to be an Acquire read to
776             // synchronize with the write coming from `is_unique`, so that the
777             // events prior to that write happen before this read.
778             match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) {
779                 Ok(_) => {
780                     // Make sure we do not create a dangling Weak
781                     debug_assert!(!is_dangling(this.ptr));
782                     return Weak { ptr: this.ptr };
783                 }
784                 Err(old) => cur = old,
785             }
786         }
787     }
788
789     /// Gets the number of [`Weak`] pointers to this allocation.
790     ///
791     /// # Safety
792     ///
793     /// This method by itself is safe, but using it correctly requires extra care.
794     /// Another thread can change the weak count at any time,
795     /// including potentially between calling this method and acting on the result.
796     ///
797     /// # Examples
798     ///
799     /// ```
800     /// use std::sync::Arc;
801     ///
802     /// let five = Arc::new(5);
803     /// let _weak_five = Arc::downgrade(&five);
804     ///
805     /// // This assertion is deterministic because we haven't shared
806     /// // the `Arc` or `Weak` between threads.
807     /// assert_eq!(1, Arc::weak_count(&five));
808     /// ```
809     #[inline]
810     #[stable(feature = "arc_counts", since = "1.15.0")]
811     pub fn weak_count(this: &Self) -> usize {
812         let cnt = this.inner().weak.load(SeqCst);
813         // If the weak count is currently locked, the value of the
814         // count was 0 just before taking the lock.
815         if cnt == usize::MAX { 0 } else { cnt - 1 }
816     }
817
818     /// Gets the number of strong (`Arc`) pointers to this allocation.
819     ///
820     /// # Safety
821     ///
822     /// This method by itself is safe, but using it correctly requires extra care.
823     /// Another thread can change the strong count at any time,
824     /// including potentially between calling this method and acting on the result.
825     ///
826     /// # Examples
827     ///
828     /// ```
829     /// use std::sync::Arc;
830     ///
831     /// let five = Arc::new(5);
832     /// let _also_five = Arc::clone(&five);
833     ///
834     /// // This assertion is deterministic because we haven't shared
835     /// // the `Arc` between threads.
836     /// assert_eq!(2, Arc::strong_count(&five));
837     /// ```
838     #[inline]
839     #[stable(feature = "arc_counts", since = "1.15.0")]
840     pub fn strong_count(this: &Self) -> usize {
841         this.inner().strong.load(SeqCst)
842     }
843
844     /// Increments the strong reference count on the `Arc<T>` associated with the
845     /// provided pointer by one.
846     ///
847     /// # Safety
848     ///
849     /// The pointer must have been obtained through `Arc::into_raw`, and the
850     /// associated `Arc` instance must be valid (i.e. the strong count must be at
851     /// least 1) for the duration of this method.
852     ///
853     /// # Examples
854     ///
855     /// ```
856     /// #![feature(arc_mutate_strong_count)]
857     ///
858     /// use std::sync::Arc;
859     ///
860     /// let five = Arc::new(5);
861     ///
862     /// unsafe {
863     ///     let ptr = Arc::into_raw(five);
864     ///     Arc::incr_strong_count(ptr);
865     ///
866     ///     // This assertion is deterministic because we haven't shared
867     ///     // the `Arc` between threads.
868     ///     let five = Arc::from_raw(ptr);
869     ///     assert_eq!(2, Arc::strong_count(&five));
870     /// }
871     /// ```
872     #[inline]
873     #[unstable(feature = "arc_mutate_strong_count", issue = "71983")]
874     pub unsafe fn incr_strong_count(ptr: *const T) {
875         // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop
876         let arc = unsafe { mem::ManuallyDrop::new(Arc::<T>::from_raw(ptr)) };
877         // Now increase refcount, but don't drop new refcount either
878         let _arc_clone: mem::ManuallyDrop<_> = arc.clone();
879     }
880
881     /// Decrements the strong reference count on the `Arc<T>` associated with the
882     /// provided pointer by one.
883     ///
884     /// # Safety
885     ///
886     /// The pointer must have been obtained through `Arc::into_raw`, and the
887     /// associated `Arc` instance must be valid (i.e. the strong count must be at
888     /// least 1) when invoking this method. This method can be used to release the final
889     /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been
890     /// released.
891     ///
892     /// # Examples
893     ///
894     /// ```
895     /// #![feature(arc_mutate_strong_count)]
896     ///
897     /// use std::sync::Arc;
898     ///
899     /// let five = Arc::new(5);
900     ///
901     /// unsafe {
902     ///     let ptr = Arc::into_raw(five);
903     ///     Arc::incr_strong_count(ptr);
904     ///
905     ///     // Those assertions are deterministic because we haven't shared
906     ///     // the `Arc` between threads.
907     ///     let five = Arc::from_raw(ptr);
908     ///     assert_eq!(2, Arc::strong_count(&five));
909     ///     Arc::decr_strong_count(ptr);
910     ///     assert_eq!(1, Arc::strong_count(&five));
911     /// }
912     /// ```
913     #[inline]
914     #[unstable(feature = "arc_mutate_strong_count", issue = "71983")]
915     pub unsafe fn decr_strong_count(ptr: *const T) {
916         unsafe { mem::drop(Arc::from_raw(ptr)) };
917     }
918
919     #[inline]
920     fn inner(&self) -> &ArcInner<T> {
921         // This unsafety is ok because while this arc is alive we're guaranteed
922         // that the inner pointer is valid. Furthermore, we know that the
923         // `ArcInner` structure itself is `Sync` because the inner data is
924         // `Sync` as well, so we're ok loaning out an immutable pointer to these
925         // contents.
926         unsafe { self.ptr.as_ref() }
927     }
928
929     // Non-inlined part of `drop`.
930     #[inline(never)]
931     unsafe fn drop_slow(&mut self) {
932         // Destroy the data at this time, even though we may not free the box
933         // allocation itself (there may still be weak pointers lying around).
934         unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) };
935
936         // Drop the weak ref collectively held by all strong references
937         drop(Weak { ptr: self.ptr });
938     }
939
940     #[inline]
941     #[stable(feature = "ptr_eq", since = "1.17.0")]
942     /// Returns `true` if the two `Arc`s point to the same allocation
943     /// (in a vein similar to [`ptr::eq`]).
944     ///
945     /// # Examples
946     ///
947     /// ```
948     /// use std::sync::Arc;
949     ///
950     /// let five = Arc::new(5);
951     /// let same_five = Arc::clone(&five);
952     /// let other_five = Arc::new(5);
953     ///
954     /// assert!(Arc::ptr_eq(&five, &same_five));
955     /// assert!(!Arc::ptr_eq(&five, &other_five));
956     /// ```
957     ///
958     /// [`ptr::eq`]: core::ptr::eq
959     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
960         this.ptr.as_ptr() == other.ptr.as_ptr()
961     }
962 }
963
964 impl<T: ?Sized> Arc<T> {
965     /// Allocates an `ArcInner<T>` with sufficient space for
966     /// a possibly-unsized inner value where the value has the layout provided.
967     ///
968     /// The function `mem_to_arcinner` is called with the data pointer
969     /// and must return back a (potentially fat)-pointer for the `ArcInner<T>`.
970     unsafe fn allocate_for_layout(
971         value_layout: Layout,
972         allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocErr>,
973         mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner<T>,
974     ) -> *mut ArcInner<T> {
975         // Calculate layout using the given value layout.
976         // Previously, layout was calculated on the expression
977         // `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
978         // reference (see #54908).
979         let layout = Layout::new::<ArcInner<()>>().extend(value_layout).unwrap().0.pad_to_align();
980
981         let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout));
982
983         // Initialize the ArcInner
984         let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr());
985         debug_assert_eq!(unsafe { Layout::for_value(&*inner) }, layout);
986
987         unsafe {
988             ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
989             ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1));
990         }
991
992         inner
993     }
994
995     /// Allocates an `ArcInner<T>` with sufficient space for an unsized inner value.
996     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
997         // Allocate for the `ArcInner<T>` using the given value.
998         unsafe {
999             Self::allocate_for_layout(
1000                 Layout::for_value(&*ptr),
1001                 |layout| Global.alloc(layout),
1002                 |mem| set_data_ptr(ptr as *mut T, mem) as *mut ArcInner<T>,
1003             )
1004         }
1005     }
1006
1007     fn from_box(v: Box<T>) -> Arc<T> {
1008         unsafe {
1009             let box_unique = Box::into_unique(v);
1010             let bptr = box_unique.as_ptr();
1011
1012             let value_size = size_of_val(&*bptr);
1013             let ptr = Self::allocate_for_ptr(bptr);
1014
1015             // Copy value as bytes
1016             ptr::copy_nonoverlapping(
1017                 bptr as *const T as *const u8,
1018                 &mut (*ptr).data as *mut _ as *mut u8,
1019                 value_size,
1020             );
1021
1022             // Free the allocation without dropping its contents
1023             box_free(box_unique);
1024
1025             Self::from_ptr(ptr)
1026         }
1027     }
1028 }
1029
1030 impl<T> Arc<[T]> {
1031     /// Allocates an `ArcInner<[T]>` with the given length.
1032     unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> {
1033         unsafe {
1034             Self::allocate_for_layout(
1035                 Layout::array::<T>(len).unwrap(),
1036                 |layout| Global.alloc(layout),
1037                 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut ArcInner<[T]>,
1038             )
1039         }
1040     }
1041 }
1042
1043 /// Sets the data pointer of a `?Sized` raw pointer.
1044 ///
1045 /// For a slice/trait object, this sets the `data` field and leaves the rest
1046 /// unchanged. For a sized raw pointer, this simply sets the pointer.
1047 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
1048     unsafe {
1049         ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
1050     }
1051     ptr
1052 }
1053
1054 impl<T> Arc<[T]> {
1055     /// Copy elements from slice into newly allocated Arc<\[T\]>
1056     ///
1057     /// Unsafe because the caller must either take ownership or bind `T: Copy`.
1058     unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> {
1059         unsafe {
1060             let ptr = Self::allocate_for_slice(v.len());
1061
1062             ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).data as *mut [T] as *mut T, v.len());
1063
1064             Self::from_ptr(ptr)
1065         }
1066     }
1067
1068     /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size.
1069     ///
1070     /// Behavior is undefined should the size be wrong.
1071     unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Arc<[T]> {
1072         // Panic guard while cloning T elements.
1073         // In the event of a panic, elements that have been written
1074         // into the new ArcInner will be dropped, then the memory freed.
1075         struct Guard<T> {
1076             mem: NonNull<u8>,
1077             elems: *mut T,
1078             layout: Layout,
1079             n_elems: usize,
1080         }
1081
1082         impl<T> Drop for Guard<T> {
1083             fn drop(&mut self) {
1084                 unsafe {
1085                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
1086                     ptr::drop_in_place(slice);
1087
1088                     Global.dealloc(self.mem, self.layout);
1089                 }
1090             }
1091         }
1092
1093         unsafe {
1094             let ptr = Self::allocate_for_slice(len);
1095
1096             let mem = ptr as *mut _ as *mut u8;
1097             let layout = Layout::for_value(&*ptr);
1098
1099             // Pointer to first element
1100             let elems = &mut (*ptr).data as *mut [T] as *mut T;
1101
1102             let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1103
1104             for (i, item) in iter.enumerate() {
1105                 ptr::write(elems.add(i), item);
1106                 guard.n_elems += 1;
1107             }
1108
1109             // All clear. Forget the guard so it doesn't free the new ArcInner.
1110             mem::forget(guard);
1111
1112             Self::from_ptr(ptr)
1113         }
1114     }
1115 }
1116
1117 /// Specialization trait used for `From<&[T]>`.
1118 trait ArcFromSlice<T> {
1119     fn from_slice(slice: &[T]) -> Self;
1120 }
1121
1122 impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
1123     #[inline]
1124     default fn from_slice(v: &[T]) -> Self {
1125         unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1126     }
1127 }
1128
1129 impl<T: Copy> ArcFromSlice<T> for Arc<[T]> {
1130     #[inline]
1131     fn from_slice(v: &[T]) -> Self {
1132         unsafe { Arc::copy_from_slice(v) }
1133     }
1134 }
1135
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<T: ?Sized> Clone for Arc<T> {
1138     /// Makes a clone of the `Arc` pointer.
1139     ///
1140     /// This creates another pointer to the same allocation, increasing the
1141     /// strong reference count.
1142     ///
1143     /// # Examples
1144     ///
1145     /// ```
1146     /// use std::sync::Arc;
1147     ///
1148     /// let five = Arc::new(5);
1149     ///
1150     /// let _ = Arc::clone(&five);
1151     /// ```
1152     #[inline]
1153     fn clone(&self) -> Arc<T> {
1154         // Using a relaxed ordering is alright here, as knowledge of the
1155         // original reference prevents other threads from erroneously deleting
1156         // the object.
1157         //
1158         // As explained in the [Boost documentation][1], Increasing the
1159         // reference counter can always be done with memory_order_relaxed: New
1160         // references to an object can only be formed from an existing
1161         // reference, and passing an existing reference from one thread to
1162         // another must already provide any required synchronization.
1163         //
1164         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1165         let old_size = self.inner().strong.fetch_add(1, Relaxed);
1166
1167         // However we need to guard against massive refcounts in case someone
1168         // is `mem::forget`ing Arcs. If we don't do this the count can overflow
1169         // and users will use-after free. We racily saturate to `isize::MAX` on
1170         // the assumption that there aren't ~2 billion threads incrementing
1171         // the reference count at once. This branch will never be taken in
1172         // any realistic program.
1173         //
1174         // We abort because such a program is incredibly degenerate, and we
1175         // don't care to support it.
1176         if old_size > MAX_REFCOUNT {
1177             abort();
1178         }
1179
1180         Self::from_inner(self.ptr)
1181     }
1182 }
1183
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<T: ?Sized> Deref for Arc<T> {
1186     type Target = T;
1187
1188     #[inline]
1189     fn deref(&self) -> &T {
1190         &self.inner().data
1191     }
1192 }
1193
1194 #[unstable(feature = "receiver_trait", issue = "none")]
1195 impl<T: ?Sized> Receiver for Arc<T> {}
1196
1197 impl<T: Clone> Arc<T> {
1198     /// Makes a mutable reference into the given `Arc`.
1199     ///
1200     /// If there are other `Arc` or [`Weak`] pointers to the same allocation,
1201     /// then `make_mut` will create a new allocation and invoke [`clone`][clone] on the inner value
1202     /// to ensure unique ownership. This is also referred to as clone-on-write.
1203     ///
1204     /// Note that this differs from the behavior of [`Rc::make_mut`] which disassociates
1205     /// any remaining `Weak` pointers.
1206     ///
1207     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
1208     ///
1209     /// [clone]: Clone::clone
1210     /// [get_mut]: Arc::get_mut
1211     /// [`Rc::make_mut`]: super::rc::Rc::make_mut
1212     ///
1213     /// # Examples
1214     ///
1215     /// ```
1216     /// use std::sync::Arc;
1217     ///
1218     /// let mut data = Arc::new(5);
1219     ///
1220     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
1221     /// let mut other_data = Arc::clone(&data); // Won't clone inner data
1222     /// *Arc::make_mut(&mut data) += 1;         // Clones inner data
1223     /// *Arc::make_mut(&mut data) += 1;         // Won't clone anything
1224     /// *Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything
1225     ///
1226     /// // Now `data` and `other_data` point to different allocations.
1227     /// assert_eq!(*data, 8);
1228     /// assert_eq!(*other_data, 12);
1229     /// ```
1230     #[inline]
1231     #[stable(feature = "arc_unique", since = "1.4.0")]
1232     pub fn make_mut(this: &mut Self) -> &mut T {
1233         // Note that we hold both a strong reference and a weak reference.
1234         // Thus, releasing our strong reference only will not, by itself, cause
1235         // the memory to be deallocated.
1236         //
1237         // Use Acquire to ensure that we see any writes to `weak` that happen
1238         // before release writes (i.e., decrements) to `strong`. Since we hold a
1239         // weak count, there's no chance the ArcInner itself could be
1240         // deallocated.
1241         if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() {
1242             // Another strong pointer exists; clone
1243             *this = Arc::new((**this).clone());
1244         } else if this.inner().weak.load(Relaxed) != 1 {
1245             // Relaxed suffices in the above because this is fundamentally an
1246             // optimization: we are always racing with weak pointers being
1247             // dropped. Worst case, we end up allocated a new Arc unnecessarily.
1248
1249             // We removed the last strong ref, but there are additional weak
1250             // refs remaining. We'll move the contents to a new Arc, and
1251             // invalidate the other weak refs.
1252
1253             // Note that it is not possible for the read of `weak` to yield
1254             // usize::MAX (i.e., locked), since the weak count can only be
1255             // locked by a thread with a strong reference.
1256
1257             // Materialize our own implicit weak pointer, so that it can clean
1258             // up the ArcInner as needed.
1259             let weak = Weak { ptr: this.ptr };
1260
1261             // mark the data itself as already deallocated
1262             unsafe {
1263                 // there is no data race in the implicit write caused by `read`
1264                 // here (due to zeroing) because data is no longer accessed by
1265                 // other threads (due to there being no more strong refs at this
1266                 // point).
1267                 let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data));
1268                 mem::swap(this, &mut swap);
1269                 mem::forget(swap);
1270             }
1271         } else {
1272             // We were the sole reference of either kind; bump back up the
1273             // strong ref count.
1274             this.inner().strong.store(1, Release);
1275         }
1276
1277         // As with `get_mut()`, the unsafety is ok because our reference was
1278         // either unique to begin with, or became one upon cloning the contents.
1279         unsafe { Self::get_mut_unchecked(this) }
1280     }
1281 }
1282
1283 impl<T: ?Sized> Arc<T> {
1284     /// Returns a mutable reference into the given `Arc`, if there are
1285     /// no other `Arc` or [`Weak`] pointers to the same allocation.
1286     ///
1287     /// Returns [`None`] otherwise, because it is not safe to
1288     /// mutate a shared value.
1289     ///
1290     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1291     /// the inner value when there are other pointers.
1292     ///
1293     /// [make_mut]: Arc::make_mut
1294     /// [clone]: Clone::clone
1295     ///
1296     /// # Examples
1297     ///
1298     /// ```
1299     /// use std::sync::Arc;
1300     ///
1301     /// let mut x = Arc::new(3);
1302     /// *Arc::get_mut(&mut x).unwrap() = 4;
1303     /// assert_eq!(*x, 4);
1304     ///
1305     /// let _y = Arc::clone(&x);
1306     /// assert!(Arc::get_mut(&mut x).is_none());
1307     /// ```
1308     #[inline]
1309     #[stable(feature = "arc_unique", since = "1.4.0")]
1310     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1311         if this.is_unique() {
1312             // This unsafety is ok because we're guaranteed that the pointer
1313             // returned is the *only* pointer that will ever be returned to T. Our
1314             // reference count is guaranteed to be 1 at this point, and we required
1315             // the Arc itself to be `mut`, so we're returning the only possible
1316             // reference to the inner data.
1317             unsafe { Some(Arc::get_mut_unchecked(this)) }
1318         } else {
1319             None
1320         }
1321     }
1322
1323     /// Returns a mutable reference into the given `Arc`,
1324     /// without any check.
1325     ///
1326     /// See also [`get_mut`], which is safe and does appropriate checks.
1327     ///
1328     /// [`get_mut`]: Arc::get_mut
1329     ///
1330     /// # Safety
1331     ///
1332     /// Any other `Arc` or [`Weak`] pointers to the same allocation must not be dereferenced
1333     /// for the duration of the returned borrow.
1334     /// This is trivially the case if no such pointers exist,
1335     /// for example immediately after `Arc::new`.
1336     ///
1337     /// # Examples
1338     ///
1339     /// ```
1340     /// #![feature(get_mut_unchecked)]
1341     ///
1342     /// use std::sync::Arc;
1343     ///
1344     /// let mut x = Arc::new(String::new());
1345     /// unsafe {
1346     ///     Arc::get_mut_unchecked(&mut x).push_str("foo")
1347     /// }
1348     /// assert_eq!(*x, "foo");
1349     /// ```
1350     #[inline]
1351     #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1352     pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1353         // We are careful to *not* create a reference covering the "count" fields, as
1354         // this would alias with concurrent access to the reference counts (e.g. by `Weak`).
1355         unsafe { &mut (*this.ptr.as_ptr()).data }
1356     }
1357
1358     /// Determine whether this is the unique reference (including weak refs) to
1359     /// the underlying data.
1360     ///
1361     /// Note that this requires locking the weak ref count.
1362     fn is_unique(&mut self) -> bool {
1363         // lock the weak pointer count if we appear to be the sole weak pointer
1364         // holder.
1365         //
1366         // The acquire label here ensures a happens-before relationship with any
1367         // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements
1368         // of the `weak` count (via `Weak::drop`, which uses release).  If the upgraded
1369         // weak ref was never dropped, the CAS here will fail so we do not care to synchronize.
1370         if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() {
1371             // This needs to be an `Acquire` to synchronize with the decrement of the `strong`
1372             // counter in `drop` -- the only access that happens when any but the last reference
1373             // is being dropped.
1374             let unique = self.inner().strong.load(Acquire) == 1;
1375
1376             // The release write here synchronizes with a read in `downgrade`,
1377             // effectively preventing the above read of `strong` from happening
1378             // after the write.
1379             self.inner().weak.store(1, Release); // release the lock
1380             unique
1381         } else {
1382             false
1383         }
1384     }
1385 }
1386
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> {
1389     /// Drops the `Arc`.
1390     ///
1391     /// This will decrement the strong reference count. If the strong reference
1392     /// count reaches zero then the only other references (if any) are
1393     /// [`Weak`], so we `drop` the inner value.
1394     ///
1395     /// # Examples
1396     ///
1397     /// ```
1398     /// use std::sync::Arc;
1399     ///
1400     /// struct Foo;
1401     ///
1402     /// impl Drop for Foo {
1403     ///     fn drop(&mut self) {
1404     ///         println!("dropped!");
1405     ///     }
1406     /// }
1407     ///
1408     /// let foo  = Arc::new(Foo);
1409     /// let foo2 = Arc::clone(&foo);
1410     ///
1411     /// drop(foo);    // Doesn't print anything
1412     /// drop(foo2);   // Prints "dropped!"
1413     /// ```
1414     #[inline]
1415     fn drop(&mut self) {
1416         // Because `fetch_sub` is already atomic, we do not need to synchronize
1417         // with other threads unless we are going to delete the object. This
1418         // same logic applies to the below `fetch_sub` to the `weak` count.
1419         if self.inner().strong.fetch_sub(1, Release) != 1 {
1420             return;
1421         }
1422
1423         // This fence is needed to prevent reordering of use of the data and
1424         // deletion of the data.  Because it is marked `Release`, the decreasing
1425         // of the reference count synchronizes with this `Acquire` fence. This
1426         // means that use of the data happens before decreasing the reference
1427         // count, which happens before this fence, which happens before the
1428         // deletion of the data.
1429         //
1430         // As explained in the [Boost documentation][1],
1431         //
1432         // > It is important to enforce any possible access to the object in one
1433         // > thread (through an existing reference) to *happen before* deleting
1434         // > the object in a different thread. This is achieved by a "release"
1435         // > operation after dropping a reference (any access to the object
1436         // > through this reference must obviously happened before), and an
1437         // > "acquire" operation before deleting the object.
1438         //
1439         // In particular, while the contents of an Arc are usually immutable, it's
1440         // possible to have interior writes to something like a Mutex<T>. Since a
1441         // Mutex is not acquired when it is deleted, we can't rely on its
1442         // synchronization logic to make writes in thread A visible to a destructor
1443         // running in thread B.
1444         //
1445         // Also note that the Acquire fence here could probably be replaced with an
1446         // Acquire load, which could improve performance in highly-contended
1447         // situations. See [2].
1448         //
1449         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
1450         // [2]: (https://github.com/rust-lang/rust/pull/41714)
1451         acquire!(self.inner().strong);
1452
1453         unsafe {
1454             self.drop_slow();
1455         }
1456     }
1457 }
1458
1459 impl Arc<dyn Any + Send + Sync> {
1460     #[inline]
1461     #[stable(feature = "rc_downcast", since = "1.29.0")]
1462     /// Attempt to downcast the `Arc<dyn Any + Send + Sync>` to a concrete type.
1463     ///
1464     /// # Examples
1465     ///
1466     /// ```
1467     /// use std::any::Any;
1468     /// use std::sync::Arc;
1469     ///
1470     /// fn print_if_string(value: Arc<dyn Any + Send + Sync>) {
1471     ///     if let Ok(string) = value.downcast::<String>() {
1472     ///         println!("String ({}): {}", string.len(), string);
1473     ///     }
1474     /// }
1475     ///
1476     /// let my_string = "Hello World".to_string();
1477     /// print_if_string(Arc::new(my_string));
1478     /// print_if_string(Arc::new(0i8));
1479     /// ```
1480     pub fn downcast<T>(self) -> Result<Arc<T>, Self>
1481     where
1482         T: Any + Send + Sync + 'static,
1483     {
1484         if (*self).is::<T>() {
1485             let ptr = self.ptr.cast::<ArcInner<T>>();
1486             mem::forget(self);
1487             Ok(Arc::from_inner(ptr))
1488         } else {
1489             Err(self)
1490         }
1491     }
1492 }
1493
1494 impl<T> Weak<T> {
1495     /// Constructs a new `Weak<T>`, without allocating any memory.
1496     /// Calling [`upgrade`] on the return value always gives [`None`].
1497     ///
1498     /// [`upgrade`]: Weak::upgrade
1499     ///
1500     /// # Examples
1501     ///
1502     /// ```
1503     /// use std::sync::Weak;
1504     ///
1505     /// let empty: Weak<i64> = Weak::new();
1506     /// assert!(empty.upgrade().is_none());
1507     /// ```
1508     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1509     pub fn new() -> Weak<T> {
1510         Weak { ptr: NonNull::new(usize::MAX as *mut ArcInner<T>).expect("MAX is not 0") }
1511     }
1512
1513     /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1514     ///
1515     /// The pointer is valid only if there are some strong references. The pointer may be dangling,
1516     /// unaligned or even [`null`] otherwise.
1517     ///
1518     /// # Examples
1519     ///
1520     /// ```
1521     /// use std::sync::Arc;
1522     /// use std::ptr;
1523     ///
1524     /// let strong = Arc::new("hello".to_owned());
1525     /// let weak = Arc::downgrade(&strong);
1526     /// // Both point to the same object
1527     /// assert!(ptr::eq(&*strong, weak.as_ptr()));
1528     /// // The strong here keeps it alive, so we can still access the object.
1529     /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
1530     ///
1531     /// drop(strong);
1532     /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
1533     /// // undefined behaviour.
1534     /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
1535     /// ```
1536     ///
1537     /// [`null`]: core::ptr::null
1538     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1539     pub fn as_ptr(&self) -> *const T {
1540         let ptr: *mut ArcInner<T> = NonNull::as_ptr(self.ptr);
1541
1542         // SAFETY: we must offset the pointer manually, and said pointer may be
1543         // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call,
1544         // because we know that a pointer to unsized T was derived from a real
1545         // unsized T, as dangling weaks are only created for sized T. wrapping_offset
1546         // is used so that we can use the same code path for the non-dangling
1547         // unsized case and the potentially dangling sized case.
1548         unsafe {
1549             let offset = data_offset(ptr as *mut T);
1550             set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset))
1551         }
1552     }
1553
1554     /// Consumes the `Weak<T>` and turns it into a raw pointer.
1555     ///
1556     /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
1557     /// one weak reference (the weak count is not modified by this operation). It can be turned
1558     /// back into the `Weak<T>` with [`from_raw`].
1559     ///
1560     /// The same restrictions of accessing the target of the pointer as with
1561     /// [`as_ptr`] apply.
1562     ///
1563     /// # Examples
1564     ///
1565     /// ```
1566     /// use std::sync::{Arc, Weak};
1567     ///
1568     /// let strong = Arc::new("hello".to_owned());
1569     /// let weak = Arc::downgrade(&strong);
1570     /// let raw = weak.into_raw();
1571     ///
1572     /// assert_eq!(1, Arc::weak_count(&strong));
1573     /// assert_eq!("hello", unsafe { &*raw });
1574     ///
1575     /// drop(unsafe { Weak::from_raw(raw) });
1576     /// assert_eq!(0, Arc::weak_count(&strong));
1577     /// ```
1578     ///
1579     /// [`from_raw`]: Weak::from_raw
1580     /// [`as_ptr`]: Weak::as_ptr
1581     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1582     pub fn into_raw(self) -> *const T {
1583         let result = self.as_ptr();
1584         mem::forget(self);
1585         result
1586     }
1587
1588     /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1589     ///
1590     /// This can be used to safely get a strong reference (by calling [`upgrade`]
1591     /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1592     ///
1593     /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
1594     /// as these don't own anything; the method still works on them).
1595     ///
1596     /// # Safety
1597     ///
1598     /// The pointer must have originated from the [`into_raw`] and must still own its potential
1599     /// weak reference.
1600     ///
1601     /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
1602     /// takes ownership of one weak reference currently represented as a raw pointer (the weak
1603     /// count is not modified by this operation) and therefore it must be paired with a previous
1604     /// call to [`into_raw`].
1605     /// # Examples
1606     ///
1607     /// ```
1608     /// use std::sync::{Arc, Weak};
1609     ///
1610     /// let strong = Arc::new("hello".to_owned());
1611     ///
1612     /// let raw_1 = Arc::downgrade(&strong).into_raw();
1613     /// let raw_2 = Arc::downgrade(&strong).into_raw();
1614     ///
1615     /// assert_eq!(2, Arc::weak_count(&strong));
1616     ///
1617     /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1618     /// assert_eq!(1, Arc::weak_count(&strong));
1619     ///
1620     /// drop(strong);
1621     ///
1622     /// // Decrement the last weak count.
1623     /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1624     /// ```
1625     ///
1626     /// [`new`]: Weak::new
1627     /// [`into_raw`]: Weak::into_raw
1628     /// [`upgrade`]: Weak::upgrade
1629     /// [`forget`]: std::mem::forget
1630     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1631     pub unsafe fn from_raw(ptr: *const T) -> Self {
1632         if ptr.is_null() {
1633             Self::new()
1634         } else {
1635             // See Arc::from_raw for details
1636             unsafe {
1637                 let offset = data_offset(ptr);
1638                 let fake_ptr = ptr as *mut ArcInner<T>;
1639                 let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1640                 Weak { ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw") }
1641             }
1642         }
1643     }
1644 }
1645
1646 /// Helper type to allow accessing the reference counts without
1647 /// making any assertions about the data field.
1648 struct WeakInner<'a> {
1649     weak: &'a atomic::AtomicUsize,
1650     strong: &'a atomic::AtomicUsize,
1651 }
1652
1653 impl<T: ?Sized> Weak<T> {
1654     /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying
1655     /// dropping of the inner value if successful.
1656     ///
1657     /// Returns [`None`] if the inner value has since been dropped.
1658     ///
1659     /// # Examples
1660     ///
1661     /// ```
1662     /// use std::sync::Arc;
1663     ///
1664     /// let five = Arc::new(5);
1665     ///
1666     /// let weak_five = Arc::downgrade(&five);
1667     ///
1668     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1669     /// assert!(strong_five.is_some());
1670     ///
1671     /// // Destroy all strong pointers.
1672     /// drop(strong_five);
1673     /// drop(five);
1674     ///
1675     /// assert!(weak_five.upgrade().is_none());
1676     /// ```
1677     #[stable(feature = "arc_weak", since = "1.4.0")]
1678     pub fn upgrade(&self) -> Option<Arc<T>> {
1679         // We use a CAS loop to increment the strong count instead of a
1680         // fetch_add as this function should never take the reference count
1681         // from zero to one.
1682         let inner = self.inner()?;
1683
1684         // Relaxed load because any write of 0 that we can observe
1685         // leaves the field in a permanently zero state (so a
1686         // "stale" read of 0 is fine), and any other value is
1687         // confirmed via the CAS below.
1688         let mut n = inner.strong.load(Relaxed);
1689
1690         loop {
1691             if n == 0 {
1692                 return None;
1693             }
1694
1695             // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1696             if n > MAX_REFCOUNT {
1697                 abort();
1698             }
1699
1700             // Relaxed is fine for the failure case because we don't have any expectations about the new state.
1701             // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner
1702             // value can be initialized after `Weak` references have already been created. In that case, we
1703             // expect to observe the fully initialized value.
1704             match inner.strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed) {
1705                 Ok(_) => return Some(Arc::from_inner(self.ptr)), // null checked above
1706                 Err(old) => n = old,
1707             }
1708         }
1709     }
1710
1711     /// Gets the number of strong (`Arc`) pointers pointing to this allocation.
1712     ///
1713     /// If `self` was created using [`Weak::new`], this will return 0.
1714     #[stable(feature = "weak_counts", since = "1.41.0")]
1715     pub fn strong_count(&self) -> usize {
1716         if let Some(inner) = self.inner() { inner.strong.load(SeqCst) } else { 0 }
1717     }
1718
1719     /// Gets an approximation of the number of `Weak` pointers pointing to this
1720     /// allocation.
1721     ///
1722     /// If `self` was created using [`Weak::new`], or if there are no remaining
1723     /// strong pointers, this will return 0.
1724     ///
1725     /// # Accuracy
1726     ///
1727     /// Due to implementation details, the returned value can be off by 1 in
1728     /// either direction when other threads are manipulating any `Arc`s or
1729     /// `Weak`s pointing to the same allocation.
1730     #[stable(feature = "weak_counts", since = "1.41.0")]
1731     pub fn weak_count(&self) -> usize {
1732         self.inner()
1733             .map(|inner| {
1734                 let weak = inner.weak.load(SeqCst);
1735                 let strong = inner.strong.load(SeqCst);
1736                 if strong == 0 {
1737                     0
1738                 } else {
1739                     // Since we observed that there was at least one strong pointer
1740                     // after reading the weak count, we know that the implicit weak
1741                     // reference (present whenever any strong references are alive)
1742                     // was still around when we observed the weak count, and can
1743                     // therefore safely subtract it.
1744                     weak - 1
1745                 }
1746             })
1747             .unwrap_or(0)
1748     }
1749
1750     /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
1751     /// (i.e., when this `Weak` was created by `Weak::new`).
1752     #[inline]
1753     fn inner(&self) -> Option<WeakInner<'_>> {
1754         if is_dangling(self.ptr) {
1755             None
1756         } else {
1757             // We are careful to *not* create a reference covering the "data" field, as
1758             // the field may be mutated concurrently (for example, if the last `Arc`
1759             // is dropped, the data field will be dropped in-place).
1760             Some(unsafe {
1761                 let ptr = self.ptr.as_ptr();
1762                 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
1763             })
1764         }
1765     }
1766
1767     /// Returns `true` if the two `Weak`s point to the same allocation (similar to
1768     /// [`ptr::eq`]), or if both don't point to any allocation
1769     /// (because they were created with `Weak::new()`).
1770     ///
1771     /// # Notes
1772     ///
1773     /// Since this compares pointers it means that `Weak::new()` will equal each
1774     /// other, even though they don't point to any allocation.
1775     ///
1776     /// # Examples
1777     ///
1778     /// ```
1779     /// use std::sync::Arc;
1780     ///
1781     /// let first_rc = Arc::new(5);
1782     /// let first = Arc::downgrade(&first_rc);
1783     /// let second = Arc::downgrade(&first_rc);
1784     ///
1785     /// assert!(first.ptr_eq(&second));
1786     ///
1787     /// let third_rc = Arc::new(5);
1788     /// let third = Arc::downgrade(&third_rc);
1789     ///
1790     /// assert!(!first.ptr_eq(&third));
1791     /// ```
1792     ///
1793     /// Comparing `Weak::new`.
1794     ///
1795     /// ```
1796     /// use std::sync::{Arc, Weak};
1797     ///
1798     /// let first = Weak::new();
1799     /// let second = Weak::new();
1800     /// assert!(first.ptr_eq(&second));
1801     ///
1802     /// let third_rc = Arc::new(());
1803     /// let third = Arc::downgrade(&third_rc);
1804     /// assert!(!first.ptr_eq(&third));
1805     /// ```
1806     ///
1807     /// [`ptr::eq`]: core::ptr::eq
1808     #[inline]
1809     #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1810     pub fn ptr_eq(&self, other: &Self) -> bool {
1811         self.ptr.as_ptr() == other.ptr.as_ptr()
1812     }
1813 }
1814
1815 #[stable(feature = "arc_weak", since = "1.4.0")]
1816 impl<T: ?Sized> Clone for Weak<T> {
1817     /// Makes a clone of the `Weak` pointer that points to the same allocation.
1818     ///
1819     /// # Examples
1820     ///
1821     /// ```
1822     /// use std::sync::{Arc, Weak};
1823     ///
1824     /// let weak_five = Arc::downgrade(&Arc::new(5));
1825     ///
1826     /// let _ = Weak::clone(&weak_five);
1827     /// ```
1828     #[inline]
1829     fn clone(&self) -> Weak<T> {
1830         let inner = if let Some(inner) = self.inner() {
1831             inner
1832         } else {
1833             return Weak { ptr: self.ptr };
1834         };
1835         // See comments in Arc::clone() for why this is relaxed.  This can use a
1836         // fetch_add (ignoring the lock) because the weak count is only locked
1837         // where are *no other* weak pointers in existence. (So we can't be
1838         // running this code in that case).
1839         let old_size = inner.weak.fetch_add(1, Relaxed);
1840
1841         // See comments in Arc::clone() for why we do this (for mem::forget).
1842         if old_size > MAX_REFCOUNT {
1843             abort();
1844         }
1845
1846         Weak { ptr: self.ptr }
1847     }
1848 }
1849
1850 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1851 impl<T> Default for Weak<T> {
1852     /// Constructs a new `Weak<T>`, without allocating memory.
1853     /// Calling [`upgrade`] on the return value always
1854     /// gives [`None`].
1855     ///
1856     /// [`upgrade`]: Weak::upgrade
1857     ///
1858     /// # Examples
1859     ///
1860     /// ```
1861     /// use std::sync::Weak;
1862     ///
1863     /// let empty: Weak<i64> = Default::default();
1864     /// assert!(empty.upgrade().is_none());
1865     /// ```
1866     fn default() -> Weak<T> {
1867         Weak::new()
1868     }
1869 }
1870
1871 #[stable(feature = "arc_weak", since = "1.4.0")]
1872 impl<T: ?Sized> Drop for Weak<T> {
1873     /// Drops the `Weak` pointer.
1874     ///
1875     /// # Examples
1876     ///
1877     /// ```
1878     /// use std::sync::{Arc, Weak};
1879     ///
1880     /// struct Foo;
1881     ///
1882     /// impl Drop for Foo {
1883     ///     fn drop(&mut self) {
1884     ///         println!("dropped!");
1885     ///     }
1886     /// }
1887     ///
1888     /// let foo = Arc::new(Foo);
1889     /// let weak_foo = Arc::downgrade(&foo);
1890     /// let other_weak_foo = Weak::clone(&weak_foo);
1891     ///
1892     /// drop(weak_foo);   // Doesn't print anything
1893     /// drop(foo);        // Prints "dropped!"
1894     ///
1895     /// assert!(other_weak_foo.upgrade().is_none());
1896     /// ```
1897     fn drop(&mut self) {
1898         // If we find out that we were the last weak pointer, then its time to
1899         // deallocate the data entirely. See the discussion in Arc::drop() about
1900         // the memory orderings
1901         //
1902         // It's not necessary to check for the locked state here, because the
1903         // weak count can only be locked if there was precisely one weak ref,
1904         // meaning that drop could only subsequently run ON that remaining weak
1905         // ref, which can only happen after the lock is released.
1906         let inner = if let Some(inner) = self.inner() { inner } else { return };
1907
1908         if inner.weak.fetch_sub(1, Release) == 1 {
1909             acquire!(inner.weak);
1910             unsafe { Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())) }
1911         }
1912     }
1913 }
1914
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 trait ArcEqIdent<T: ?Sized + PartialEq> {
1917     fn eq(&self, other: &Arc<T>) -> bool;
1918     fn ne(&self, other: &Arc<T>) -> bool;
1919 }
1920
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1923     #[inline]
1924     default fn eq(&self, other: &Arc<T>) -> bool {
1925         **self == **other
1926     }
1927     #[inline]
1928     default fn ne(&self, other: &Arc<T>) -> bool {
1929         **self != **other
1930     }
1931 }
1932
1933 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1934 /// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
1935 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1936 /// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
1937 /// the same value, than two `&T`s.
1938 ///
1939 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl<T: ?Sized + crate::rc::MarkerEq> ArcEqIdent<T> for Arc<T> {
1942     #[inline]
1943     fn eq(&self, other: &Arc<T>) -> bool {
1944         Arc::ptr_eq(self, other) || **self == **other
1945     }
1946
1947     #[inline]
1948     fn ne(&self, other: &Arc<T>) -> bool {
1949         !Arc::ptr_eq(self, other) && **self != **other
1950     }
1951 }
1952
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1955     /// Equality for two `Arc`s.
1956     ///
1957     /// Two `Arc`s are equal if their inner values are equal, even if they are
1958     /// stored in different allocation.
1959     ///
1960     /// If `T` also implements `Eq` (implying reflexivity of equality),
1961     /// two `Arc`s that point to the same allocation are always equal.
1962     ///
1963     /// # Examples
1964     ///
1965     /// ```
1966     /// use std::sync::Arc;
1967     ///
1968     /// let five = Arc::new(5);
1969     ///
1970     /// assert!(five == Arc::new(5));
1971     /// ```
1972     #[inline]
1973     fn eq(&self, other: &Arc<T>) -> bool {
1974         ArcEqIdent::eq(self, other)
1975     }
1976
1977     /// Inequality for two `Arc`s.
1978     ///
1979     /// Two `Arc`s are unequal if their inner values are unequal.
1980     ///
1981     /// If `T` also implements `Eq` (implying reflexivity of equality),
1982     /// two `Arc`s that point to the same value are never unequal.
1983     ///
1984     /// # Examples
1985     ///
1986     /// ```
1987     /// use std::sync::Arc;
1988     ///
1989     /// let five = Arc::new(5);
1990     ///
1991     /// assert!(five != Arc::new(6));
1992     /// ```
1993     #[inline]
1994     fn ne(&self, other: &Arc<T>) -> bool {
1995         ArcEqIdent::ne(self, other)
1996     }
1997 }
1998
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
2001     /// Partial comparison for two `Arc`s.
2002     ///
2003     /// The two are compared by calling `partial_cmp()` on their inner values.
2004     ///
2005     /// # Examples
2006     ///
2007     /// ```
2008     /// use std::sync::Arc;
2009     /// use std::cmp::Ordering;
2010     ///
2011     /// let five = Arc::new(5);
2012     ///
2013     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
2014     /// ```
2015     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
2016         (**self).partial_cmp(&**other)
2017     }
2018
2019     /// Less-than comparison for two `Arc`s.
2020     ///
2021     /// The two are compared by calling `<` on their inner values.
2022     ///
2023     /// # Examples
2024     ///
2025     /// ```
2026     /// use std::sync::Arc;
2027     ///
2028     /// let five = Arc::new(5);
2029     ///
2030     /// assert!(five < Arc::new(6));
2031     /// ```
2032     fn lt(&self, other: &Arc<T>) -> bool {
2033         *(*self) < *(*other)
2034     }
2035
2036     /// 'Less than or equal to' comparison for two `Arc`s.
2037     ///
2038     /// The two are compared by calling `<=` on their inner values.
2039     ///
2040     /// # Examples
2041     ///
2042     /// ```
2043     /// use std::sync::Arc;
2044     ///
2045     /// let five = Arc::new(5);
2046     ///
2047     /// assert!(five <= Arc::new(5));
2048     /// ```
2049     fn le(&self, other: &Arc<T>) -> bool {
2050         *(*self) <= *(*other)
2051     }
2052
2053     /// Greater-than comparison for two `Arc`s.
2054     ///
2055     /// The two are compared by calling `>` on their inner values.
2056     ///
2057     /// # Examples
2058     ///
2059     /// ```
2060     /// use std::sync::Arc;
2061     ///
2062     /// let five = Arc::new(5);
2063     ///
2064     /// assert!(five > Arc::new(4));
2065     /// ```
2066     fn gt(&self, other: &Arc<T>) -> bool {
2067         *(*self) > *(*other)
2068     }
2069
2070     /// 'Greater than or equal to' comparison for two `Arc`s.
2071     ///
2072     /// The two are compared by calling `>=` on their inner values.
2073     ///
2074     /// # Examples
2075     ///
2076     /// ```
2077     /// use std::sync::Arc;
2078     ///
2079     /// let five = Arc::new(5);
2080     ///
2081     /// assert!(five >= Arc::new(5));
2082     /// ```
2083     fn ge(&self, other: &Arc<T>) -> bool {
2084         *(*self) >= *(*other)
2085     }
2086 }
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl<T: ?Sized + Ord> Ord for Arc<T> {
2089     /// Comparison for two `Arc`s.
2090     ///
2091     /// The two are compared by calling `cmp()` on their inner values.
2092     ///
2093     /// # Examples
2094     ///
2095     /// ```
2096     /// use std::sync::Arc;
2097     /// use std::cmp::Ordering;
2098     ///
2099     /// let five = Arc::new(5);
2100     ///
2101     /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
2102     /// ```
2103     fn cmp(&self, other: &Arc<T>) -> Ordering {
2104         (**self).cmp(&**other)
2105     }
2106 }
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 impl<T: ?Sized + Eq> Eq for Arc<T> {}
2109
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
2112     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2113         fmt::Display::fmt(&**self, f)
2114     }
2115 }
2116
2117 #[stable(feature = "rust1", since = "1.0.0")]
2118 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
2119     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2120         fmt::Debug::fmt(&**self, f)
2121     }
2122 }
2123
2124 #[stable(feature = "rust1", since = "1.0.0")]
2125 impl<T: ?Sized> fmt::Pointer for Arc<T> {
2126     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2127         fmt::Pointer::fmt(&(&**self as *const T), f)
2128     }
2129 }
2130
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<T: Default> Default for Arc<T> {
2133     /// Creates a new `Arc<T>`, with the `Default` value for `T`.
2134     ///
2135     /// # Examples
2136     ///
2137     /// ```
2138     /// use std::sync::Arc;
2139     ///
2140     /// let x: Arc<i32> = Default::default();
2141     /// assert_eq!(*x, 0);
2142     /// ```
2143     fn default() -> Arc<T> {
2144         Arc::new(Default::default())
2145     }
2146 }
2147
2148 #[stable(feature = "rust1", since = "1.0.0")]
2149 impl<T: ?Sized + Hash> Hash for Arc<T> {
2150     fn hash<H: Hasher>(&self, state: &mut H) {
2151         (**self).hash(state)
2152     }
2153 }
2154
2155 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
2156 impl<T> From<T> for Arc<T> {
2157     fn from(t: T) -> Self {
2158         Arc::new(t)
2159     }
2160 }
2161
2162 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2163 impl<T: Clone> From<&[T]> for Arc<[T]> {
2164     #[inline]
2165     fn from(v: &[T]) -> Arc<[T]> {
2166         <Self as ArcFromSlice<T>>::from_slice(v)
2167     }
2168 }
2169
2170 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2171 impl From<&str> for Arc<str> {
2172     #[inline]
2173     fn from(v: &str) -> Arc<str> {
2174         let arc = Arc::<[u8]>::from(v.as_bytes());
2175         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
2176     }
2177 }
2178
2179 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2180 impl From<String> for Arc<str> {
2181     #[inline]
2182     fn from(v: String) -> Arc<str> {
2183         Arc::from(&v[..])
2184     }
2185 }
2186
2187 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2188 impl<T: ?Sized> From<Box<T>> for Arc<T> {
2189     #[inline]
2190     fn from(v: Box<T>) -> Arc<T> {
2191         Arc::from_box(v)
2192     }
2193 }
2194
2195 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2196 impl<T> From<Vec<T>> for Arc<[T]> {
2197     #[inline]
2198     fn from(mut v: Vec<T>) -> Arc<[T]> {
2199         unsafe {
2200             let arc = Arc::copy_from_slice(&v);
2201
2202             // Allow the Vec to free its memory, but not destroy its contents
2203             v.set_len(0);
2204
2205             arc
2206         }
2207     }
2208 }
2209
2210 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2211 impl<'a, B> From<Cow<'a, B>> for Arc<B>
2212 where
2213     B: ToOwned + ?Sized,
2214     Arc<B>: From<&'a B> + From<B::Owned>,
2215 {
2216     #[inline]
2217     fn from(cow: Cow<'a, B>) -> Arc<B> {
2218         match cow {
2219             Cow::Borrowed(s) => Arc::from(s),
2220             Cow::Owned(s) => Arc::from(s),
2221         }
2222     }
2223 }
2224
2225 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2226 impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> {
2227     type Error = Arc<[T]>;
2228
2229     fn try_from(boxed_slice: Arc<[T]>) -> Result<Self, Self::Error> {
2230         if boxed_slice.len() == N {
2231             Ok(unsafe { Arc::from_raw(Arc::into_raw(boxed_slice) as *mut [T; N]) })
2232         } else {
2233             Err(boxed_slice)
2234         }
2235     }
2236 }
2237
2238 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2239 impl<T> iter::FromIterator<T> for Arc<[T]> {
2240     /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
2241     ///
2242     /// # Performance characteristics
2243     ///
2244     /// ## The general case
2245     ///
2246     /// In the general case, collecting into `Arc<[T]>` is done by first
2247     /// collecting into a `Vec<T>`. That is, when writing the following:
2248     ///
2249     /// ```rust
2250     /// # use std::sync::Arc;
2251     /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2252     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2253     /// ```
2254     ///
2255     /// this behaves as if we wrote:
2256     ///
2257     /// ```rust
2258     /// # use std::sync::Arc;
2259     /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2260     ///     .collect::<Vec<_>>() // The first set of allocations happens here.
2261     ///     .into(); // A second allocation for `Arc<[T]>` happens here.
2262     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2263     /// ```
2264     ///
2265     /// This will allocate as many times as needed for constructing the `Vec<T>`
2266     /// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
2267     ///
2268     /// ## Iterators of known length
2269     ///
2270     /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2271     /// a single allocation will be made for the `Arc<[T]>`. For example:
2272     ///
2273     /// ```rust
2274     /// # use std::sync::Arc;
2275     /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2276     /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2277     /// ```
2278     fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
2279         ToArcSlice::to_arc_slice(iter.into_iter())
2280     }
2281 }
2282
2283 /// Specialization trait used for collecting into `Arc<[T]>`.
2284 trait ToArcSlice<T>: Iterator<Item = T> + Sized {
2285     fn to_arc_slice(self) -> Arc<[T]>;
2286 }
2287
2288 impl<T, I: Iterator<Item = T>> ToArcSlice<T> for I {
2289     default fn to_arc_slice(self) -> Arc<[T]> {
2290         self.collect::<Vec<T>>().into()
2291     }
2292 }
2293
2294 impl<T, I: iter::TrustedLen<Item = T>> ToArcSlice<T> for I {
2295     fn to_arc_slice(self) -> Arc<[T]> {
2296         // This is the case for a `TrustedLen` iterator.
2297         let (low, high) = self.size_hint();
2298         if let Some(high) = high {
2299             debug_assert_eq!(
2300                 low,
2301                 high,
2302                 "TrustedLen iterator's size hint is not exact: {:?}",
2303                 (low, high)
2304             );
2305
2306             unsafe {
2307                 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2308                 Arc::from_iter_exact(self, low)
2309             }
2310         } else {
2311             // Fall back to normal implementation.
2312             self.collect::<Vec<T>>().into()
2313         }
2314     }
2315 }
2316
2317 #[stable(feature = "rust1", since = "1.0.0")]
2318 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2319     fn borrow(&self) -> &T {
2320         &**self
2321     }
2322 }
2323
2324 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2325 impl<T: ?Sized> AsRef<T> for Arc<T> {
2326     fn as_ref(&self) -> &T {
2327         &**self
2328     }
2329 }
2330
2331 #[stable(feature = "pin", since = "1.33.0")]
2332 impl<T: ?Sized> Unpin for Arc<T> {}
2333
2334 /// Get the offset within an `ArcInner` for
2335 /// a payload of type described by a pointer.
2336 ///
2337 /// # Safety
2338 ///
2339 /// This has the same safety requirements as `align_of_val_raw`. In effect:
2340 ///
2341 /// - This function is safe for any argument if `T` is sized, and
2342 /// - if `T` is unsized, the pointer must have appropriate pointer metadata
2343 ///   acquired from the real instance that you are getting this offset for.
2344 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2345     // Align the unsized value to the end of the `ArcInner`.
2346     // Because it is `?Sized`, it will always be the last field in memory.
2347     // Note: This is a detail of the current implementation of the compiler,
2348     // and is not a guaranteed language detail. Do not rely on it outside of std.
2349     unsafe { data_offset_align(align_of_val(&*ptr)) }
2350 }
2351
2352 #[inline]
2353 fn data_offset_align(align: usize) -> isize {
2354     let layout = Layout::new::<ArcInner<()>>();
2355     (layout.size() + layout.padding_needed_for(align)) as isize
2356 }