]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
85aaf69f | 11 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 12 | |
c30ab7b3 | 13 | //! Thread-safe reference-counting pointers. |
1a4d82fc | 14 | //! |
c30ab7b3 | 15 | //! See the [`Arc<T>`][arc] documentation for more details. |
1a4d82fc | 16 | //! |
c30ab7b3 | 17 | //! [arc]: struct.Arc.html |
1a4d82fc | 18 | |
c34b1796 AL |
19 | use boxed::Box; |
20 | ||
e9174d1e | 21 | use core::sync::atomic; |
3157f602 | 22 | use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst}; |
e9174d1e | 23 | use core::borrow; |
85aaf69f | 24 | use core::fmt; |
c34b1796 | 25 | use core::cmp::Ordering; |
62682a34 | 26 | use core::mem::{align_of_val, size_of_val}; |
92a42be0 | 27 | use core::intrinsics::abort; |
1a4d82fc | 28 | use core::mem; |
9cc50fc6 | 29 | use core::mem::uninitialized; |
92a42be0 | 30 | use core::ops::Deref; |
92a42be0 | 31 | use core::ops::CoerceUnsized; |
b039eaaf | 32 | use core::ptr::{self, Shared}; |
62682a34 | 33 | use core::marker::Unsize; |
1a4d82fc | 34 | use core::hash::{Hash, Hasher}; |
3157f602 | 35 | use core::{isize, usize}; |
92a42be0 | 36 | use core::convert::From; |
1a4d82fc JJ |
37 | use heap::deallocate; |
38 | ||
c30ab7b3 SL |
39 | /// A soft limit on the amount of references that may be made to an `Arc`. |
40 | /// | |
41 | /// Going above this limit will abort your program (although not | |
42 | /// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references. | |
c1a9b12d SL |
43 | const MAX_REFCOUNT: usize = (isize::MAX) as usize; |
44 | ||
c30ab7b3 | 45 | /// A thread-safe reference-counting pointer. |
1a4d82fc | 46 | /// |
c30ab7b3 SL |
47 | /// The type `Arc<T>` provides shared ownership of a value of type `T`, |
48 | /// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces | |
49 | /// a new pointer to the same value in the heap. When the last `Arc` | |
50 | /// pointer to a given value is destroyed, the pointed-to value is | |
51 | /// also destroyed. | |
1a4d82fc | 52 | /// |
c30ab7b3 SL |
53 | /// Shared references in Rust disallow mutation by default, and `Arc` is no |
54 | /// exception. If you need to mutate through an `Arc`, use [`Mutex`][mutex], | |
55 | /// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types. | |
9e0c209e | 56 | /// |
7cac9316 XL |
57 | /// ## Thread Safety |
58 | /// | |
59 | /// Unlike [`Rc<T>`], `Arc<T>` uses atomic operations for its reference | |
60 | /// counting This means that it is thread-safe. The disadvantage is that | |
61 | /// atomic operations are more expensive than ordinary memory accesses. If you | |
62 | /// are not sharing reference-counted values between threads, consider using | |
63 | /// [`Rc<T>`] for lower overhead. [`Rc<T>`] is a safe default, because the | |
64 | /// compiler will catch any attempt to send an [`Rc<T>`] between threads. | |
65 | /// However, a library might choose `Arc<T>` in order to give library consumers | |
c30ab7b3 | 66 | /// more flexibility. |
1a4d82fc | 67 | /// |
7cac9316 XL |
68 | /// `Arc<T>` will implement [`Send`] and [`Sync`] as long as the `T` implements |
69 | /// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an | |
70 | /// `Arc<T>` to make it thread-safe? This may be a bit counter-intuitive at | |
71 | /// first: after all, isn't the point of `Arc<T>` thread safety? The key is | |
72 | /// this: `Arc<T>` makes it thread safe to have multiple ownership of the same | |
73 | /// data, but it doesn't add thread safety to its data. Consider | |
74 | /// `Arc<RefCell<T>>`. `RefCell<T>` isn't [`Sync`], and if `Arc<T>` was always | |
75 | /// [`Send`], `Arc<RefCell<T>>` would be as well. But then we'd have a problem: | |
76 | /// `RefCell<T>` is not thread safe; it keeps track of the borrowing count using | |
77 | /// non-atomic operations. | |
78 | /// | |
79 | /// In the end, this means that you may need to pair `Arc<T>` with some sort of | |
80 | /// `std::sync` type, usually `Mutex<T>`. | |
81 | /// | |
82 | /// ## Breaking cycles with `Weak` | |
83 | /// | |
c30ab7b3 | 84 | /// The [`downgrade`][downgrade] method can be used to create a non-owning |
32a655c1 SL |
85 | /// [`Weak`][weak] pointer. A [`Weak`][weak] pointer can be [`upgrade`][upgrade]d |
86 | /// to an `Arc`, but this will return [`None`] if the value has already been | |
87 | /// dropped. | |
c30ab7b3 SL |
88 | /// |
89 | /// A cycle between `Arc` pointers will never be deallocated. For this reason, | |
32a655c1 SL |
90 | /// [`Weak`][weak] is used to break cycles. For example, a tree could have |
91 | /// strong `Arc` pointers from parent nodes to children, and [`Weak`][weak] | |
92 | /// pointers from children back to their parents. | |
c30ab7b3 | 93 | /// |
7cac9316 XL |
94 | /// # Cloning references |
95 | /// | |
96 | /// Creating a new reference from an existing reference counted pointer is done using the | |
97 | /// `Clone` trait implemented for [`Arc<T>`][`arc`] and [`Weak<T>`][`weak`]. | |
98 | /// | |
99 | /// ``` | |
100 | /// use std::sync::Arc; | |
101 | /// let foo = Arc::new(vec![1.0, 2.0, 3.0]); | |
102 | /// // The two syntaxes below are equivalent. | |
103 | /// let a = foo.clone(); | |
104 | /// let b = Arc::clone(&foo); | |
105 | /// // a and b both point to the same memory location as foo. | |
106 | /// ``` | |
107 | /// | |
108 | /// The `Arc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly | |
109 | /// the meaning of the code. In the example above, this syntax makes it easier to see that | |
110 | /// this code is creating a new reference rather than copying the whole content of foo. | |
111 | /// | |
112 | /// ## `Deref` behavior | |
113 | /// | |
c30ab7b3 SL |
114 | /// `Arc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait), |
115 | /// so you can call `T`'s methods on a value of type `Arc<T>`. To avoid name | |
116 | /// clashes with `T`'s methods, the methods of `Arc<T>` itself are [associated | |
117 | /// functions][assoc], called using function-like syntax: | |
c34b1796 AL |
118 | /// |
119 | /// ``` | |
1a4d82fc | 120 | /// use std::sync::Arc; |
c30ab7b3 | 121 | /// let my_arc = Arc::new(()); |
1a4d82fc | 122 | /// |
c30ab7b3 SL |
123 | /// Arc::downgrade(&my_arc); |
124 | /// ``` | |
1a4d82fc | 125 | /// |
32a655c1 | 126 | /// [`Weak<T>`][weak] does not auto-dereference to `T`, because the value may have |
c30ab7b3 | 127 | /// already been destroyed. |
1a4d82fc | 128 | /// |
c30ab7b3 SL |
129 | /// [arc]: struct.Arc.html |
130 | /// [weak]: struct.Weak.html | |
7cac9316 | 131 | /// [`Rc<T>`]: ../../std/rc/struct.Rc.html |
c30ab7b3 SL |
132 | /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone |
133 | /// [mutex]: ../../std/sync/struct.Mutex.html | |
134 | /// [rwlock]: ../../std/sync/struct.RwLock.html | |
135 | /// [atomic]: ../../std/sync/atomic/index.html | |
32a655c1 | 136 | /// [`Send`]: ../../std/marker/trait.Send.html |
7cac9316 | 137 | /// [`Sync`]: ../../std/marker/trait.Sync.html |
c30ab7b3 SL |
138 | /// [deref]: ../../std/ops/trait.Deref.html |
139 | /// [downgrade]: struct.Arc.html#method.downgrade | |
140 | /// [upgrade]: struct.Weak.html#method.upgrade | |
32a655c1 | 141 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
cc61c64b | 142 | /// [assoc]: ../../book/first-edition/method-syntax.html#associated-functions |
1a4d82fc | 143 | /// |
c30ab7b3 | 144 | /// # Examples |
5bcae85e | 145 | /// |
c30ab7b3 SL |
146 | /// Sharing some immutable data between threads: |
147 | /// | |
148 | // Note that we **do not** run these tests here. The windows builders get super | |
149 | // unhappy if a thread outlives the main thread and then exits at the same time | |
150 | // (something deadlocks) so we just avoid this entirely by not running these | |
151 | // tests. | |
5bcae85e | 152 | /// ```no_run |
c30ab7b3 | 153 | /// use std::sync::Arc; |
5bcae85e SL |
154 | /// use std::thread; |
155 | /// | |
c30ab7b3 | 156 | /// let five = Arc::new(5); |
5bcae85e SL |
157 | /// |
158 | /// for _ in 0..10 { | |
7cac9316 | 159 | /// let five = Arc::clone(&five); |
5bcae85e SL |
160 | /// |
161 | /// thread::spawn(move || { | |
c30ab7b3 SL |
162 | /// println!("{:?}", five); |
163 | /// }); | |
164 | /// } | |
165 | /// ``` | |
5bcae85e | 166 | /// |
32a655c1 SL |
167 | /// Sharing a mutable [`AtomicUsize`]: |
168 | /// | |
169 | /// [`AtomicUsize`]: ../../std/sync/atomic/struct.AtomicUsize.html | |
5bcae85e | 170 | /// |
c30ab7b3 SL |
171 | /// ```no_run |
172 | /// use std::sync::Arc; | |
173 | /// use std::sync::atomic::{AtomicUsize, Ordering}; | |
174 | /// use std::thread; | |
175 | /// | |
176 | /// let val = Arc::new(AtomicUsize::new(5)); | |
177 | /// | |
178 | /// for _ in 0..10 { | |
7cac9316 | 179 | /// let val = Arc::clone(&val); |
c30ab7b3 SL |
180 | /// |
181 | /// thread::spawn(move || { | |
182 | /// let v = val.fetch_add(1, Ordering::SeqCst); | |
183 | /// println!("{:?}", v); | |
5bcae85e SL |
184 | /// }); |
185 | /// } | |
186 | /// ``` | |
c30ab7b3 SL |
187 | /// |
188 | /// See the [`rc` documentation][rc_examples] for more examples of reference | |
189 | /// counting in general. | |
190 | /// | |
191 | /// [rc_examples]: ../../std/rc/index.html#examples | |
85aaf69f | 192 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 193 | pub struct Arc<T: ?Sized> { |
54a0048b | 194 | ptr: Shared<ArcInner<T>>, |
1a4d82fc JJ |
195 | } |
196 | ||
92a42be0 SL |
197 | #[stable(feature = "rust1", since = "1.0.0")] |
198 | unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {} | |
199 | #[stable(feature = "rust1", since = "1.0.0")] | |
200 | unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {} | |
1a4d82fc | 201 | |
92a42be0 | 202 | #[unstable(feature = "coerce_unsized", issue = "27732")] |
62682a34 | 203 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {} |
1a4d82fc | 204 | |
cc61c64b XL |
205 | /// `Weak` is a version of [`Arc`] that holds a non-owning reference to the |
206 | /// managed value. The value is accessed by calling [`upgrade`] on the `Weak` | |
207 | /// pointer, which returns an [`Option`]`<`[`Arc`]`<T>>`. | |
1a4d82fc | 208 | /// |
cc61c64b XL |
209 | /// Since a `Weak` reference does not count towards ownership, it will not |
210 | /// prevent the inner value from being dropped, and `Weak` itself makes no | |
211 | /// guarantees about the value still being present and may return [`None`] | |
212 | /// when [`upgrade`]d. | |
5bcae85e | 213 | /// |
cc61c64b XL |
214 | /// A `Weak` pointer is useful for keeping a temporary reference to the value |
215 | /// within [`Arc`] without extending its lifetime. It is also used to prevent | |
216 | /// circular references between [`Arc`] pointers, since mutual owning references | |
217 | /// would never allow either [`Arc`] to be dropped. For example, a tree could | |
218 | /// have strong [`Arc`] pointers from parent nodes to children, and `Weak` | |
219 | /// pointers from children back to their parents. | |
5bcae85e | 220 | /// |
cc61c64b | 221 | /// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`]. |
c30ab7b3 | 222 | /// |
cc61c64b XL |
223 | /// [`Arc`]: struct.Arc.html |
224 | /// [`Arc::downgrade`]: struct.Arc.html#method.downgrade | |
225 | /// [`upgrade`]: struct.Weak.html#method.upgrade | |
226 | /// [`Option`]: ../../std/option/enum.Option.html | |
227 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
e9174d1e | 228 | #[stable(feature = "arc_weak", since = "1.4.0")] |
62682a34 | 229 | pub struct Weak<T: ?Sized> { |
54a0048b | 230 | ptr: Shared<ArcInner<T>>, |
1a4d82fc JJ |
231 | } |
232 | ||
7453a54e | 233 | #[stable(feature = "arc_weak", since = "1.4.0")] |
92a42be0 | 234 | unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {} |
7453a54e | 235 | #[stable(feature = "arc_weak", since = "1.4.0")] |
92a42be0 | 236 | unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {} |
1a4d82fc | 237 | |
92a42be0 | 238 | #[unstable(feature = "coerce_unsized", issue = "27732")] |
c1a9b12d SL |
239 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {} |
240 | ||
7453a54e | 241 | #[stable(feature = "arc_weak", since = "1.4.0")] |
62682a34 | 242 | impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> { |
c34b1796 AL |
243 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
244 | write!(f, "(Weak)") | |
245 | } | |
246 | } | |
247 | ||
62682a34 | 248 | struct ArcInner<T: ?Sized> { |
85aaf69f | 249 | strong: atomic::AtomicUsize, |
c1a9b12d SL |
250 | |
251 | // the value usize::MAX acts as a sentinel for temporarily "locking" the | |
252 | // ability to upgrade weak pointers or downgrade strong ones; this is used | |
e9174d1e | 253 | // to avoid races in `make_mut` and `get_mut`. |
85aaf69f | 254 | weak: atomic::AtomicUsize, |
c1a9b12d | 255 | |
1a4d82fc JJ |
256 | data: T, |
257 | } | |
258 | ||
62682a34 SL |
259 | unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {} |
260 | unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {} | |
1a4d82fc JJ |
261 | |
262 | impl<T> Arc<T> { | |
263 | /// Constructs a new `Arc<T>`. | |
264 | /// | |
265 | /// # Examples | |
266 | /// | |
267 | /// ``` | |
268 | /// use std::sync::Arc; | |
269 | /// | |
85aaf69f | 270 | /// let five = Arc::new(5); |
1a4d82fc JJ |
271 | /// ``` |
272 | #[inline] | |
85aaf69f | 273 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
274 | pub fn new(data: T) -> Arc<T> { |
275 | // Start the weak pointer count as 1 which is the weak pointer that's | |
276 | // held by all the strong pointers (kinda), see std/rc.rs for more info | |
c34b1796 | 277 | let x: Box<_> = box ArcInner { |
85aaf69f SL |
278 | strong: atomic::AtomicUsize::new(1), |
279 | weak: atomic::AtomicUsize::new(1), | |
1a4d82fc JJ |
280 | data: data, |
281 | }; | |
54a0048b | 282 | Arc { ptr: unsafe { Shared::new(Box::into_raw(x)) } } |
e9174d1e SL |
283 | } |
284 | ||
c30ab7b3 | 285 | /// Returns the contained value, if the `Arc` has exactly one strong reference. |
e9174d1e | 286 | /// |
c30ab7b3 SL |
287 | /// Otherwise, an [`Err`][result] is returned with the same `Arc` that was |
288 | /// passed in. | |
e9174d1e | 289 | /// |
54a0048b SL |
290 | /// This will succeed even if there are outstanding weak references. |
291 | /// | |
c30ab7b3 SL |
292 | /// [result]: ../../std/result/enum.Result.html |
293 | /// | |
e9174d1e SL |
294 | /// # Examples |
295 | /// | |
296 | /// ``` | |
297 | /// use std::sync::Arc; | |
298 | /// | |
299 | /// let x = Arc::new(3); | |
300 | /// assert_eq!(Arc::try_unwrap(x), Ok(3)); | |
301 | /// | |
302 | /// let x = Arc::new(4); | |
7cac9316 | 303 | /// let _y = Arc::clone(&x); |
c30ab7b3 | 304 | /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4); |
e9174d1e SL |
305 | /// ``` |
306 | #[inline] | |
307 | #[stable(feature = "arc_unique", since = "1.4.0")] | |
308 | pub fn try_unwrap(this: Self) -> Result<T, Self> { | |
309 | // See `drop` for why all these atomics are like this | |
54a0048b | 310 | if this.inner().strong.compare_exchange(1, 0, Release, Relaxed).is_err() { |
92a42be0 | 311 | return Err(this); |
b039eaaf | 312 | } |
e9174d1e SL |
313 | |
314 | atomic::fence(Acquire); | |
315 | ||
316 | unsafe { | |
7cac9316 | 317 | let elem = ptr::read(&this.ptr.as_ref().data); |
e9174d1e SL |
318 | |
319 | // Make a weak pointer to clean up the implicit strong-weak reference | |
54a0048b | 320 | let _weak = Weak { ptr: this.ptr }; |
e9174d1e SL |
321 | mem::forget(this); |
322 | ||
323 | Ok(elem) | |
324 | } | |
1a4d82fc | 325 | } |
476ff2be SL |
326 | |
327 | /// Consumes the `Arc`, returning the wrapped pointer. | |
328 | /// | |
329 | /// To avoid a memory leak the pointer must be converted back to an `Arc` using | |
330 | /// [`Arc::from_raw`][from_raw]. | |
331 | /// | |
332 | /// [from_raw]: struct.Arc.html#method.from_raw | |
333 | /// | |
334 | /// # Examples | |
335 | /// | |
336 | /// ``` | |
476ff2be SL |
337 | /// use std::sync::Arc; |
338 | /// | |
339 | /// let x = Arc::new(10); | |
340 | /// let x_ptr = Arc::into_raw(x); | |
341 | /// assert_eq!(unsafe { *x_ptr }, 10); | |
342 | /// ``` | |
8bb4bdeb XL |
343 | #[stable(feature = "rc_raw", since = "1.17.0")] |
344 | pub fn into_raw(this: Self) -> *const T { | |
7cac9316 | 345 | let ptr: *const T = &*this; |
476ff2be SL |
346 | mem::forget(this); |
347 | ptr | |
348 | } | |
349 | ||
350 | /// Constructs an `Arc` from a raw pointer. | |
351 | /// | |
352 | /// The raw pointer must have been previously returned by a call to a | |
353 | /// [`Arc::into_raw`][into_raw]. | |
354 | /// | |
355 | /// This function is unsafe because improper use may lead to memory problems. For example, a | |
356 | /// double-free may occur if the function is called twice on the same raw pointer. | |
357 | /// | |
358 | /// [into_raw]: struct.Arc.html#method.into_raw | |
359 | /// | |
360 | /// # Examples | |
361 | /// | |
362 | /// ``` | |
476ff2be SL |
363 | /// use std::sync::Arc; |
364 | /// | |
365 | /// let x = Arc::new(10); | |
366 | /// let x_ptr = Arc::into_raw(x); | |
367 | /// | |
368 | /// unsafe { | |
369 | /// // Convert back to an `Arc` to prevent leak. | |
370 | /// let x = Arc::from_raw(x_ptr); | |
371 | /// assert_eq!(*x, 10); | |
372 | /// | |
373 | /// // Further calls to `Arc::from_raw(x_ptr)` would be memory unsafe. | |
374 | /// } | |
375 | /// | |
376 | /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! | |
377 | /// ``` | |
8bb4bdeb XL |
378 | #[stable(feature = "rc_raw", since = "1.17.0")] |
379 | pub unsafe fn from_raw(ptr: *const T) -> Self { | |
476ff2be SL |
380 | // To find the corresponding pointer to the `ArcInner` we need to subtract the offset of the |
381 | // `data` field from the pointer. | |
8bb4bdeb XL |
382 | let ptr = (ptr as *const u8).offset(-offset_of!(ArcInner<T>, data)); |
383 | Arc { | |
7cac9316 | 384 | ptr: Shared::new(ptr as *mut u8 as *mut _), |
8bb4bdeb | 385 | } |
476ff2be | 386 | } |
62682a34 | 387 | } |
1a4d82fc | 388 | |
62682a34 | 389 | impl<T: ?Sized> Arc<T> { |
c30ab7b3 SL |
390 | /// Creates a new [`Weak`][weak] pointer to this value. |
391 | /// | |
392 | /// [weak]: struct.Weak.html | |
1a4d82fc JJ |
393 | /// |
394 | /// # Examples | |
395 | /// | |
396 | /// ``` | |
397 | /// use std::sync::Arc; | |
398 | /// | |
85aaf69f | 399 | /// let five = Arc::new(5); |
1a4d82fc | 400 | /// |
e9174d1e | 401 | /// let weak_five = Arc::downgrade(&five); |
1a4d82fc | 402 | /// ``` |
e9174d1e SL |
403 | #[stable(feature = "arc_weak", since = "1.4.0")] |
404 | pub fn downgrade(this: &Self) -> Weak<T> { | |
54a0048b SL |
405 | // This Relaxed is OK because we're checking the value in the CAS |
406 | // below. | |
407 | let mut cur = this.inner().weak.load(Relaxed); | |
c1a9b12d | 408 | |
54a0048b | 409 | loop { |
c1a9b12d | 410 | // check if the weak counter is currently "locked"; if so, spin. |
b039eaaf | 411 | if cur == usize::MAX { |
54a0048b | 412 | cur = this.inner().weak.load(Relaxed); |
92a42be0 | 413 | continue; |
b039eaaf | 414 | } |
c1a9b12d SL |
415 | |
416 | // NOTE: this code currently ignores the possibility of overflow | |
417 | // into usize::MAX; in general both Rc and Arc need to be adjusted | |
418 | // to deal with overflow. | |
419 | ||
420 | // Unlike with Clone(), we need this to be an Acquire read to | |
421 | // synchronize with the write coming from `is_unique`, so that the | |
422 | // events prior to that write happen before this read. | |
54a0048b SL |
423 | match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) { |
424 | Ok(_) => return Weak { ptr: this.ptr }, | |
425 | Err(old) => cur = old, | |
c1a9b12d SL |
426 | } |
427 | } | |
1a4d82fc | 428 | } |
1a4d82fc | 429 | |
c30ab7b3 SL |
430 | /// Gets the number of [`Weak`][weak] pointers to this value. |
431 | /// | |
c30ab7b3 SL |
432 | /// [weak]: struct.Weak.html |
433 | /// | |
476ff2be SL |
434 | /// # Safety |
435 | /// | |
436 | /// This method by itself is safe, but using it correctly requires extra care. | |
437 | /// Another thread can change the weak count at any time, | |
438 | /// including potentially between calling this method and acting on the result. | |
439 | /// | |
c30ab7b3 SL |
440 | /// # Examples |
441 | /// | |
442 | /// ``` | |
c30ab7b3 SL |
443 | /// use std::sync::Arc; |
444 | /// | |
445 | /// let five = Arc::new(5); | |
446 | /// let _weak_five = Arc::downgrade(&five); | |
447 | /// | |
448 | /// // This assertion is deterministic because we haven't shared | |
449 | /// // the `Arc` or `Weak` between threads. | |
450 | /// assert_eq!(1, Arc::weak_count(&five)); | |
451 | /// ``` | |
62682a34 | 452 | #[inline] |
476ff2be | 453 | #[stable(feature = "arc_counts", since = "1.15.0")] |
e9174d1e | 454 | pub fn weak_count(this: &Self) -> usize { |
62682a34 SL |
455 | this.inner().weak.load(SeqCst) - 1 |
456 | } | |
457 | ||
c30ab7b3 SL |
458 | /// Gets the number of strong (`Arc`) pointers to this value. |
459 | /// | |
476ff2be SL |
460 | /// # Safety |
461 | /// | |
462 | /// This method by itself is safe, but using it correctly requires extra care. | |
463 | /// Another thread can change the strong count at any time, | |
464 | /// including potentially between calling this method and acting on the result. | |
c30ab7b3 SL |
465 | /// |
466 | /// # Examples | |
467 | /// | |
468 | /// ``` | |
c30ab7b3 SL |
469 | /// use std::sync::Arc; |
470 | /// | |
471 | /// let five = Arc::new(5); | |
7cac9316 | 472 | /// let _also_five = Arc::clone(&five); |
c30ab7b3 SL |
473 | /// |
474 | /// // This assertion is deterministic because we haven't shared | |
475 | /// // the `Arc` between threads. | |
476 | /// assert_eq!(2, Arc::strong_count(&five)); | |
477 | /// ``` | |
62682a34 | 478 | #[inline] |
476ff2be | 479 | #[stable(feature = "arc_counts", since = "1.15.0")] |
e9174d1e | 480 | pub fn strong_count(this: &Self) -> usize { |
62682a34 SL |
481 | this.inner().strong.load(SeqCst) |
482 | } | |
483 | ||
1a4d82fc JJ |
484 | #[inline] |
485 | fn inner(&self) -> &ArcInner<T> { | |
c34b1796 AL |
486 | // This unsafety is ok because while this arc is alive we're guaranteed |
487 | // that the inner pointer is valid. Furthermore, we know that the | |
488 | // `ArcInner` structure itself is `Sync` because the inner data is | |
489 | // `Sync` as well, so we're ok loaning out an immutable pointer to these | |
490 | // contents. | |
7cac9316 | 491 | unsafe { self.ptr.as_ref() } |
1a4d82fc | 492 | } |
c34b1796 AL |
493 | |
494 | // Non-inlined part of `drop`. | |
495 | #[inline(never)] | |
496 | unsafe fn drop_slow(&mut self) { | |
7cac9316 | 497 | let ptr = self.ptr.as_ptr(); |
c34b1796 AL |
498 | |
499 | // Destroy the data at this time, even though we may not free the box | |
500 | // allocation itself (there may still be weak pointers lying around). | |
7cac9316 | 501 | ptr::drop_in_place(&mut self.ptr.as_mut().data); |
c34b1796 AL |
502 | |
503 | if self.inner().weak.fetch_sub(1, Release) == 1 { | |
504 | atomic::fence(Acquire); | |
62682a34 | 505 | deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) |
c34b1796 AL |
506 | } |
507 | } | |
9e0c209e SL |
508 | |
509 | #[inline] | |
8bb4bdeb | 510 | #[stable(feature = "ptr_eq", since = "1.17.0")] |
c30ab7b3 SL |
511 | /// Returns true if the two `Arc`s point to the same value (not |
512 | /// just values that compare as equal). | |
9e0c209e SL |
513 | /// |
514 | /// # Examples | |
515 | /// | |
516 | /// ``` | |
9e0c209e SL |
517 | /// use std::sync::Arc; |
518 | /// | |
519 | /// let five = Arc::new(5); | |
7cac9316 | 520 | /// let same_five = Arc::clone(&five); |
9e0c209e SL |
521 | /// let other_five = Arc::new(5); |
522 | /// | |
523 | /// assert!(Arc::ptr_eq(&five, &same_five)); | |
524 | /// assert!(!Arc::ptr_eq(&five, &other_five)); | |
525 | /// ``` | |
526 | pub fn ptr_eq(this: &Self, other: &Self) -> bool { | |
7cac9316 | 527 | this.ptr.as_ptr() == other.ptr.as_ptr() |
9e0c209e | 528 | } |
1a4d82fc JJ |
529 | } |
530 | ||
85aaf69f | 531 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 532 | impl<T: ?Sized> Clone for Arc<T> { |
c30ab7b3 | 533 | /// Makes a clone of the `Arc` pointer. |
1a4d82fc | 534 | /// |
c30ab7b3 SL |
535 | /// This creates another pointer to the same inner value, increasing the |
536 | /// strong reference count. | |
1a4d82fc JJ |
537 | /// |
538 | /// # Examples | |
539 | /// | |
540 | /// ``` | |
541 | /// use std::sync::Arc; | |
542 | /// | |
85aaf69f | 543 | /// let five = Arc::new(5); |
1a4d82fc | 544 | /// |
7cac9316 | 545 | /// Arc::clone(&five); |
1a4d82fc JJ |
546 | /// ``` |
547 | #[inline] | |
548 | fn clone(&self) -> Arc<T> { | |
c34b1796 AL |
549 | // Using a relaxed ordering is alright here, as knowledge of the |
550 | // original reference prevents other threads from erroneously deleting | |
551 | // the object. | |
1a4d82fc | 552 | // |
c34b1796 AL |
553 | // As explained in the [Boost documentation][1], Increasing the |
554 | // reference counter can always be done with memory_order_relaxed: New | |
555 | // references to an object can only be formed from an existing | |
556 | // reference, and passing an existing reference from one thread to | |
557 | // another must already provide any required synchronization. | |
1a4d82fc JJ |
558 | // |
559 | // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) | |
c1a9b12d SL |
560 | let old_size = self.inner().strong.fetch_add(1, Relaxed); |
561 | ||
562 | // However we need to guard against massive refcounts in case someone | |
563 | // is `mem::forget`ing Arcs. If we don't do this the count can overflow | |
564 | // and users will use-after free. We racily saturate to `isize::MAX` on | |
565 | // the assumption that there aren't ~2 billion threads incrementing | |
566 | // the reference count at once. This branch will never be taken in | |
567 | // any realistic program. | |
568 | // | |
569 | // We abort because such a program is incredibly degenerate, and we | |
570 | // don't care to support it. | |
571 | if old_size > MAX_REFCOUNT { | |
b039eaaf SL |
572 | unsafe { |
573 | abort(); | |
574 | } | |
c1a9b12d SL |
575 | } |
576 | ||
54a0048b | 577 | Arc { ptr: self.ptr } |
1a4d82fc JJ |
578 | } |
579 | } | |
580 | ||
85aaf69f | 581 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 582 | impl<T: ?Sized> Deref for Arc<T> { |
1a4d82fc JJ |
583 | type Target = T; |
584 | ||
585 | #[inline] | |
586 | fn deref(&self) -> &T { | |
587 | &self.inner().data | |
588 | } | |
589 | } | |
590 | ||
c34b1796 | 591 | impl<T: Clone> Arc<T> { |
c30ab7b3 SL |
592 | /// Makes a mutable reference into the given `Arc`. |
593 | /// | |
594 | /// If there are other `Arc` or [`Weak`][weak] pointers to the same value, | |
595 | /// then `make_mut` will invoke [`clone`][clone] on the inner value to | |
596 | /// ensure unique ownership. This is also referred to as clone-on-write. | |
1a4d82fc | 597 | /// |
c30ab7b3 SL |
598 | /// See also [`get_mut`][get_mut], which will fail rather than cloning. |
599 | /// | |
600 | /// [weak]: struct.Weak.html | |
601 | /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone | |
602 | /// [get_mut]: struct.Arc.html#method.get_mut | |
62682a34 | 603 | /// |
1a4d82fc JJ |
604 | /// # Examples |
605 | /// | |
606 | /// ``` | |
607 | /// use std::sync::Arc; | |
608 | /// | |
e9174d1e SL |
609 | /// let mut data = Arc::new(5); |
610 | /// | |
611 | /// *Arc::make_mut(&mut data) += 1; // Won't clone anything | |
7cac9316 | 612 | /// let mut other_data = Arc::clone(&data); // Won't clone inner data |
e9174d1e SL |
613 | /// *Arc::make_mut(&mut data) += 1; // Clones inner data |
614 | /// *Arc::make_mut(&mut data) += 1; // Won't clone anything | |
615 | /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything | |
616 | /// | |
c30ab7b3 | 617 | /// // Now `data` and `other_data` point to different values. |
e9174d1e SL |
618 | /// assert_eq!(*data, 8); |
619 | /// assert_eq!(*other_data, 12); | |
1a4d82fc JJ |
620 | /// ``` |
621 | #[inline] | |
e9174d1e SL |
622 | #[stable(feature = "arc_unique", since = "1.4.0")] |
623 | pub fn make_mut(this: &mut Self) -> &mut T { | |
c1a9b12d SL |
624 | // Note that we hold both a strong reference and a weak reference. |
625 | // Thus, releasing our strong reference only will not, by itself, cause | |
626 | // the memory to be deallocated. | |
62682a34 | 627 | // |
c1a9b12d SL |
628 | // Use Acquire to ensure that we see any writes to `weak` that happen |
629 | // before release writes (i.e., decrements) to `strong`. Since we hold a | |
630 | // weak count, there's no chance the ArcInner itself could be | |
631 | // deallocated. | |
54a0048b | 632 | if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() { |
9cc50fc6 | 633 | // Another strong pointer exists; clone |
c1a9b12d SL |
634 | *this = Arc::new((**this).clone()); |
635 | } else if this.inner().weak.load(Relaxed) != 1 { | |
636 | // Relaxed suffices in the above because this is fundamentally an | |
637 | // optimization: we are always racing with weak pointers being | |
638 | // dropped. Worst case, we end up allocated a new Arc unnecessarily. | |
639 | ||
640 | // We removed the last strong ref, but there are additional weak | |
641 | // refs remaining. We'll move the contents to a new Arc, and | |
642 | // invalidate the other weak refs. | |
643 | ||
644 | // Note that it is not possible for the read of `weak` to yield | |
645 | // usize::MAX (i.e., locked), since the weak count can only be | |
646 | // locked by a thread with a strong reference. | |
647 | ||
648 | // Materialize our own implicit weak pointer, so that it can clean | |
649 | // up the ArcInner as needed. | |
54a0048b | 650 | let weak = Weak { ptr: this.ptr }; |
c1a9b12d SL |
651 | |
652 | // mark the data itself as already deallocated | |
653 | unsafe { | |
654 | // there is no data race in the implicit write caused by `read` | |
655 | // here (due to zeroing) because data is no longer accessed by | |
656 | // other threads (due to there being no more strong refs at this | |
657 | // point). | |
7cac9316 | 658 | let mut swap = Arc::new(ptr::read(&weak.ptr.as_ref().data)); |
c1a9b12d SL |
659 | mem::swap(this, &mut swap); |
660 | mem::forget(swap); | |
661 | } | |
662 | } else { | |
663 | // We were the sole reference of either kind; bump back up the | |
664 | // strong ref count. | |
665 | this.inner().strong.store(1, Release); | |
1a4d82fc | 666 | } |
c1a9b12d | 667 | |
9346a6ac | 668 | // As with `get_mut()`, the unsafety is ok because our reference was |
c34b1796 | 669 | // either unique to begin with, or became one upon cloning the contents. |
c1a9b12d | 670 | unsafe { |
7cac9316 | 671 | &mut this.ptr.as_mut().data |
c1a9b12d | 672 | } |
1a4d82fc JJ |
673 | } |
674 | } | |
675 | ||
c1a9b12d | 676 | impl<T: ?Sized> Arc<T> { |
c30ab7b3 SL |
677 | /// Returns a mutable reference to the inner value, if there are |
678 | /// no other `Arc` or [`Weak`][weak] pointers to the same value. | |
679 | /// | |
680 | /// Returns [`None`][option] otherwise, because it is not safe to | |
681 | /// mutate a shared value. | |
682 | /// | |
683 | /// See also [`make_mut`][make_mut], which will [`clone`][clone] | |
684 | /// the inner value when it's shared. | |
685 | /// | |
686 | /// [weak]: struct.Weak.html | |
687 | /// [option]: ../../std/option/enum.Option.html | |
688 | /// [make_mut]: struct.Arc.html#method.make_mut | |
689 | /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone | |
c1a9b12d SL |
690 | /// |
691 | /// # Examples | |
692 | /// | |
693 | /// ``` | |
e9174d1e | 694 | /// use std::sync::Arc; |
c1a9b12d SL |
695 | /// |
696 | /// let mut x = Arc::new(3); | |
697 | /// *Arc::get_mut(&mut x).unwrap() = 4; | |
698 | /// assert_eq!(*x, 4); | |
699 | /// | |
7cac9316 | 700 | /// let _y = Arc::clone(&x); |
c1a9b12d | 701 | /// assert!(Arc::get_mut(&mut x).is_none()); |
c1a9b12d SL |
702 | /// ``` |
703 | #[inline] | |
e9174d1e SL |
704 | #[stable(feature = "arc_unique", since = "1.4.0")] |
705 | pub fn get_mut(this: &mut Self) -> Option<&mut T> { | |
c1a9b12d SL |
706 | if this.is_unique() { |
707 | // This unsafety is ok because we're guaranteed that the pointer | |
708 | // returned is the *only* pointer that will ever be returned to T. Our | |
709 | // reference count is guaranteed to be 1 at this point, and we required | |
710 | // the Arc itself to be `mut`, so we're returning the only possible | |
711 | // reference to the inner data. | |
712 | unsafe { | |
7cac9316 | 713 | Some(&mut this.ptr.as_mut().data) |
c1a9b12d SL |
714 | } |
715 | } else { | |
716 | None | |
717 | } | |
718 | } | |
719 | ||
720 | /// Determine whether this is the unique reference (including weak refs) to | |
721 | /// the underlying data. | |
722 | /// | |
723 | /// Note that this requires locking the weak ref count. | |
724 | fn is_unique(&mut self) -> bool { | |
725 | // lock the weak pointer count if we appear to be the sole weak pointer | |
726 | // holder. | |
727 | // | |
728 | // The acquire label here ensures a happens-before relationship with any | |
729 | // writes to `strong` prior to decrements of the `weak` count (via drop, | |
730 | // which uses Release). | |
54a0048b | 731 | if self.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() { |
c1a9b12d SL |
732 | // Due to the previous acquire read, this will observe any writes to |
733 | // `strong` that were due to upgrading weak pointers; only strong | |
734 | // clones remain, which require that the strong count is > 1 anyway. | |
735 | let unique = self.inner().strong.load(Relaxed) == 1; | |
736 | ||
737 | // The release write here synchronizes with a read in `downgrade`, | |
738 | // effectively preventing the above read of `strong` from happening | |
739 | // after the write. | |
740 | self.inner().weak.store(1, Release); // release the lock | |
741 | unique | |
742 | } else { | |
743 | false | |
744 | } | |
745 | } | |
746 | } | |
747 | ||
85aaf69f | 748 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 749 | unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc<T> { |
c30ab7b3 | 750 | /// Drops the `Arc`. |
1a4d82fc | 751 | /// |
c34b1796 | 752 | /// This will decrement the strong reference count. If the strong reference |
c30ab7b3 SL |
753 | /// count reaches zero then the only other references (if any) are |
754 | /// [`Weak`][weak], so we `drop` the inner value. | |
755 | /// | |
756 | /// [weak]: struct.Weak.html | |
1a4d82fc JJ |
757 | /// |
758 | /// # Examples | |
759 | /// | |
760 | /// ``` | |
761 | /// use std::sync::Arc; | |
762 | /// | |
c30ab7b3 | 763 | /// struct Foo; |
1a4d82fc | 764 | /// |
c30ab7b3 SL |
765 | /// impl Drop for Foo { |
766 | /// fn drop(&mut self) { | |
767 | /// println!("dropped!"); | |
768 | /// } | |
1a4d82fc | 769 | /// } |
1a4d82fc | 770 | /// |
c30ab7b3 | 771 | /// let foo = Arc::new(Foo); |
7cac9316 | 772 | /// let foo2 = Arc::clone(&foo); |
1a4d82fc | 773 | /// |
c30ab7b3 SL |
774 | /// drop(foo); // Doesn't print anything |
775 | /// drop(foo2); // Prints "dropped!" | |
1a4d82fc | 776 | /// ``` |
c34b1796 | 777 | #[inline] |
1a4d82fc | 778 | fn drop(&mut self) { |
c34b1796 AL |
779 | // Because `fetch_sub` is already atomic, we do not need to synchronize |
780 | // with other threads unless we are going to delete the object. This | |
781 | // same logic applies to the below `fetch_sub` to the `weak` count. | |
b039eaaf | 782 | if self.inner().strong.fetch_sub(1, Release) != 1 { |
92a42be0 | 783 | return; |
b039eaaf | 784 | } |
1a4d82fc | 785 | |
c34b1796 AL |
786 | // This fence is needed to prevent reordering of use of the data and |
787 | // deletion of the data. Because it is marked `Release`, the decreasing | |
788 | // of the reference count synchronizes with this `Acquire` fence. This | |
789 | // means that use of the data happens before decreasing the reference | |
790 | // count, which happens before this fence, which happens before the | |
791 | // deletion of the data. | |
1a4d82fc JJ |
792 | // |
793 | // As explained in the [Boost documentation][1], | |
794 | // | |
c34b1796 AL |
795 | // > It is important to enforce any possible access to the object in one |
796 | // > thread (through an existing reference) to *happen before* deleting | |
797 | // > the object in a different thread. This is achieved by a "release" | |
798 | // > operation after dropping a reference (any access to the object | |
799 | // > through this reference must obviously happened before), and an | |
800 | // > "acquire" operation before deleting the object. | |
1a4d82fc | 801 | // |
7cac9316 XL |
802 | // In particular, while the contents of an Arc are usually immutable, it's |
803 | // possible to have interior writes to something like a Mutex<T>. Since a | |
804 | // Mutex is not acquired when it is deleted, we can't rely on its | |
805 | // synchronization logic to make writes in thread A visible to a destructor | |
806 | // running in thread B. | |
807 | // | |
808 | // Also note that the Acquire fence here could probably be replaced with an | |
809 | // Acquire load, which could improve performance in highly-contended | |
810 | // situations. See [2]. | |
811 | // | |
1a4d82fc | 812 | // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) |
7cac9316 | 813 | // [2]: (https://github.com/rust-lang/rust/pull/41714) |
1a4d82fc JJ |
814 | atomic::fence(Acquire); |
815 | ||
c34b1796 | 816 | unsafe { |
b039eaaf | 817 | self.drop_slow(); |
1a4d82fc JJ |
818 | } |
819 | } | |
820 | } | |
821 | ||
a7813a04 | 822 | impl<T> Weak<T> { |
cc61c64b XL |
823 | /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing |
824 | /// it. Calling [`upgrade`] on the return value always gives [`None`]. | |
c30ab7b3 | 825 | /// |
cc61c64b XL |
826 | /// [`upgrade`]: struct.Weak.html#method.upgrade |
827 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
a7813a04 XL |
828 | /// |
829 | /// # Examples | |
830 | /// | |
831 | /// ``` | |
832 | /// use std::sync::Weak; | |
833 | /// | |
834 | /// let empty: Weak<i64> = Weak::new(); | |
c30ab7b3 | 835 | /// assert!(empty.upgrade().is_none()); |
a7813a04 XL |
836 | /// ``` |
837 | #[stable(feature = "downgraded_weak", since = "1.10.0")] | |
838 | pub fn new() -> Weak<T> { | |
839 | unsafe { | |
3157f602 XL |
840 | Weak { |
841 | ptr: Shared::new(Box::into_raw(box ArcInner { | |
842 | strong: atomic::AtomicUsize::new(0), | |
843 | weak: atomic::AtomicUsize::new(1), | |
844 | data: uninitialized(), | |
845 | })), | |
846 | } | |
a7813a04 XL |
847 | } |
848 | } | |
849 | } | |
850 | ||
62682a34 | 851 | impl<T: ?Sized> Weak<T> { |
cc61c64b XL |
852 | /// Attempts to upgrade the `Weak` pointer to an [`Arc`], extending |
853 | /// the lifetime of the value if successful. | |
1a4d82fc | 854 | /// |
cc61c64b | 855 | /// Returns [`None`] if the value has since been dropped. |
1a4d82fc | 856 | /// |
cc61c64b XL |
857 | /// [`Arc`]: struct.Arc.html |
858 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
1a4d82fc JJ |
859 | /// |
860 | /// # Examples | |
861 | /// | |
862 | /// ``` | |
863 | /// use std::sync::Arc; | |
864 | /// | |
85aaf69f | 865 | /// let five = Arc::new(5); |
1a4d82fc | 866 | /// |
e9174d1e | 867 | /// let weak_five = Arc::downgrade(&five); |
1a4d82fc JJ |
868 | /// |
869 | /// let strong_five: Option<Arc<_>> = weak_five.upgrade(); | |
c30ab7b3 SL |
870 | /// assert!(strong_five.is_some()); |
871 | /// | |
872 | /// // Destroy all strong pointers. | |
873 | /// drop(strong_five); | |
874 | /// drop(five); | |
875 | /// | |
876 | /// assert!(weak_five.upgrade().is_none()); | |
1a4d82fc | 877 | /// ``` |
e9174d1e | 878 | #[stable(feature = "arc_weak", since = "1.4.0")] |
1a4d82fc | 879 | pub fn upgrade(&self) -> Option<Arc<T>> { |
c34b1796 | 880 | // We use a CAS loop to increment the strong count instead of a |
9346a6ac | 881 | // fetch_add because once the count hits 0 it must never be above 0. |
1a4d82fc | 882 | let inner = self.inner(); |
54a0048b SL |
883 | |
884 | // Relaxed load because any write of 0 that we can observe | |
885 | // leaves the field in a permanently zero state (so a | |
886 | // "stale" read of 0 is fine), and any other value is | |
887 | // confirmed via the CAS below. | |
888 | let mut n = inner.strong.load(Relaxed); | |
889 | ||
1a4d82fc | 890 | loop { |
b039eaaf | 891 | if n == 0 { |
92a42be0 SL |
892 | return None; |
893 | } | |
894 | ||
895 | // See comments in `Arc::clone` for why we do this (for `mem::forget`). | |
896 | if n > MAX_REFCOUNT { | |
3157f602 XL |
897 | unsafe { |
898 | abort(); | |
899 | } | |
b039eaaf | 900 | } |
c1a9b12d SL |
901 | |
902 | // Relaxed is valid for the same reason it is on Arc's Clone impl | |
54a0048b SL |
903 | match inner.strong.compare_exchange_weak(n, n + 1, Relaxed, Relaxed) { |
904 | Ok(_) => return Some(Arc { ptr: self.ptr }), | |
905 | Err(old) => n = old, | |
b039eaaf | 906 | } |
1a4d82fc JJ |
907 | } |
908 | } | |
909 | ||
910 | #[inline] | |
911 | fn inner(&self) -> &ArcInner<T> { | |
912 | // See comments above for why this is "safe" | |
7cac9316 | 913 | unsafe { self.ptr.as_ref() } |
1a4d82fc JJ |
914 | } |
915 | } | |
916 | ||
e9174d1e | 917 | #[stable(feature = "arc_weak", since = "1.4.0")] |
62682a34 | 918 | impl<T: ?Sized> Clone for Weak<T> { |
cc61c64b | 919 | /// Makes a clone of the `Weak` pointer that points to the same value. |
1a4d82fc JJ |
920 | /// |
921 | /// # Examples | |
922 | /// | |
923 | /// ``` | |
7cac9316 | 924 | /// use std::sync::{Arc, Weak}; |
1a4d82fc | 925 | /// |
e9174d1e | 926 | /// let weak_five = Arc::downgrade(&Arc::new(5)); |
1a4d82fc | 927 | /// |
7cac9316 | 928 | /// Weak::clone(&weak_five); |
1a4d82fc JJ |
929 | /// ``` |
930 | #[inline] | |
931 | fn clone(&self) -> Weak<T> { | |
c1a9b12d SL |
932 | // See comments in Arc::clone() for why this is relaxed. This can use a |
933 | // fetch_add (ignoring the lock) because the weak count is only locked | |
934 | // where are *no other* weak pointers in existence. (So we can't be | |
935 | // running this code in that case). | |
936 | let old_size = self.inner().weak.fetch_add(1, Relaxed); | |
937 | ||
938 | // See comments in Arc::clone() for why we do this (for mem::forget). | |
939 | if old_size > MAX_REFCOUNT { | |
b039eaaf SL |
940 | unsafe { |
941 | abort(); | |
942 | } | |
c1a9b12d SL |
943 | } |
944 | ||
54a0048b | 945 | return Weak { ptr: self.ptr }; |
1a4d82fc JJ |
946 | } |
947 | } | |
948 | ||
a7813a04 XL |
949 | #[stable(feature = "downgraded_weak", since = "1.10.0")] |
950 | impl<T> Default for Weak<T> { | |
cc61c64b XL |
951 | /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing |
952 | /// it. Calling [`upgrade`] on the return value always gives [`None`]. | |
c30ab7b3 | 953 | /// |
cc61c64b XL |
954 | /// [`upgrade`]: struct.Weak.html#method.upgrade |
955 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
c30ab7b3 SL |
956 | /// |
957 | /// # Examples | |
958 | /// | |
959 | /// ``` | |
960 | /// use std::sync::Weak; | |
961 | /// | |
962 | /// let empty: Weak<i64> = Default::default(); | |
963 | /// assert!(empty.upgrade().is_none()); | |
964 | /// ``` | |
a7813a04 XL |
965 | fn default() -> Weak<T> { |
966 | Weak::new() | |
967 | } | |
968 | } | |
969 | ||
7453a54e | 970 | #[stable(feature = "arc_weak", since = "1.4.0")] |
62682a34 | 971 | impl<T: ?Sized> Drop for Weak<T> { |
c30ab7b3 | 972 | /// Drops the `Weak` pointer. |
1a4d82fc | 973 | /// |
1a4d82fc JJ |
974 | /// # Examples |
975 | /// | |
976 | /// ``` | |
7cac9316 | 977 | /// use std::sync::{Arc, Weak}; |
1a4d82fc | 978 | /// |
c30ab7b3 | 979 | /// struct Foo; |
1a4d82fc | 980 | /// |
c30ab7b3 SL |
981 | /// impl Drop for Foo { |
982 | /// fn drop(&mut self) { | |
983 | /// println!("dropped!"); | |
984 | /// } | |
1a4d82fc | 985 | /// } |
1a4d82fc | 986 | /// |
c30ab7b3 SL |
987 | /// let foo = Arc::new(Foo); |
988 | /// let weak_foo = Arc::downgrade(&foo); | |
7cac9316 | 989 | /// let other_weak_foo = Weak::clone(&weak_foo); |
1a4d82fc | 990 | /// |
c30ab7b3 SL |
991 | /// drop(weak_foo); // Doesn't print anything |
992 | /// drop(foo); // Prints "dropped!" | |
993 | /// | |
994 | /// assert!(other_weak_foo.upgrade().is_none()); | |
1a4d82fc JJ |
995 | /// ``` |
996 | fn drop(&mut self) { | |
7cac9316 | 997 | let ptr = self.ptr.as_ptr(); |
1a4d82fc | 998 | |
c34b1796 AL |
999 | // If we find out that we were the last weak pointer, then its time to |
1000 | // deallocate the data entirely. See the discussion in Arc::drop() about | |
1001 | // the memory orderings | |
c1a9b12d SL |
1002 | // |
1003 | // It's not necessary to check for the locked state here, because the | |
1004 | // weak count can only be locked if there was precisely one weak ref, | |
1005 | // meaning that drop could only subsequently run ON that remaining weak | |
1006 | // ref, which can only happen after the lock is released. | |
1a4d82fc JJ |
1007 | if self.inner().weak.fetch_sub(1, Release) == 1 { |
1008 | atomic::fence(Acquire); | |
b039eaaf | 1009 | unsafe { deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr)) } |
1a4d82fc JJ |
1010 | } |
1011 | } | |
1012 | } | |
1013 | ||
85aaf69f | 1014 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1015 | impl<T: ?Sized + PartialEq> PartialEq for Arc<T> { |
c30ab7b3 | 1016 | /// Equality for two `Arc`s. |
1a4d82fc | 1017 | /// |
c30ab7b3 | 1018 | /// Two `Arc`s are equal if their inner values are equal. |
1a4d82fc JJ |
1019 | /// |
1020 | /// # Examples | |
1021 | /// | |
1022 | /// ``` | |
1023 | /// use std::sync::Arc; | |
1024 | /// | |
85aaf69f | 1025 | /// let five = Arc::new(5); |
1a4d82fc | 1026 | /// |
c30ab7b3 | 1027 | /// assert!(five == Arc::new(5)); |
1a4d82fc | 1028 | /// ``` |
b039eaaf SL |
1029 | fn eq(&self, other: &Arc<T>) -> bool { |
1030 | *(*self) == *(*other) | |
1031 | } | |
1a4d82fc | 1032 | |
c30ab7b3 | 1033 | /// Inequality for two `Arc`s. |
1a4d82fc | 1034 | /// |
c30ab7b3 | 1035 | /// Two `Arc`s are unequal if their inner values are unequal. |
1a4d82fc JJ |
1036 | /// |
1037 | /// # Examples | |
1038 | /// | |
1039 | /// ``` | |
1040 | /// use std::sync::Arc; | |
1041 | /// | |
85aaf69f | 1042 | /// let five = Arc::new(5); |
1a4d82fc | 1043 | /// |
c30ab7b3 | 1044 | /// assert!(five != Arc::new(6)); |
1a4d82fc | 1045 | /// ``` |
b039eaaf SL |
1046 | fn ne(&self, other: &Arc<T>) -> bool { |
1047 | *(*self) != *(*other) | |
1048 | } | |
1a4d82fc | 1049 | } |
85aaf69f | 1050 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1051 | impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> { |
c30ab7b3 | 1052 | /// Partial comparison for two `Arc`s. |
1a4d82fc JJ |
1053 | /// |
1054 | /// The two are compared by calling `partial_cmp()` on their inner values. | |
1055 | /// | |
1056 | /// # Examples | |
1057 | /// | |
1058 | /// ``` | |
1059 | /// use std::sync::Arc; | |
c30ab7b3 | 1060 | /// use std::cmp::Ordering; |
1a4d82fc | 1061 | /// |
85aaf69f | 1062 | /// let five = Arc::new(5); |
1a4d82fc | 1063 | /// |
c30ab7b3 | 1064 | /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); |
1a4d82fc JJ |
1065 | /// ``` |
1066 | fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> { | |
1067 | (**self).partial_cmp(&**other) | |
1068 | } | |
1069 | ||
c30ab7b3 | 1070 | /// Less-than comparison for two `Arc`s. |
1a4d82fc JJ |
1071 | /// |
1072 | /// The two are compared by calling `<` on their inner values. | |
1073 | /// | |
1074 | /// # Examples | |
1075 | /// | |
1076 | /// ``` | |
1077 | /// use std::sync::Arc; | |
1078 | /// | |
85aaf69f | 1079 | /// let five = Arc::new(5); |
1a4d82fc | 1080 | /// |
c30ab7b3 | 1081 | /// assert!(five < Arc::new(6)); |
1a4d82fc | 1082 | /// ``` |
b039eaaf SL |
1083 | fn lt(&self, other: &Arc<T>) -> bool { |
1084 | *(*self) < *(*other) | |
1085 | } | |
1a4d82fc | 1086 | |
c30ab7b3 | 1087 | /// 'Less than or equal to' comparison for two `Arc`s. |
1a4d82fc JJ |
1088 | /// |
1089 | /// The two are compared by calling `<=` on their inner values. | |
1090 | /// | |
1091 | /// # Examples | |
1092 | /// | |
1093 | /// ``` | |
1094 | /// use std::sync::Arc; | |
1095 | /// | |
85aaf69f | 1096 | /// let five = Arc::new(5); |
1a4d82fc | 1097 | /// |
c30ab7b3 | 1098 | /// assert!(five <= Arc::new(5)); |
1a4d82fc | 1099 | /// ``` |
b039eaaf SL |
1100 | fn le(&self, other: &Arc<T>) -> bool { |
1101 | *(*self) <= *(*other) | |
1102 | } | |
1a4d82fc | 1103 | |
c30ab7b3 | 1104 | /// Greater-than comparison for two `Arc`s. |
1a4d82fc JJ |
1105 | /// |
1106 | /// The two are compared by calling `>` on their inner values. | |
1107 | /// | |
1108 | /// # Examples | |
1109 | /// | |
1110 | /// ``` | |
1111 | /// use std::sync::Arc; | |
1112 | /// | |
85aaf69f | 1113 | /// let five = Arc::new(5); |
1a4d82fc | 1114 | /// |
c30ab7b3 | 1115 | /// assert!(five > Arc::new(4)); |
1a4d82fc | 1116 | /// ``` |
b039eaaf SL |
1117 | fn gt(&self, other: &Arc<T>) -> bool { |
1118 | *(*self) > *(*other) | |
1119 | } | |
1a4d82fc | 1120 | |
c30ab7b3 | 1121 | /// 'Greater than or equal to' comparison for two `Arc`s. |
1a4d82fc JJ |
1122 | /// |
1123 | /// The two are compared by calling `>=` on their inner values. | |
1124 | /// | |
1125 | /// # Examples | |
1126 | /// | |
1127 | /// ``` | |
1128 | /// use std::sync::Arc; | |
1129 | /// | |
85aaf69f | 1130 | /// let five = Arc::new(5); |
1a4d82fc | 1131 | /// |
c30ab7b3 | 1132 | /// assert!(five >= Arc::new(5)); |
1a4d82fc | 1133 | /// ``` |
b039eaaf SL |
1134 | fn ge(&self, other: &Arc<T>) -> bool { |
1135 | *(*self) >= *(*other) | |
1136 | } | |
1a4d82fc | 1137 | } |
85aaf69f | 1138 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1139 | impl<T: ?Sized + Ord> Ord for Arc<T> { |
c30ab7b3 SL |
1140 | /// Comparison for two `Arc`s. |
1141 | /// | |
1142 | /// The two are compared by calling `cmp()` on their inner values. | |
1143 | /// | |
1144 | /// # Examples | |
1145 | /// | |
1146 | /// ``` | |
1147 | /// use std::sync::Arc; | |
1148 | /// use std::cmp::Ordering; | |
1149 | /// | |
1150 | /// let five = Arc::new(5); | |
1151 | /// | |
1152 | /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6))); | |
1153 | /// ``` | |
b039eaaf SL |
1154 | fn cmp(&self, other: &Arc<T>) -> Ordering { |
1155 | (**self).cmp(&**other) | |
1156 | } | |
1a4d82fc | 1157 | } |
85aaf69f | 1158 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1159 | impl<T: ?Sized + Eq> Eq for Arc<T> {} |
1a4d82fc | 1160 | |
85aaf69f | 1161 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1162 | impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> { |
1a4d82fc | 1163 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
85aaf69f | 1164 | fmt::Display::fmt(&**self, f) |
1a4d82fc JJ |
1165 | } |
1166 | } | |
1167 | ||
85aaf69f | 1168 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1169 | impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> { |
1a4d82fc | 1170 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
85aaf69f | 1171 | fmt::Debug::fmt(&**self, f) |
1a4d82fc JJ |
1172 | } |
1173 | } | |
1174 | ||
9346a6ac | 1175 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 1176 | impl<T: ?Sized> fmt::Pointer for Arc<T> { |
9346a6ac | 1177 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
7cac9316 | 1178 | fmt::Pointer::fmt(&self.ptr, f) |
9346a6ac AL |
1179 | } |
1180 | } | |
1181 | ||
85aaf69f | 1182 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 1183 | impl<T: Default> Default for Arc<T> { |
c30ab7b3 SL |
1184 | /// Creates a new `Arc<T>`, with the `Default` value for `T`. |
1185 | /// | |
1186 | /// # Examples | |
1187 | /// | |
1188 | /// ``` | |
1189 | /// use std::sync::Arc; | |
1190 | /// | |
1191 | /// let x: Arc<i32> = Default::default(); | |
1192 | /// assert_eq!(*x, 0); | |
1193 | /// ``` | |
b039eaaf SL |
1194 | fn default() -> Arc<T> { |
1195 | Arc::new(Default::default()) | |
1196 | } | |
1a4d82fc JJ |
1197 | } |
1198 | ||
85aaf69f | 1199 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1200 | impl<T: ?Sized + Hash> Hash for Arc<T> { |
85aaf69f SL |
1201 | fn hash<H: Hasher>(&self, state: &mut H) { |
1202 | (**self).hash(state) | |
1203 | } | |
1204 | } | |
1a4d82fc | 1205 | |
92a42be0 SL |
1206 | #[stable(feature = "from_for_ptrs", since = "1.6.0")] |
1207 | impl<T> From<T> for Arc<T> { | |
1208 | fn from(t: T) -> Self { | |
1209 | Arc::new(t) | |
1210 | } | |
1211 | } | |
1212 | ||
1a4d82fc | 1213 | #[cfg(test)] |
1a4d82fc JJ |
1214 | mod tests { |
1215 | use std::clone::Clone; | |
1216 | use std::sync::mpsc::channel; | |
1217 | use std::mem::drop; | |
1218 | use std::ops::Drop; | |
1219 | use std::option::Option; | |
3157f602 | 1220 | use std::option::Option::{None, Some}; |
1a4d82fc JJ |
1221 | use std::sync::atomic; |
1222 | use std::sync::atomic::Ordering::{Acquire, SeqCst}; | |
85aaf69f | 1223 | use std::thread; |
1a4d82fc | 1224 | use std::vec::Vec; |
e9174d1e | 1225 | use super::{Arc, Weak}; |
1a4d82fc | 1226 | use std::sync::Mutex; |
92a42be0 | 1227 | use std::convert::From; |
1a4d82fc | 1228 | |
85aaf69f | 1229 | struct Canary(*mut atomic::AtomicUsize); |
1a4d82fc | 1230 | |
92a42be0 | 1231 | impl Drop for Canary { |
1a4d82fc JJ |
1232 | fn drop(&mut self) { |
1233 | unsafe { | |
1234 | match *self { | |
1235 | Canary(c) => { | |
1236 | (*c).fetch_add(1, SeqCst); | |
1237 | } | |
1238 | } | |
1239 | } | |
1240 | } | |
1241 | } | |
1242 | ||
1243 | #[test] | |
c30ab7b3 | 1244 | #[cfg_attr(target_os = "emscripten", ignore)] |
1a4d82fc | 1245 | fn manually_share_arc() { |
92a42be0 | 1246 | let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; |
1a4d82fc JJ |
1247 | let arc_v = Arc::new(v); |
1248 | ||
1249 | let (tx, rx) = channel(); | |
1250 | ||
85aaf69f SL |
1251 | let _t = thread::spawn(move || { |
1252 | let arc_v: Arc<Vec<i32>> = rx.recv().unwrap(); | |
1a4d82fc JJ |
1253 | assert_eq!((*arc_v)[3], 4); |
1254 | }); | |
1255 | ||
1256 | tx.send(arc_v.clone()).unwrap(); | |
1257 | ||
1258 | assert_eq!((*arc_v)[2], 3); | |
1259 | assert_eq!((*arc_v)[4], 5); | |
1260 | } | |
1261 | ||
c34b1796 | 1262 | #[test] |
9346a6ac | 1263 | fn test_arc_get_mut() { |
e9174d1e SL |
1264 | let mut x = Arc::new(3); |
1265 | *Arc::get_mut(&mut x).unwrap() = 4; | |
1266 | assert_eq!(*x, 4); | |
1267 | let y = x.clone(); | |
1268 | assert!(Arc::get_mut(&mut x).is_none()); | |
1269 | drop(y); | |
1270 | assert!(Arc::get_mut(&mut x).is_some()); | |
1271 | let _w = Arc::downgrade(&x); | |
1272 | assert!(Arc::get_mut(&mut x).is_none()); | |
c34b1796 AL |
1273 | } |
1274 | ||
1a4d82fc | 1275 | #[test] |
e9174d1e SL |
1276 | fn try_unwrap() { |
1277 | let x = Arc::new(3); | |
1278 | assert_eq!(Arc::try_unwrap(x), Ok(3)); | |
1279 | let x = Arc::new(4); | |
1280 | let _y = x.clone(); | |
1281 | assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4))); | |
1282 | let x = Arc::new(5); | |
1283 | let _w = Arc::downgrade(&x); | |
1284 | assert_eq!(Arc::try_unwrap(x), Ok(5)); | |
1285 | } | |
1286 | ||
476ff2be SL |
1287 | #[test] |
1288 | fn into_from_raw() { | |
1289 | let x = Arc::new(box "hello"); | |
1290 | let y = x.clone(); | |
1291 | ||
1292 | let x_ptr = Arc::into_raw(x); | |
1293 | drop(y); | |
1294 | unsafe { | |
1295 | assert_eq!(**x_ptr, "hello"); | |
1296 | ||
1297 | let x = Arc::from_raw(x_ptr); | |
1298 | assert_eq!(**x, "hello"); | |
1299 | ||
1300 | assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello")); | |
1301 | } | |
1302 | } | |
1303 | ||
e9174d1e SL |
1304 | #[test] |
1305 | fn test_cowarc_clone_make_mut() { | |
1306 | let mut cow0 = Arc::new(75); | |
1307 | let mut cow1 = cow0.clone(); | |
1308 | let mut cow2 = cow1.clone(); | |
1309 | ||
1310 | assert!(75 == *Arc::make_mut(&mut cow0)); | |
1311 | assert!(75 == *Arc::make_mut(&mut cow1)); | |
1312 | assert!(75 == *Arc::make_mut(&mut cow2)); | |
1313 | ||
1314 | *Arc::make_mut(&mut cow0) += 1; | |
1315 | *Arc::make_mut(&mut cow1) += 2; | |
1316 | *Arc::make_mut(&mut cow2) += 3; | |
1317 | ||
1318 | assert!(76 == *cow0); | |
1319 | assert!(77 == *cow1); | |
1320 | assert!(78 == *cow2); | |
1321 | ||
1322 | // none should point to the same backing memory | |
1323 | assert!(*cow0 != *cow1); | |
1324 | assert!(*cow0 != *cow2); | |
1325 | assert!(*cow1 != *cow2); | |
1a4d82fc JJ |
1326 | } |
1327 | ||
1328 | #[test] | |
1329 | fn test_cowarc_clone_unique2() { | |
85aaf69f | 1330 | let mut cow0 = Arc::new(75); |
1a4d82fc JJ |
1331 | let cow1 = cow0.clone(); |
1332 | let cow2 = cow1.clone(); | |
1333 | ||
1334 | assert!(75 == *cow0); | |
1335 | assert!(75 == *cow1); | |
1336 | assert!(75 == *cow2); | |
1337 | ||
e9174d1e | 1338 | *Arc::make_mut(&mut cow0) += 1; |
1a4d82fc JJ |
1339 | assert!(76 == *cow0); |
1340 | assert!(75 == *cow1); | |
1341 | assert!(75 == *cow2); | |
1342 | ||
1343 | // cow1 and cow2 should share the same contents | |
1344 | // cow0 should have a unique reference | |
1345 | assert!(*cow0 != *cow1); | |
1346 | assert!(*cow0 != *cow2); | |
1347 | assert!(*cow1 == *cow2); | |
1348 | } | |
1349 | ||
1350 | #[test] | |
1351 | fn test_cowarc_clone_weak() { | |
85aaf69f | 1352 | let mut cow0 = Arc::new(75); |
e9174d1e | 1353 | let cow1_weak = Arc::downgrade(&cow0); |
1a4d82fc JJ |
1354 | |
1355 | assert!(75 == *cow0); | |
1356 | assert!(75 == *cow1_weak.upgrade().unwrap()); | |
1357 | ||
e9174d1e | 1358 | *Arc::make_mut(&mut cow0) += 1; |
1a4d82fc JJ |
1359 | |
1360 | assert!(76 == *cow0); | |
1361 | assert!(cow1_weak.upgrade().is_none()); | |
1362 | } | |
1363 | ||
1364 | #[test] | |
1365 | fn test_live() { | |
85aaf69f | 1366 | let x = Arc::new(5); |
e9174d1e | 1367 | let y = Arc::downgrade(&x); |
1a4d82fc JJ |
1368 | assert!(y.upgrade().is_some()); |
1369 | } | |
1370 | ||
1371 | #[test] | |
1372 | fn test_dead() { | |
85aaf69f | 1373 | let x = Arc::new(5); |
e9174d1e | 1374 | let y = Arc::downgrade(&x); |
1a4d82fc JJ |
1375 | drop(x); |
1376 | assert!(y.upgrade().is_none()); | |
1377 | } | |
1378 | ||
1379 | #[test] | |
1380 | fn weak_self_cyclic() { | |
1381 | struct Cycle { | |
b039eaaf | 1382 | x: Mutex<Option<Weak<Cycle>>>, |
1a4d82fc JJ |
1383 | } |
1384 | ||
1385 | let a = Arc::new(Cycle { x: Mutex::new(None) }); | |
e9174d1e | 1386 | let b = Arc::downgrade(&a.clone()); |
1a4d82fc JJ |
1387 | *a.x.lock().unwrap() = Some(b); |
1388 | ||
1389 | // hopefully we don't double-free (or leak)... | |
1390 | } | |
1391 | ||
1392 | #[test] | |
1393 | fn drop_arc() { | |
85aaf69f SL |
1394 | let mut canary = atomic::AtomicUsize::new(0); |
1395 | let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize)); | |
1a4d82fc JJ |
1396 | drop(x); |
1397 | assert!(canary.load(Acquire) == 1); | |
1398 | } | |
1399 | ||
1400 | #[test] | |
1401 | fn drop_arc_weak() { | |
85aaf69f SL |
1402 | let mut canary = atomic::AtomicUsize::new(0); |
1403 | let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize)); | |
e9174d1e | 1404 | let arc_weak = Arc::downgrade(&arc); |
1a4d82fc JJ |
1405 | assert!(canary.load(Acquire) == 0); |
1406 | drop(arc); | |
1407 | assert!(canary.load(Acquire) == 1); | |
1408 | drop(arc_weak); | |
1409 | } | |
1410 | ||
1411 | #[test] | |
1412 | fn test_strong_count() { | |
54a0048b | 1413 | let a = Arc::new(0); |
e9174d1e SL |
1414 | assert!(Arc::strong_count(&a) == 1); |
1415 | let w = Arc::downgrade(&a); | |
1416 | assert!(Arc::strong_count(&a) == 1); | |
1a4d82fc | 1417 | let b = w.upgrade().expect(""); |
e9174d1e SL |
1418 | assert!(Arc::strong_count(&b) == 2); |
1419 | assert!(Arc::strong_count(&a) == 2); | |
1a4d82fc JJ |
1420 | drop(w); |
1421 | drop(a); | |
e9174d1e | 1422 | assert!(Arc::strong_count(&b) == 1); |
1a4d82fc | 1423 | let c = b.clone(); |
e9174d1e SL |
1424 | assert!(Arc::strong_count(&b) == 2); |
1425 | assert!(Arc::strong_count(&c) == 2); | |
1a4d82fc JJ |
1426 | } |
1427 | ||
1428 | #[test] | |
1429 | fn test_weak_count() { | |
54a0048b | 1430 | let a = Arc::new(0); |
e9174d1e SL |
1431 | assert!(Arc::strong_count(&a) == 1); |
1432 | assert!(Arc::weak_count(&a) == 0); | |
1433 | let w = Arc::downgrade(&a); | |
1434 | assert!(Arc::strong_count(&a) == 1); | |
1435 | assert!(Arc::weak_count(&a) == 1); | |
1a4d82fc | 1436 | let x = w.clone(); |
e9174d1e | 1437 | assert!(Arc::weak_count(&a) == 2); |
1a4d82fc JJ |
1438 | drop(w); |
1439 | drop(x); | |
e9174d1e SL |
1440 | assert!(Arc::strong_count(&a) == 1); |
1441 | assert!(Arc::weak_count(&a) == 0); | |
1a4d82fc | 1442 | let c = a.clone(); |
e9174d1e SL |
1443 | assert!(Arc::strong_count(&a) == 2); |
1444 | assert!(Arc::weak_count(&a) == 0); | |
1445 | let d = Arc::downgrade(&c); | |
1446 | assert!(Arc::weak_count(&c) == 1); | |
1447 | assert!(Arc::strong_count(&c) == 2); | |
1a4d82fc JJ |
1448 | |
1449 | drop(a); | |
1450 | drop(c); | |
1451 | drop(d); | |
1452 | } | |
1453 | ||
1454 | #[test] | |
1455 | fn show_arc() { | |
54a0048b | 1456 | let a = Arc::new(5); |
85aaf69f | 1457 | assert_eq!(format!("{:?}", a), "5"); |
1a4d82fc JJ |
1458 | } |
1459 | ||
1460 | // Make sure deriving works with Arc<T> | |
85aaf69f | 1461 | #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)] |
b039eaaf SL |
1462 | struct Foo { |
1463 | inner: Arc<i32>, | |
1464 | } | |
62682a34 SL |
1465 | |
1466 | #[test] | |
1467 | fn test_unsized() { | |
1468 | let x: Arc<[i32]> = Arc::new([1, 2, 3]); | |
1469 | assert_eq!(format!("{:?}", x), "[1, 2, 3]"); | |
e9174d1e | 1470 | let y = Arc::downgrade(&x.clone()); |
62682a34 SL |
1471 | drop(x); |
1472 | assert!(y.upgrade().is_none()); | |
1473 | } | |
92a42be0 SL |
1474 | |
1475 | #[test] | |
1476 | fn test_from_owned() { | |
1477 | let foo = 123; | |
1478 | let foo_arc = Arc::from(foo); | |
1479 | assert!(123 == *foo_arc); | |
1480 | } | |
9cc50fc6 SL |
1481 | |
1482 | #[test] | |
1483 | fn test_new_weak() { | |
1484 | let foo: Weak<usize> = Weak::new(); | |
1485 | assert!(foo.upgrade().is_none()); | |
1486 | } | |
9e0c209e SL |
1487 | |
1488 | #[test] | |
1489 | fn test_ptr_eq() { | |
1490 | let five = Arc::new(5); | |
1491 | let same_five = five.clone(); | |
1492 | let other_five = Arc::new(5); | |
1493 | ||
1494 | assert!(Arc::ptr_eq(&five, &same_five)); | |
1495 | assert!(!Arc::ptr_eq(&five, &other_five)); | |
1496 | } | |
1a4d82fc | 1497 | } |
e9174d1e | 1498 | |
92a42be0 | 1499 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 1500 | impl<T: ?Sized> borrow::Borrow<T> for Arc<T> { |
b039eaaf SL |
1501 | fn borrow(&self) -> &T { |
1502 | &**self | |
1503 | } | |
1504 | } | |
1505 | ||
1506 | #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] | |
1507 | impl<T: ?Sized> AsRef<T> for Arc<T> { | |
1508 | fn as_ref(&self) -> &T { | |
1509 | &**self | |
1510 | } | |
e9174d1e | 1511 | } |