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