]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/sync.rs
Rollup merge of #75209 - Hirrolot:suggest-macro-imports, r=estebank
[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, AllocError, 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]: ../../std/mem/union.MaybeUninit.html#method.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]: ../../std/mem/union.MaybeUninit.html#method.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`]: ../../std/mem/union.MaybeUninit.html#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`]: ../../std/mem/union.MaybeUninit.html#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]>, AllocError>,
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
1514 /// Helper type to allow accessing the reference counts without
1515 /// making any assertions about the data field.
1516 struct WeakInner<'a> {
1517     weak: &'a atomic::AtomicUsize,
1518     strong: &'a atomic::AtomicUsize,
1519 }
1520
1521 impl<T: ?Sized> Weak<T> {
1522     /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1523     ///
1524     /// The pointer is valid only if there are some strong references. The pointer may be dangling,
1525     /// unaligned or even [`null`] otherwise.
1526     ///
1527     /// # Examples
1528     ///
1529     /// ```
1530     /// use std::sync::Arc;
1531     /// use std::ptr;
1532     ///
1533     /// let strong = Arc::new("hello".to_owned());
1534     /// let weak = Arc::downgrade(&strong);
1535     /// // Both point to the same object
1536     /// assert!(ptr::eq(&*strong, weak.as_ptr()));
1537     /// // The strong here keeps it alive, so we can still access the object.
1538     /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
1539     ///
1540     /// drop(strong);
1541     /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
1542     /// // undefined behaviour.
1543     /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
1544     /// ```
1545     ///
1546     /// [`null`]: core::ptr::null
1547     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1548     pub fn as_ptr(&self) -> *const T {
1549         let ptr: *mut ArcInner<T> = NonNull::as_ptr(self.ptr);
1550
1551         // SAFETY: we must offset the pointer manually, and said pointer may be
1552         // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call,
1553         // because we know that a pointer to unsized T was derived from a real
1554         // unsized T, as dangling weaks are only created for sized T. wrapping_offset
1555         // is used so that we can use the same code path for the non-dangling
1556         // unsized case and the potentially dangling sized case.
1557         unsafe {
1558             let offset = data_offset(ptr as *mut T);
1559             set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset))
1560         }
1561     }
1562
1563     /// Consumes the `Weak<T>` and turns it into a raw pointer.
1564     ///
1565     /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
1566     /// one weak reference (the weak count is not modified by this operation). It can be turned
1567     /// back into the `Weak<T>` with [`from_raw`].
1568     ///
1569     /// The same restrictions of accessing the target of the pointer as with
1570     /// [`as_ptr`] apply.
1571     ///
1572     /// # Examples
1573     ///
1574     /// ```
1575     /// use std::sync::{Arc, Weak};
1576     ///
1577     /// let strong = Arc::new("hello".to_owned());
1578     /// let weak = Arc::downgrade(&strong);
1579     /// let raw = weak.into_raw();
1580     ///
1581     /// assert_eq!(1, Arc::weak_count(&strong));
1582     /// assert_eq!("hello", unsafe { &*raw });
1583     ///
1584     /// drop(unsafe { Weak::from_raw(raw) });
1585     /// assert_eq!(0, Arc::weak_count(&strong));
1586     /// ```
1587     ///
1588     /// [`from_raw`]: Weak::from_raw
1589     /// [`as_ptr`]: Weak::as_ptr
1590     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1591     pub fn into_raw(self) -> *const T {
1592         let result = self.as_ptr();
1593         mem::forget(self);
1594         result
1595     }
1596
1597     /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1598     ///
1599     /// This can be used to safely get a strong reference (by calling [`upgrade`]
1600     /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1601     ///
1602     /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
1603     /// as these don't own anything; the method still works on them).
1604     ///
1605     /// # Safety
1606     ///
1607     /// The pointer must have originated from the [`into_raw`] and must still own its potential
1608     /// weak reference.
1609     ///
1610     /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
1611     /// takes ownership of one weak reference currently represented as a raw pointer (the weak
1612     /// count is not modified by this operation) and therefore it must be paired with a previous
1613     /// call to [`into_raw`].
1614     /// # Examples
1615     ///
1616     /// ```
1617     /// use std::sync::{Arc, Weak};
1618     ///
1619     /// let strong = Arc::new("hello".to_owned());
1620     ///
1621     /// let raw_1 = Arc::downgrade(&strong).into_raw();
1622     /// let raw_2 = Arc::downgrade(&strong).into_raw();
1623     ///
1624     /// assert_eq!(2, Arc::weak_count(&strong));
1625     ///
1626     /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1627     /// assert_eq!(1, Arc::weak_count(&strong));
1628     ///
1629     /// drop(strong);
1630     ///
1631     /// // Decrement the last weak count.
1632     /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1633     /// ```
1634     ///
1635     /// [`new`]: Weak::new
1636     /// [`into_raw`]: Weak::into_raw
1637     /// [`upgrade`]: Weak::upgrade
1638     /// [`forget`]: std::mem::forget
1639     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1640     pub unsafe fn from_raw(ptr: *const T) -> Self {
1641         // SAFETY: data_offset is safe to call, because this pointer originates from a Weak.
1642         // See Weak::as_ptr for context on how the input pointer is derived.
1643         let offset = unsafe { data_offset(ptr) };
1644
1645         // Reverse the offset to find the original ArcInner.
1646         // SAFETY: we use wrapping_offset here because the pointer may be dangling (but only if T: Sized)
1647         let ptr = unsafe {
1648             set_data_ptr(ptr as *mut ArcInner<T>, (ptr as *mut u8).wrapping_offset(-offset))
1649         };
1650
1651         // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
1652         unsafe { Weak { ptr: NonNull::new_unchecked(ptr) } }
1653     }
1654
1655     /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying
1656     /// dropping of the inner value if successful.
1657     ///
1658     /// Returns [`None`] if the inner value has since been dropped.
1659     ///
1660     /// # Examples
1661     ///
1662     /// ```
1663     /// use std::sync::Arc;
1664     ///
1665     /// let five = Arc::new(5);
1666     ///
1667     /// let weak_five = Arc::downgrade(&five);
1668     ///
1669     /// let strong_five: Option<Arc<_>> = weak_five.upgrade();
1670     /// assert!(strong_five.is_some());
1671     ///
1672     /// // Destroy all strong pointers.
1673     /// drop(strong_five);
1674     /// drop(five);
1675     ///
1676     /// assert!(weak_five.upgrade().is_none());
1677     /// ```
1678     #[stable(feature = "arc_weak", since = "1.4.0")]
1679     pub fn upgrade(&self) -> Option<Arc<T>> {
1680         // We use a CAS loop to increment the strong count instead of a
1681         // fetch_add as this function should never take the reference count
1682         // from zero to one.
1683         let inner = self.inner()?;
1684
1685         // Relaxed load because any write of 0 that we can observe
1686         // leaves the field in a permanently zero state (so a
1687         // "stale" read of 0 is fine), and any other value is
1688         // confirmed via the CAS below.
1689         let mut n = inner.strong.load(Relaxed);
1690
1691         loop {
1692             if n == 0 {
1693                 return None;
1694             }
1695
1696             // See comments in `Arc::clone` for why we do this (for `mem::forget`).
1697             if n > MAX_REFCOUNT {
1698                 abort();
1699             }
1700
1701             // Relaxed is fine for the failure case because we don't have any expectations about the new state.
1702             // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner
1703             // value can be initialized after `Weak` references have already been created. In that case, we
1704             // expect to observe the fully initialized value.
1705             match inner.strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed) {
1706                 Ok(_) => return Some(Arc::from_inner(self.ptr)), // null checked above
1707                 Err(old) => n = old,
1708             }
1709         }
1710     }
1711
1712     /// Gets the number of strong (`Arc`) pointers pointing to this allocation.
1713     ///
1714     /// If `self` was created using [`Weak::new`], this will return 0.
1715     #[stable(feature = "weak_counts", since = "1.41.0")]
1716     pub fn strong_count(&self) -> usize {
1717         if let Some(inner) = self.inner() { inner.strong.load(SeqCst) } else { 0 }
1718     }
1719
1720     /// Gets an approximation of the number of `Weak` pointers pointing to this
1721     /// allocation.
1722     ///
1723     /// If `self` was created using [`Weak::new`], or if there are no remaining
1724     /// strong pointers, this will return 0.
1725     ///
1726     /// # Accuracy
1727     ///
1728     /// Due to implementation details, the returned value can be off by 1 in
1729     /// either direction when other threads are manipulating any `Arc`s or
1730     /// `Weak`s pointing to the same allocation.
1731     #[stable(feature = "weak_counts", since = "1.41.0")]
1732     pub fn weak_count(&self) -> usize {
1733         self.inner()
1734             .map(|inner| {
1735                 let weak = inner.weak.load(SeqCst);
1736                 let strong = inner.strong.load(SeqCst);
1737                 if strong == 0 {
1738                     0
1739                 } else {
1740                     // Since we observed that there was at least one strong pointer
1741                     // after reading the weak count, we know that the implicit weak
1742                     // reference (present whenever any strong references are alive)
1743                     // was still around when we observed the weak count, and can
1744                     // therefore safely subtract it.
1745                     weak - 1
1746                 }
1747             })
1748             .unwrap_or(0)
1749     }
1750
1751     /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`,
1752     /// (i.e., when this `Weak` was created by `Weak::new`).
1753     #[inline]
1754     fn inner(&self) -> Option<WeakInner<'_>> {
1755         if is_dangling(self.ptr) {
1756             None
1757         } else {
1758             // We are careful to *not* create a reference covering the "data" field, as
1759             // the field may be mutated concurrently (for example, if the last `Arc`
1760             // is dropped, the data field will be dropped in-place).
1761             Some(unsafe {
1762                 let ptr = self.ptr.as_ptr();
1763                 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
1764             })
1765         }
1766     }
1767
1768     /// Returns `true` if the two `Weak`s point to the same allocation (similar to
1769     /// [`ptr::eq`]), or if both don't point to any allocation
1770     /// (because they were created with `Weak::new()`).
1771     ///
1772     /// # Notes
1773     ///
1774     /// Since this compares pointers it means that `Weak::new()` will equal each
1775     /// other, even though they don't point to any allocation.
1776     ///
1777     /// # Examples
1778     ///
1779     /// ```
1780     /// use std::sync::Arc;
1781     ///
1782     /// let first_rc = Arc::new(5);
1783     /// let first = Arc::downgrade(&first_rc);
1784     /// let second = Arc::downgrade(&first_rc);
1785     ///
1786     /// assert!(first.ptr_eq(&second));
1787     ///
1788     /// let third_rc = Arc::new(5);
1789     /// let third = Arc::downgrade(&third_rc);
1790     ///
1791     /// assert!(!first.ptr_eq(&third));
1792     /// ```
1793     ///
1794     /// Comparing `Weak::new`.
1795     ///
1796     /// ```
1797     /// use std::sync::{Arc, Weak};
1798     ///
1799     /// let first = Weak::new();
1800     /// let second = Weak::new();
1801     /// assert!(first.ptr_eq(&second));
1802     ///
1803     /// let third_rc = Arc::new(());
1804     /// let third = Arc::downgrade(&third_rc);
1805     /// assert!(!first.ptr_eq(&third));
1806     /// ```
1807     ///
1808     /// [`ptr::eq`]: core::ptr::eq
1809     #[inline]
1810     #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1811     pub fn ptr_eq(&self, other: &Self) -> bool {
1812         self.ptr.as_ptr() == other.ptr.as_ptr()
1813     }
1814 }
1815
1816 #[stable(feature = "arc_weak", since = "1.4.0")]
1817 impl<T: ?Sized> Clone for Weak<T> {
1818     /// Makes a clone of the `Weak` pointer that points to the same allocation.
1819     ///
1820     /// # Examples
1821     ///
1822     /// ```
1823     /// use std::sync::{Arc, Weak};
1824     ///
1825     /// let weak_five = Arc::downgrade(&Arc::new(5));
1826     ///
1827     /// let _ = Weak::clone(&weak_five);
1828     /// ```
1829     #[inline]
1830     fn clone(&self) -> Weak<T> {
1831         let inner = if let Some(inner) = self.inner() {
1832             inner
1833         } else {
1834             return Weak { ptr: self.ptr };
1835         };
1836         // See comments in Arc::clone() for why this is relaxed.  This can use a
1837         // fetch_add (ignoring the lock) because the weak count is only locked
1838         // where are *no other* weak pointers in existence. (So we can't be
1839         // running this code in that case).
1840         let old_size = inner.weak.fetch_add(1, Relaxed);
1841
1842         // See comments in Arc::clone() for why we do this (for mem::forget).
1843         if old_size > MAX_REFCOUNT {
1844             abort();
1845         }
1846
1847         Weak { ptr: self.ptr }
1848     }
1849 }
1850
1851 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1852 impl<T> Default for Weak<T> {
1853     /// Constructs a new `Weak<T>`, without allocating memory.
1854     /// Calling [`upgrade`] on the return value always
1855     /// gives [`None`].
1856     ///
1857     /// [`upgrade`]: Weak::upgrade
1858     ///
1859     /// # Examples
1860     ///
1861     /// ```
1862     /// use std::sync::Weak;
1863     ///
1864     /// let empty: Weak<i64> = Default::default();
1865     /// assert!(empty.upgrade().is_none());
1866     /// ```
1867     fn default() -> Weak<T> {
1868         Weak::new()
1869     }
1870 }
1871
1872 #[stable(feature = "arc_weak", since = "1.4.0")]
1873 impl<T: ?Sized> Drop for Weak<T> {
1874     /// Drops the `Weak` pointer.
1875     ///
1876     /// # Examples
1877     ///
1878     /// ```
1879     /// use std::sync::{Arc, Weak};
1880     ///
1881     /// struct Foo;
1882     ///
1883     /// impl Drop for Foo {
1884     ///     fn drop(&mut self) {
1885     ///         println!("dropped!");
1886     ///     }
1887     /// }
1888     ///
1889     /// let foo = Arc::new(Foo);
1890     /// let weak_foo = Arc::downgrade(&foo);
1891     /// let other_weak_foo = Weak::clone(&weak_foo);
1892     ///
1893     /// drop(weak_foo);   // Doesn't print anything
1894     /// drop(foo);        // Prints "dropped!"
1895     ///
1896     /// assert!(other_weak_foo.upgrade().is_none());
1897     /// ```
1898     fn drop(&mut self) {
1899         // If we find out that we were the last weak pointer, then its time to
1900         // deallocate the data entirely. See the discussion in Arc::drop() about
1901         // the memory orderings
1902         //
1903         // It's not necessary to check for the locked state here, because the
1904         // weak count can only be locked if there was precisely one weak ref,
1905         // meaning that drop could only subsequently run ON that remaining weak
1906         // ref, which can only happen after the lock is released.
1907         let inner = if let Some(inner) = self.inner() { inner } else { return };
1908
1909         if inner.weak.fetch_sub(1, Release) == 1 {
1910             acquire!(inner.weak);
1911             unsafe { Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())) }
1912         }
1913     }
1914 }
1915
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 trait ArcEqIdent<T: ?Sized + PartialEq> {
1918     fn eq(&self, other: &Arc<T>) -> bool;
1919     fn ne(&self, other: &Arc<T>) -> bool;
1920 }
1921
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<T: ?Sized + PartialEq> ArcEqIdent<T> for Arc<T> {
1924     #[inline]
1925     default fn eq(&self, other: &Arc<T>) -> bool {
1926         **self == **other
1927     }
1928     #[inline]
1929     default fn ne(&self, other: &Arc<T>) -> bool {
1930         **self != **other
1931     }
1932 }
1933
1934 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1935 /// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to
1936 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1937 /// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to
1938 /// the same value, than two `&T`s.
1939 ///
1940 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl<T: ?Sized + crate::rc::MarkerEq> ArcEqIdent<T> for Arc<T> {
1943     #[inline]
1944     fn eq(&self, other: &Arc<T>) -> bool {
1945         Arc::ptr_eq(self, other) || **self == **other
1946     }
1947
1948     #[inline]
1949     fn ne(&self, other: &Arc<T>) -> bool {
1950         !Arc::ptr_eq(self, other) && **self != **other
1951     }
1952 }
1953
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
1956     /// Equality for two `Arc`s.
1957     ///
1958     /// Two `Arc`s are equal if their inner values are equal, even if they are
1959     /// stored in different allocation.
1960     ///
1961     /// If `T` also implements `Eq` (implying reflexivity of equality),
1962     /// two `Arc`s that point to the same allocation are always equal.
1963     ///
1964     /// # Examples
1965     ///
1966     /// ```
1967     /// use std::sync::Arc;
1968     ///
1969     /// let five = Arc::new(5);
1970     ///
1971     /// assert!(five == Arc::new(5));
1972     /// ```
1973     #[inline]
1974     fn eq(&self, other: &Arc<T>) -> bool {
1975         ArcEqIdent::eq(self, other)
1976     }
1977
1978     /// Inequality for two `Arc`s.
1979     ///
1980     /// Two `Arc`s are unequal if their inner values are unequal.
1981     ///
1982     /// If `T` also implements `Eq` (implying reflexivity of equality),
1983     /// two `Arc`s that point to the same value are never unequal.
1984     ///
1985     /// # Examples
1986     ///
1987     /// ```
1988     /// use std::sync::Arc;
1989     ///
1990     /// let five = Arc::new(5);
1991     ///
1992     /// assert!(five != Arc::new(6));
1993     /// ```
1994     #[inline]
1995     fn ne(&self, other: &Arc<T>) -> bool {
1996         ArcEqIdent::ne(self, other)
1997     }
1998 }
1999
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
2002     /// Partial comparison for two `Arc`s.
2003     ///
2004     /// The two are compared by calling `partial_cmp()` on their inner values.
2005     ///
2006     /// # Examples
2007     ///
2008     /// ```
2009     /// use std::sync::Arc;
2010     /// use std::cmp::Ordering;
2011     ///
2012     /// let five = Arc::new(5);
2013     ///
2014     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
2015     /// ```
2016     fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
2017         (**self).partial_cmp(&**other)
2018     }
2019
2020     /// Less-than comparison for two `Arc`s.
2021     ///
2022     /// The two are compared by calling `<` on their inner values.
2023     ///
2024     /// # Examples
2025     ///
2026     /// ```
2027     /// use std::sync::Arc;
2028     ///
2029     /// let five = Arc::new(5);
2030     ///
2031     /// assert!(five < Arc::new(6));
2032     /// ```
2033     fn lt(&self, other: &Arc<T>) -> bool {
2034         *(*self) < *(*other)
2035     }
2036
2037     /// 'Less than or equal to' comparison for two `Arc`s.
2038     ///
2039     /// The two are compared by calling `<=` on their inner values.
2040     ///
2041     /// # Examples
2042     ///
2043     /// ```
2044     /// use std::sync::Arc;
2045     ///
2046     /// let five = Arc::new(5);
2047     ///
2048     /// assert!(five <= Arc::new(5));
2049     /// ```
2050     fn le(&self, other: &Arc<T>) -> bool {
2051         *(*self) <= *(*other)
2052     }
2053
2054     /// Greater-than comparison for two `Arc`s.
2055     ///
2056     /// The two are compared by calling `>` on their inner values.
2057     ///
2058     /// # Examples
2059     ///
2060     /// ```
2061     /// use std::sync::Arc;
2062     ///
2063     /// let five = Arc::new(5);
2064     ///
2065     /// assert!(five > Arc::new(4));
2066     /// ```
2067     fn gt(&self, other: &Arc<T>) -> bool {
2068         *(*self) > *(*other)
2069     }
2070
2071     /// 'Greater than or equal to' comparison for two `Arc`s.
2072     ///
2073     /// The two are compared by calling `>=` on their inner values.
2074     ///
2075     /// # Examples
2076     ///
2077     /// ```
2078     /// use std::sync::Arc;
2079     ///
2080     /// let five = Arc::new(5);
2081     ///
2082     /// assert!(five >= Arc::new(5));
2083     /// ```
2084     fn ge(&self, other: &Arc<T>) -> bool {
2085         *(*self) >= *(*other)
2086     }
2087 }
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 impl<T: ?Sized + Ord> Ord for Arc<T> {
2090     /// Comparison for two `Arc`s.
2091     ///
2092     /// The two are compared by calling `cmp()` on their inner values.
2093     ///
2094     /// # Examples
2095     ///
2096     /// ```
2097     /// use std::sync::Arc;
2098     /// use std::cmp::Ordering;
2099     ///
2100     /// let five = Arc::new(5);
2101     ///
2102     /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
2103     /// ```
2104     fn cmp(&self, other: &Arc<T>) -> Ordering {
2105         (**self).cmp(&**other)
2106     }
2107 }
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<T: ?Sized + Eq> Eq for Arc<T> {}
2110
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
2113     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114         fmt::Display::fmt(&**self, f)
2115     }
2116 }
2117
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
2120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2121         fmt::Debug::fmt(&**self, f)
2122     }
2123 }
2124
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl<T: ?Sized> fmt::Pointer for Arc<T> {
2127     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2128         fmt::Pointer::fmt(&(&**self as *const T), f)
2129     }
2130 }
2131
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl<T: Default> Default for Arc<T> {
2134     /// Creates a new `Arc<T>`, with the `Default` value for `T`.
2135     ///
2136     /// # Examples
2137     ///
2138     /// ```
2139     /// use std::sync::Arc;
2140     ///
2141     /// let x: Arc<i32> = Default::default();
2142     /// assert_eq!(*x, 0);
2143     /// ```
2144     fn default() -> Arc<T> {
2145         Arc::new(Default::default())
2146     }
2147 }
2148
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl<T: ?Sized + Hash> Hash for Arc<T> {
2151     fn hash<H: Hasher>(&self, state: &mut H) {
2152         (**self).hash(state)
2153     }
2154 }
2155
2156 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
2157 impl<T> From<T> for Arc<T> {
2158     fn from(t: T) -> Self {
2159         Arc::new(t)
2160     }
2161 }
2162
2163 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2164 impl<T: Clone> From<&[T]> for Arc<[T]> {
2165     #[inline]
2166     fn from(v: &[T]) -> Arc<[T]> {
2167         <Self as ArcFromSlice<T>>::from_slice(v)
2168     }
2169 }
2170
2171 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2172 impl From<&str> for Arc<str> {
2173     #[inline]
2174     fn from(v: &str) -> Arc<str> {
2175         let arc = Arc::<[u8]>::from(v.as_bytes());
2176         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) }
2177     }
2178 }
2179
2180 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2181 impl From<String> for Arc<str> {
2182     #[inline]
2183     fn from(v: String) -> Arc<str> {
2184         Arc::from(&v[..])
2185     }
2186 }
2187
2188 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2189 impl<T: ?Sized> From<Box<T>> for Arc<T> {
2190     #[inline]
2191     fn from(v: Box<T>) -> Arc<T> {
2192         Arc::from_box(v)
2193     }
2194 }
2195
2196 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2197 impl<T> From<Vec<T>> for Arc<[T]> {
2198     #[inline]
2199     fn from(mut v: Vec<T>) -> Arc<[T]> {
2200         unsafe {
2201             let arc = Arc::copy_from_slice(&v);
2202
2203             // Allow the Vec to free its memory, but not destroy its contents
2204             v.set_len(0);
2205
2206             arc
2207         }
2208     }
2209 }
2210
2211 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2212 impl<'a, B> From<Cow<'a, B>> for Arc<B>
2213 where
2214     B: ToOwned + ?Sized,
2215     Arc<B>: From<&'a B> + From<B::Owned>,
2216 {
2217     #[inline]
2218     fn from(cow: Cow<'a, B>) -> Arc<B> {
2219         match cow {
2220             Cow::Borrowed(s) => Arc::from(s),
2221             Cow::Owned(s) => Arc::from(s),
2222         }
2223     }
2224 }
2225
2226 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2227 impl<T, const N: usize> TryFrom<Arc<[T]>> for Arc<[T; N]> {
2228     type Error = Arc<[T]>;
2229
2230     fn try_from(boxed_slice: Arc<[T]>) -> Result<Self, Self::Error> {
2231         if boxed_slice.len() == N {
2232             Ok(unsafe { Arc::from_raw(Arc::into_raw(boxed_slice) as *mut [T; N]) })
2233         } else {
2234             Err(boxed_slice)
2235         }
2236     }
2237 }
2238
2239 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2240 impl<T> iter::FromIterator<T> for Arc<[T]> {
2241     /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
2242     ///
2243     /// # Performance characteristics
2244     ///
2245     /// ## The general case
2246     ///
2247     /// In the general case, collecting into `Arc<[T]>` is done by first
2248     /// collecting into a `Vec<T>`. That is, when writing the following:
2249     ///
2250     /// ```rust
2251     /// # use std::sync::Arc;
2252     /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2253     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2254     /// ```
2255     ///
2256     /// this behaves as if we wrote:
2257     ///
2258     /// ```rust
2259     /// # use std::sync::Arc;
2260     /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2261     ///     .collect::<Vec<_>>() // The first set of allocations happens here.
2262     ///     .into(); // A second allocation for `Arc<[T]>` happens here.
2263     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2264     /// ```
2265     ///
2266     /// This will allocate as many times as needed for constructing the `Vec<T>`
2267     /// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
2268     ///
2269     /// ## Iterators of known length
2270     ///
2271     /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2272     /// a single allocation will be made for the `Arc<[T]>`. For example:
2273     ///
2274     /// ```rust
2275     /// # use std::sync::Arc;
2276     /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2277     /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2278     /// ```
2279     fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
2280         ToArcSlice::to_arc_slice(iter.into_iter())
2281     }
2282 }
2283
2284 /// Specialization trait used for collecting into `Arc<[T]>`.
2285 trait ToArcSlice<T>: Iterator<Item = T> + Sized {
2286     fn to_arc_slice(self) -> Arc<[T]>;
2287 }
2288
2289 impl<T, I: Iterator<Item = T>> ToArcSlice<T> for I {
2290     default fn to_arc_slice(self) -> Arc<[T]> {
2291         self.collect::<Vec<T>>().into()
2292     }
2293 }
2294
2295 impl<T, I: iter::TrustedLen<Item = T>> ToArcSlice<T> for I {
2296     fn to_arc_slice(self) -> Arc<[T]> {
2297         // This is the case for a `TrustedLen` iterator.
2298         let (low, high) = self.size_hint();
2299         if let Some(high) = high {
2300             debug_assert_eq!(
2301                 low,
2302                 high,
2303                 "TrustedLen iterator's size hint is not exact: {:?}",
2304                 (low, high)
2305             );
2306
2307             unsafe {
2308                 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2309                 Arc::from_iter_exact(self, low)
2310             }
2311         } else {
2312             // Fall back to normal implementation.
2313             self.collect::<Vec<T>>().into()
2314         }
2315     }
2316 }
2317
2318 #[stable(feature = "rust1", since = "1.0.0")]
2319 impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
2320     fn borrow(&self) -> &T {
2321         &**self
2322     }
2323 }
2324
2325 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2326 impl<T: ?Sized> AsRef<T> for Arc<T> {
2327     fn as_ref(&self) -> &T {
2328         &**self
2329     }
2330 }
2331
2332 #[stable(feature = "pin", since = "1.33.0")]
2333 impl<T: ?Sized> Unpin for Arc<T> {}
2334
2335 /// Get the offset within an `ArcInner` for
2336 /// a payload of type described by a pointer.
2337 ///
2338 /// # Safety
2339 ///
2340 /// This has the same safety requirements as `align_of_val_raw`. In effect:
2341 ///
2342 /// - This function is safe for any argument if `T` is sized, and
2343 /// - if `T` is unsized, the pointer must have appropriate pointer metadata
2344 ///   acquired from the real instance that you are getting this offset for.
2345 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2346     // Align the unsized value to the end of the `ArcInner`.
2347     // Because it is `?Sized`, it will always be the last field in memory.
2348     // Note: This is a detail of the current implementation of the compiler,
2349     // and is not a guaranteed language detail. Do not rely on it outside of std.
2350     unsafe { data_offset_align(align_of_val(&*ptr)) }
2351 }
2352
2353 #[inline]
2354 fn data_offset_align(align: usize) -> isize {
2355     let layout = Layout::new::<ArcInner<()>>();
2356     (layout.size() + layout.padding_needed_for(align)) as isize
2357 }