5 use std::convert::{From, TryInto};
8 use std::option::Option::{self, None, Some};
9 use std::sync::atomic::{
11 Ordering::{Acquire, SeqCst},
13 use std::sync::mpsc::channel;
19 struct Canary(*mut atomic::AtomicUsize);
21 impl Drop for Canary {
26 (*c).fetch_add(1, SeqCst);
34 #[cfg_attr(target_os = "emscripten", ignore)]
35 fn manually_share_arc() {
36 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
37 let arc_v = Arc::new(v);
39 let (tx, rx) = channel();
41 let _t = thread::spawn(move || {
42 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
43 assert_eq!((*arc_v)[3], 4);
46 tx.send(arc_v.clone()).unwrap();
48 assert_eq!((*arc_v)[2], 3);
49 assert_eq!((*arc_v)[4], 5);
53 fn test_arc_get_mut() {
54 let mut x = Arc::new(3);
55 *Arc::get_mut(&mut x).unwrap() = 4;
58 assert!(Arc::get_mut(&mut x).is_none());
60 assert!(Arc::get_mut(&mut x).is_some());
61 let _w = Arc::downgrade(&x);
62 assert!(Arc::get_mut(&mut x).is_none());
67 assert_eq!(Weak::weak_count(&Weak::<u64>::new()), 0);
68 assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
71 let w = Arc::downgrade(&a);
72 assert_eq!(Weak::strong_count(&w), 1);
73 assert_eq!(Weak::weak_count(&w), 1);
75 assert_eq!(Weak::strong_count(&w), 1);
76 assert_eq!(Weak::weak_count(&w), 2);
77 assert_eq!(Weak::strong_count(&w2), 1);
78 assert_eq!(Weak::weak_count(&w2), 2);
80 assert_eq!(Weak::strong_count(&w2), 1);
81 assert_eq!(Weak::weak_count(&w2), 1);
83 assert_eq!(Weak::strong_count(&w2), 2);
84 assert_eq!(Weak::weak_count(&w2), 1);
87 assert_eq!(Weak::strong_count(&w2), 0);
88 assert_eq!(Weak::weak_count(&w2), 0);
95 assert_eq!(Arc::try_unwrap(x), Ok(3));
98 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
100 let _w = Arc::downgrade(&x);
101 assert_eq!(Arc::try_unwrap(x), Ok(5));
107 // ^ Increase chances of hitting potential race conditions
110 let y = Arc::clone(&x);
111 let r_thread = std::thread::spawn(|| Arc::into_inner(x));
112 let s_thread = std::thread::spawn(|| Arc::into_inner(y));
113 let r = r_thread.join().expect("r_thread panicked");
114 let s = s_thread.join().expect("s_thread panicked");
116 matches!((r, s), (None, Some(3)) | (Some(3), None)),
117 "assertion failed: unexpected result `{:?}`\
118 \n expected `(None, Some(3))` or `(Some(3), None)`",
124 assert_eq!(Arc::into_inner(x), Some(3));
127 let y = Arc::clone(&x);
128 assert_eq!(Arc::into_inner(x), None);
129 assert_eq!(Arc::into_inner(y), Some(4));
132 let _w = Arc::downgrade(&x);
133 assert_eq!(Arc::into_inner(x), Some(5));
138 let x = Arc::new(Box::new("hello"));
141 let x_ptr = Arc::into_raw(x);
144 assert_eq!(**x_ptr, "hello");
146 let x = Arc::from_raw(x_ptr);
147 assert_eq!(**x, "hello");
149 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
154 fn test_into_from_raw_unsized() {
155 use std::fmt::Display;
156 use std::string::ToString;
158 let arc: Arc<str> = Arc::from("foo");
160 let ptr = Arc::into_raw(arc.clone());
161 let arc2 = unsafe { Arc::from_raw(ptr) };
163 assert_eq!(unsafe { &*ptr }, "foo");
164 assert_eq!(arc, arc2);
166 let arc: Arc<dyn Display> = Arc::new(123);
168 let ptr = Arc::into_raw(arc.clone());
169 let arc2 = unsafe { Arc::from_raw(ptr) };
171 assert_eq!(unsafe { &*ptr }.to_string(), "123");
172 assert_eq!(arc2.to_string(), "123");
176 fn into_from_weak_raw() {
177 let x = Arc::new(Box::new("hello"));
178 let y = Arc::downgrade(&x);
180 let y_ptr = Weak::into_raw(y);
182 assert_eq!(**y_ptr, "hello");
184 let y = Weak::from_raw(y_ptr);
185 let y_up = Weak::upgrade(&y).unwrap();
186 assert_eq!(**y_up, "hello");
189 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
194 fn test_into_from_weak_raw_unsized() {
195 use std::fmt::Display;
196 use std::string::ToString;
198 let arc: Arc<str> = Arc::from("foo");
199 let weak: Weak<str> = Arc::downgrade(&arc);
201 let ptr = Weak::into_raw(weak.clone());
202 let weak2 = unsafe { Weak::from_raw(ptr) };
204 assert_eq!(unsafe { &*ptr }, "foo");
205 assert!(weak.ptr_eq(&weak2));
207 let arc: Arc<dyn Display> = Arc::new(123);
208 let weak: Weak<dyn Display> = Arc::downgrade(&arc);
210 let ptr = Weak::into_raw(weak.clone());
211 let weak2 = unsafe { Weak::from_raw(ptr) };
213 assert_eq!(unsafe { &*ptr }.to_string(), "123");
214 assert!(weak.ptr_eq(&weak2));
218 fn test_cowarc_clone_make_mut() {
219 let mut cow0 = Arc::new(75);
220 let mut cow1 = cow0.clone();
221 let mut cow2 = cow1.clone();
223 assert!(75 == *Arc::make_mut(&mut cow0));
224 assert!(75 == *Arc::make_mut(&mut cow1));
225 assert!(75 == *Arc::make_mut(&mut cow2));
227 *Arc::make_mut(&mut cow0) += 1;
228 *Arc::make_mut(&mut cow1) += 2;
229 *Arc::make_mut(&mut cow2) += 3;
231 assert!(76 == *cow0);
232 assert!(77 == *cow1);
233 assert!(78 == *cow2);
235 // none should point to the same backing memory
236 assert!(*cow0 != *cow1);
237 assert!(*cow0 != *cow2);
238 assert!(*cow1 != *cow2);
242 fn test_cowarc_clone_unique2() {
243 let mut cow0 = Arc::new(75);
244 let cow1 = cow0.clone();
245 let cow2 = cow1.clone();
247 assert!(75 == *cow0);
248 assert!(75 == *cow1);
249 assert!(75 == *cow2);
251 *Arc::make_mut(&mut cow0) += 1;
252 assert!(76 == *cow0);
253 assert!(75 == *cow1);
254 assert!(75 == *cow2);
256 // cow1 and cow2 should share the same contents
257 // cow0 should have a unique reference
258 assert!(*cow0 != *cow1);
259 assert!(*cow0 != *cow2);
260 assert!(*cow1 == *cow2);
264 fn test_cowarc_clone_weak() {
265 let mut cow0 = Arc::new(75);
266 let cow1_weak = Arc::downgrade(&cow0);
268 assert!(75 == *cow0);
269 assert!(75 == *cow1_weak.upgrade().unwrap());
271 *Arc::make_mut(&mut cow0) += 1;
273 assert!(76 == *cow0);
274 assert!(cow1_weak.upgrade().is_none());
280 let y = Arc::downgrade(&x);
281 assert!(y.upgrade().is_some());
287 let y = Arc::downgrade(&x);
289 assert!(y.upgrade().is_none());
293 fn weak_self_cyclic() {
295 x: Mutex<Option<Weak<Cycle>>>,
298 let a = Arc::new(Cycle { x: Mutex::new(None) });
299 let b = Arc::downgrade(&a.clone());
300 *a.x.lock().unwrap() = Some(b);
302 // hopefully we don't double-free (or leak)...
307 let mut canary = atomic::AtomicUsize::new(0);
308 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
310 assert!(canary.load(Acquire) == 1);
315 let mut canary = atomic::AtomicUsize::new(0);
316 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
317 let arc_weak = Arc::downgrade(&arc);
318 assert!(canary.load(Acquire) == 0);
320 assert!(canary.load(Acquire) == 1);
325 fn test_strong_count() {
327 assert!(Arc::strong_count(&a) == 1);
328 let w = Arc::downgrade(&a);
329 assert!(Arc::strong_count(&a) == 1);
330 let b = w.upgrade().expect("");
331 assert!(Arc::strong_count(&b) == 2);
332 assert!(Arc::strong_count(&a) == 2);
335 assert!(Arc::strong_count(&b) == 1);
337 assert!(Arc::strong_count(&b) == 2);
338 assert!(Arc::strong_count(&c) == 2);
342 fn test_weak_count() {
344 assert!(Arc::strong_count(&a) == 1);
345 assert!(Arc::weak_count(&a) == 0);
346 let w = Arc::downgrade(&a);
347 assert!(Arc::strong_count(&a) == 1);
348 assert!(Arc::weak_count(&a) == 1);
350 assert!(Arc::weak_count(&a) == 2);
353 assert!(Arc::strong_count(&a) == 1);
354 assert!(Arc::weak_count(&a) == 0);
356 assert!(Arc::strong_count(&a) == 2);
357 assert!(Arc::weak_count(&a) == 0);
358 let d = Arc::downgrade(&c);
359 assert!(Arc::weak_count(&c) == 1);
360 assert!(Arc::strong_count(&c) == 2);
370 assert_eq!(format!("{a:?}"), "5");
373 // Make sure deriving works with Arc<T>
374 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
381 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
382 assert_eq!(format!("{x:?}"), "[1, 2, 3]");
383 let y = Arc::downgrade(&x.clone());
385 assert!(y.upgrade().is_none());
389 fn test_maybe_thin_unsized() {
390 // If/when custom thin DSTs exist, this test should be updated to use one
391 use std::ffi::{CStr, CString};
393 let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
394 assert_eq!(format!("{x:?}"), "\"swordfish\"");
395 let y: Weak<CStr> = Arc::downgrade(&x);
398 // At this point, the weak points to a dropped DST
399 assert!(y.upgrade().is_none());
400 // But we still need to be able to get the alloc layout to drop.
401 // CStr has no drop glue, but custom DSTs might, and need to work.
406 fn test_from_owned() {
408 let foo_arc = Arc::from(foo);
409 assert!(123 == *foo_arc);
414 let foo: Weak<usize> = Weak::new();
415 assert!(foo.upgrade().is_none());
420 let five = Arc::new(5);
421 let same_five = five.clone();
422 let other_five = Arc::new(5);
424 assert!(Arc::ptr_eq(&five, &same_five));
425 assert!(!Arc::ptr_eq(&five, &other_five));
429 #[cfg_attr(target_os = "emscripten", ignore)]
430 fn test_weak_count_locked() {
431 let mut a = Arc::new(atomic::AtomicBool::new(false));
433 let t = thread::spawn(move || {
435 let count = if cfg!(miri) { 1000 } else { 1000000 };
437 Arc::get_mut(&mut a);
439 a.store(true, SeqCst);
442 while !a2.load(SeqCst) {
443 let n = Arc::weak_count(&a2);
444 assert!(n < 2, "bad weak count: {}", n);
445 #[cfg(miri)] // Miri's scheduler does not guarantee liveness, and thus needs this hint.
446 std::hint::spin_loop();
453 let r: Arc<str> = Arc::from("foo");
455 assert_eq!(&r[..], "foo");
459 fn test_copy_from_slice() {
460 let s: &[u32] = &[1, 2, 3];
461 let r: Arc<[u32]> = Arc::from(s);
463 assert_eq!(&r[..], [1, 2, 3]);
467 fn test_clone_from_slice() {
468 #[derive(Clone, Debug, Eq, PartialEq)]
471 let s: &[X] = &[X(1), X(2), X(3)];
472 let r: Arc<[X]> = Arc::from(s);
474 assert_eq!(&r[..], s);
479 fn test_clone_from_slice_panic() {
480 use std::string::{String, ToString};
482 struct Fail(u32, String);
484 impl Clone for Fail {
485 fn clone(&self) -> Fail {
489 Fail(self.0, self.1.clone())
494 &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())];
496 // Should panic, but not cause memory corruption
497 let _r: Arc<[Fail]> = Arc::from(s);
502 let b: Box<u32> = Box::new(123);
503 let r: Arc<u32> = Arc::from(b);
509 fn test_from_box_str() {
510 use std::string::String;
512 let s = String::from("foo").into_boxed_str();
513 let r: Arc<str> = Arc::from(s);
515 assert_eq!(&r[..], "foo");
519 fn test_from_box_slice() {
520 let s = vec![1, 2, 3].into_boxed_slice();
521 let r: Arc<[u32]> = Arc::from(s);
523 assert_eq!(&r[..], [1, 2, 3]);
527 fn test_from_box_trait() {
528 use std::fmt::Display;
529 use std::string::ToString;
531 let b: Box<dyn Display> = Box::new(123);
532 let r: Arc<dyn Display> = Arc::from(b);
534 assert_eq!(r.to_string(), "123");
538 fn test_from_box_trait_zero_sized() {
541 let b: Box<dyn Debug> = Box::new(());
542 let r: Arc<dyn Debug> = Arc::from(b);
544 assert_eq!(format!("{r:?}"), "()");
549 let v = vec![1, 2, 3];
550 let r: Arc<[u32]> = Arc::from(v);
552 assert_eq!(&r[..], [1, 2, 3]);
559 let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::MAX);
560 let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
562 assert!(r1.clone().downcast::<u32>().is_err());
564 let r1i32 = r1.downcast::<i32>();
565 assert!(r1i32.is_ok());
566 assert_eq!(r1i32.unwrap(), Arc::new(i32::MAX));
568 assert!(r2.clone().downcast::<i32>().is_err());
570 let r2str = r2.downcast::<&'static str>();
571 assert!(r2str.is_ok());
572 assert_eq!(r2str.unwrap(), Arc::new("abc"));
576 fn test_array_from_slice() {
577 let v = vec![1, 2, 3];
578 let r: Arc<[u32]> = Arc::from(v);
580 let a: Result<Arc<[u32; 3]>, _> = r.clone().try_into();
583 let a: Result<Arc<[u32; 2]>, _> = r.clone().try_into();
588 fn test_arc_cyclic_with_zero_refs() {
590 inner: Weak<ZeroRefs>,
592 let zero_refs = Arc::new_cyclic(|inner| {
593 assert_eq!(inner.strong_count(), 0);
594 assert!(inner.upgrade().is_none());
595 ZeroRefs { inner: Weak::new() }
598 assert_eq!(Arc::strong_count(&zero_refs), 1);
599 assert_eq!(Arc::weak_count(&zero_refs), 0);
600 assert_eq!(zero_refs.inner.strong_count(), 0);
601 assert_eq!(zero_refs.inner.weak_count(), 0);
605 fn test_arc_new_cyclic_one_ref() {
609 let one_ref = Arc::new_cyclic(|inner| {
610 assert_eq!(inner.strong_count(), 0);
611 assert!(inner.upgrade().is_none());
612 OneRef { inner: inner.clone() }
615 assert_eq!(Arc::strong_count(&one_ref), 1);
616 assert_eq!(Arc::weak_count(&one_ref), 1);
618 let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap();
619 assert!(Arc::ptr_eq(&one_ref, &one_ref2));
621 assert_eq!(Arc::strong_count(&one_ref), 2);
622 assert_eq!(Arc::weak_count(&one_ref), 1);
626 fn test_arc_cyclic_two_refs() {
628 inner1: Weak<TwoRefs>,
629 inner2: Weak<TwoRefs>,
631 let two_refs = Arc::new_cyclic(|inner| {
632 assert_eq!(inner.strong_count(), 0);
633 assert!(inner.upgrade().is_none());
635 let inner1 = inner.clone();
636 let inner2 = inner1.clone();
638 TwoRefs { inner1, inner2 }
641 assert_eq!(Arc::strong_count(&two_refs), 1);
642 assert_eq!(Arc::weak_count(&two_refs), 2);
644 let two_refs1 = Weak::upgrade(&two_refs.inner1).unwrap();
645 assert!(Arc::ptr_eq(&two_refs, &two_refs1));
647 let two_refs2 = Weak::upgrade(&two_refs.inner2).unwrap();
648 assert!(Arc::ptr_eq(&two_refs, &two_refs2));
650 assert_eq!(Arc::strong_count(&two_refs), 3);
651 assert_eq!(Arc::weak_count(&two_refs), 2);
654 /// Test for Arc::drop bug (https://github.com/rust-lang/rust/issues/55005)
656 #[cfg(miri)] // relies on Stacked Borrows in Miri
657 fn arc_drop_dereferenceable_race() {
658 // The bug seems to take up to 700 iterations to reproduce with most seeds (tested 0-9).
660 let arc_1 = Arc::new(());
661 let arc_2 = arc_1.clone();
662 let thread = thread::spawn(|| drop(arc_2));
663 // Spin a bit; makes the race more likely to appear
669 thread.join().unwrap();