1 use super::*;
2
3 use std::boxed::Box;
4 use std::clone::Clone;
5 use std::convert::{From, TryInto};
6 use std::mem::drop;
7 use std::ops::Drop;
8 use std::option::Option::{self, None, Some};
9 use std::sync::atomic::{
10 self,
11 Ordering::{Acquire, SeqCst},
12 };
13 use std::sync::mpsc::channel;
14 use std::sync::Mutex;
15 use std::thread;
16
17 use crate::vec::Vec;
18
19 struct Canary(*mut atomic::AtomicUsize);
20
21 impl Drop for Canary {
drop(&mut self)22 fn drop(&mut self) {
23 unsafe {
24 match *self {
25 Canary(c) => {
26 (*c).fetch_add(1, SeqCst);
27 }
28 }
29 }
30 }
31 }
32
33 #[test]
34 #[cfg_attr(target_os = "emscripten", ignore)]
manually_share_arc()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);
38
39 let (tx, rx) = channel();
40
41 let _t = thread::spawn(move || {
42 let arc_v: Arc<Vec<i32>> = rx.recv().unwrap();
43 assert_eq!((*arc_v)[3], 4);
44 });
45
46 tx.send(arc_v.clone()).unwrap();
47
48 assert_eq!((*arc_v)[2], 3);
49 assert_eq!((*arc_v)[4], 5);
50 }
51
52 #[test]
test_arc_get_mut()53 fn test_arc_get_mut() {
54 let mut x = Arc::new(3);
55 *Arc::get_mut(&mut x).unwrap() = 4;
56 assert_eq!(*x, 4);
57 let y = x.clone();
58 assert!(Arc::get_mut(&mut x).is_none());
59 drop(y);
60 assert!(Arc::get_mut(&mut x).is_some());
61 let _w = Arc::downgrade(&x);
62 assert!(Arc::get_mut(&mut x).is_none());
63 }
64
65 #[test]
weak_counts()66 fn weak_counts() {
67 assert_eq!(Weak::weak_count(&Weak::<u64>::new()), 0);
68 assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
69
70 let a = Arc::new(0);
71 let w = Arc::downgrade(&a);
72 assert_eq!(Weak::strong_count(&w), 1);
73 assert_eq!(Weak::weak_count(&w), 1);
74 let w2 = w.clone();
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);
79 drop(w);
80 assert_eq!(Weak::strong_count(&w2), 1);
81 assert_eq!(Weak::weak_count(&w2), 1);
82 let a2 = a.clone();
83 assert_eq!(Weak::strong_count(&w2), 2);
84 assert_eq!(Weak::weak_count(&w2), 1);
85 drop(a2);
86 drop(a);
87 assert_eq!(Weak::strong_count(&w2), 0);
88 assert_eq!(Weak::weak_count(&w2), 0);
89 drop(w2);
90 }
91
92 #[test]
try_unwrap()93 fn try_unwrap() {
94 let x = Arc::new(3);
95 assert_eq!(Arc::try_unwrap(x), Ok(3));
96 let x = Arc::new(4);
97 let _y = x.clone();
98 assert_eq!(Arc::try_unwrap(x), Err(Arc::new(4)));
99 let x = Arc::new(5);
100 let _w = Arc::downgrade(&x);
101 assert_eq!(Arc::try_unwrap(x), Ok(5));
102 }
103
104 #[test]
into_inner()105 fn into_inner() {
106 for _ in 0..100
107 // ^ Increase chances of hitting potential race conditions
108 {
109 let x = Arc::new(3);
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");
115 assert!(
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)`",
119 (r, s),
120 );
121 }
122
123 let x = Arc::new(3);
124 assert_eq!(Arc::into_inner(x), Some(3));
125
126 let x = Arc::new(4);
127 let y = Arc::clone(&x);
128 assert_eq!(Arc::into_inner(x), None);
129 assert_eq!(Arc::into_inner(y), Some(4));
130
131 let x = Arc::new(5);
132 let _w = Arc::downgrade(&x);
133 assert_eq!(Arc::into_inner(x), Some(5));
134 }
135
136 #[test]
into_from_raw()137 fn into_from_raw() {
138 let x = Arc::new(Box::new("hello"));
139 let y = x.clone();
140
141 let x_ptr = Arc::into_raw(x);
142 drop(y);
143 unsafe {
144 assert_eq!(**x_ptr, "hello");
145
146 let x = Arc::from_raw(x_ptr);
147 assert_eq!(**x, "hello");
148
149 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
150 }
151 }
152
153 #[test]
test_into_from_raw_unsized()154 fn test_into_from_raw_unsized() {
155 use std::fmt::Display;
156 use std::string::ToString;
157
158 let arc: Arc<str> = Arc::from("foo");
159
160 let ptr = Arc::into_raw(arc.clone());
161 let arc2 = unsafe { Arc::from_raw(ptr) };
162
163 assert_eq!(unsafe { &*ptr }, "foo");
164 assert_eq!(arc, arc2);
165
166 let arc: Arc<dyn Display> = Arc::new(123);
167
168 let ptr = Arc::into_raw(arc.clone());
169 let arc2 = unsafe { Arc::from_raw(ptr) };
170
171 assert_eq!(unsafe { &*ptr }.to_string(), "123");
172 assert_eq!(arc2.to_string(), "123");
173 }
174
175 #[test]
into_from_weak_raw()176 fn into_from_weak_raw() {
177 let x = Arc::new(Box::new("hello"));
178 let y = Arc::downgrade(&x);
179
180 let y_ptr = Weak::into_raw(y);
181 unsafe {
182 assert_eq!(**y_ptr, "hello");
183
184 let y = Weak::from_raw(y_ptr);
185 let y_up = Weak::upgrade(&y).unwrap();
186 assert_eq!(**y_up, "hello");
187 drop(y_up);
188
189 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
190 }
191 }
192
193 #[test]
test_into_from_weak_raw_unsized()194 fn test_into_from_weak_raw_unsized() {
195 use std::fmt::Display;
196 use std::string::ToString;
197
198 let arc: Arc<str> = Arc::from("foo");
199 let weak: Weak<str> = Arc::downgrade(&arc);
200
201 let ptr = Weak::into_raw(weak.clone());
202 let weak2 = unsafe { Weak::from_raw(ptr) };
203
204 assert_eq!(unsafe { &*ptr }, "foo");
205 assert!(weak.ptr_eq(&weak2));
206
207 let arc: Arc<dyn Display> = Arc::new(123);
208 let weak: Weak<dyn Display> = Arc::downgrade(&arc);
209
210 let ptr = Weak::into_raw(weak.clone());
211 let weak2 = unsafe { Weak::from_raw(ptr) };
212
213 assert_eq!(unsafe { &*ptr }.to_string(), "123");
214 assert!(weak.ptr_eq(&weak2));
215 }
216
217 #[test]
test_cowarc_clone_make_mut()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();
222
223 assert!(75 == *Arc::make_mut(&mut cow0));
224 assert!(75 == *Arc::make_mut(&mut cow1));
225 assert!(75 == *Arc::make_mut(&mut cow2));
226
227 *Arc::make_mut(&mut cow0) += 1;
228 *Arc::make_mut(&mut cow1) += 2;
229 *Arc::make_mut(&mut cow2) += 3;
230
231 assert!(76 == *cow0);
232 assert!(77 == *cow1);
233 assert!(78 == *cow2);
234
235 // none should point to the same backing memory
236 assert!(*cow0 != *cow1);
237 assert!(*cow0 != *cow2);
238 assert!(*cow1 != *cow2);
239 }
240
241 #[test]
test_cowarc_clone_unique2()242 fn test_cowarc_clone_unique2() {
243 let mut cow0 = Arc::new(75);
244 let cow1 = cow0.clone();
245 let cow2 = cow1.clone();
246
247 assert!(75 == *cow0);
248 assert!(75 == *cow1);
249 assert!(75 == *cow2);
250
251 *Arc::make_mut(&mut cow0) += 1;
252 assert!(76 == *cow0);
253 assert!(75 == *cow1);
254 assert!(75 == *cow2);
255
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);
261 }
262
263 #[test]
test_cowarc_clone_weak()264 fn test_cowarc_clone_weak() {
265 let mut cow0 = Arc::new(75);
266 let cow1_weak = Arc::downgrade(&cow0);
267
268 assert!(75 == *cow0);
269 assert!(75 == *cow1_weak.upgrade().unwrap());
270
271 *Arc::make_mut(&mut cow0) += 1;
272
273 assert!(76 == *cow0);
274 assert!(cow1_weak.upgrade().is_none());
275 }
276
277 #[test]
test_live()278 fn test_live() {
279 let x = Arc::new(5);
280 let y = Arc::downgrade(&x);
281 assert!(y.upgrade().is_some());
282 }
283
284 #[test]
test_dead()285 fn test_dead() {
286 let x = Arc::new(5);
287 let y = Arc::downgrade(&x);
288 drop(x);
289 assert!(y.upgrade().is_none());
290 }
291
292 #[test]
weak_self_cyclic()293 fn weak_self_cyclic() {
294 struct Cycle {
295 x: Mutex<Option<Weak<Cycle>>>,
296 }
297
298 let a = Arc::new(Cycle { x: Mutex::new(None) });
299 let b = Arc::downgrade(&a.clone());
300 *a.x.lock().unwrap() = Some(b);
301
302 // hopefully we don't double-free (or leak)...
303 }
304
305 #[test]
drop_arc()306 fn drop_arc() {
307 let mut canary = atomic::AtomicUsize::new(0);
308 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
309 drop(x);
310 assert!(canary.load(Acquire) == 1);
311 }
312
313 #[test]
drop_arc_weak()314 fn drop_arc_weak() {
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);
319 drop(arc);
320 assert!(canary.load(Acquire) == 1);
321 drop(arc_weak);
322 }
323
324 #[test]
test_strong_count()325 fn test_strong_count() {
326 let a = Arc::new(0);
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);
333 drop(w);
334 drop(a);
335 assert!(Arc::strong_count(&b) == 1);
336 let c = b.clone();
337 assert!(Arc::strong_count(&b) == 2);
338 assert!(Arc::strong_count(&c) == 2);
339 }
340
341 #[test]
test_weak_count()342 fn test_weak_count() {
343 let a = Arc::new(0);
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);
349 let x = w.clone();
350 assert!(Arc::weak_count(&a) == 2);
351 drop(w);
352 drop(x);
353 assert!(Arc::strong_count(&a) == 1);
354 assert!(Arc::weak_count(&a) == 0);
355 let c = a.clone();
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);
361
362 drop(a);
363 drop(c);
364 drop(d);
365 }
366
367 #[test]
show_arc()368 fn show_arc() {
369 let a = Arc::new(5);
370 assert_eq!(format!("{a:?}"), "5");
371 }
372
373 // Make sure deriving works with Arc<T>
374 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
375 struct Foo {
376 inner: Arc<i32>,
377 }
378
379 #[test]
test_unsized()380 fn test_unsized() {
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());
384 drop(x);
385 assert!(y.upgrade().is_none());
386 }
387
388 #[test]
test_maybe_thin_unsized()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};
392
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);
396 drop(x);
397
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.
402 drop(y);
403 }
404
405 #[test]
test_from_owned()406 fn test_from_owned() {
407 let foo = 123;
408 let foo_arc = Arc::from(foo);
409 assert!(123 == *foo_arc);
410 }
411
412 #[test]
test_new_weak()413 fn test_new_weak() {
414 let foo: Weak<usize> = Weak::new();
415 assert!(foo.upgrade().is_none());
416 }
417
418 #[test]
test_ptr_eq()419 fn test_ptr_eq() {
420 let five = Arc::new(5);
421 let same_five = five.clone();
422 let other_five = Arc::new(5);
423
424 assert!(Arc::ptr_eq(&five, &same_five));
425 assert!(!Arc::ptr_eq(&five, &other_five));
426 }
427
428 #[test]
429 #[cfg_attr(target_os = "emscripten", ignore)]
test_weak_count_locked()430 fn test_weak_count_locked() {
431 let mut a = Arc::new(atomic::AtomicBool::new(false));
432 let a2 = a.clone();
433 let t = thread::spawn(move || {
434 // Miri is too slow
435 let count = if cfg!(miri) { 1000 } else { 1000000 };
436 for _i in 0..count {
437 Arc::get_mut(&mut a);
438 }
439 a.store(true, SeqCst);
440 });
441
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();
447 }
448 t.join().unwrap();
449 }
450
451 #[test]
test_from_str()452 fn test_from_str() {
453 let r: Arc<str> = Arc::from("foo");
454
455 assert_eq!(&r[..], "foo");
456 }
457
458 #[test]
test_copy_from_slice()459 fn test_copy_from_slice() {
460 let s: &[u32] = &[1, 2, 3];
461 let r: Arc<[u32]> = Arc::from(s);
462
463 assert_eq!(&r[..], [1, 2, 3]);
464 }
465
466 #[test]
test_clone_from_slice()467 fn test_clone_from_slice() {
468 #[derive(Clone, Debug, Eq, PartialEq)]
469 struct X(u32);
470
471 let s: &[X] = &[X(1), X(2), X(3)];
472 let r: Arc<[X]> = Arc::from(s);
473
474 assert_eq!(&r[..], s);
475 }
476
477 #[test]
478 #[should_panic]
test_clone_from_slice_panic()479 fn test_clone_from_slice_panic() {
480 use std::string::{String, ToString};
481
482 struct Fail(u32, String);
483
484 impl Clone for Fail {
485 fn clone(&self) -> Fail {
486 if self.0 == 2 {
487 panic!();
488 }
489 Fail(self.0, self.1.clone())
490 }
491 }
492
493 let s: &[Fail] =
494 &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())];
495
496 // Should panic, but not cause memory corruption
497 let _r: Arc<[Fail]> = Arc::from(s);
498 }
499
500 #[test]
test_from_box()501 fn test_from_box() {
502 let b: Box<u32> = Box::new(123);
503 let r: Arc<u32> = Arc::from(b);
504
505 assert_eq!(*r, 123);
506 }
507
508 #[test]
test_from_box_str()509 fn test_from_box_str() {
510 use std::string::String;
511
512 let s = String::from("foo").into_boxed_str();
513 let r: Arc<str> = Arc::from(s);
514
515 assert_eq!(&r[..], "foo");
516 }
517
518 #[test]
test_from_box_slice()519 fn test_from_box_slice() {
520 let s = vec![1, 2, 3].into_boxed_slice();
521 let r: Arc<[u32]> = Arc::from(s);
522
523 assert_eq!(&r[..], [1, 2, 3]);
524 }
525
526 #[test]
test_from_box_trait()527 fn test_from_box_trait() {
528 use std::fmt::Display;
529 use std::string::ToString;
530
531 let b: Box<dyn Display> = Box::new(123);
532 let r: Arc<dyn Display> = Arc::from(b);
533
534 assert_eq!(r.to_string(), "123");
535 }
536
537 #[test]
test_from_box_trait_zero_sized()538 fn test_from_box_trait_zero_sized() {
539 use std::fmt::Debug;
540
541 let b: Box<dyn Debug> = Box::new(());
542 let r: Arc<dyn Debug> = Arc::from(b);
543
544 assert_eq!(format!("{r:?}"), "()");
545 }
546
547 #[test]
test_from_vec()548 fn test_from_vec() {
549 let v = vec![1, 2, 3];
550 let r: Arc<[u32]> = Arc::from(v);
551
552 assert_eq!(&r[..], [1, 2, 3]);
553 }
554
555 #[test]
test_downcast()556 fn test_downcast() {
557 use std::any::Any;
558
559 let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::MAX);
560 let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
561
562 assert!(r1.clone().downcast::<u32>().is_err());
563
564 let r1i32 = r1.downcast::<i32>();
565 assert!(r1i32.is_ok());
566 assert_eq!(r1i32.unwrap(), Arc::new(i32::MAX));
567
568 assert!(r2.clone().downcast::<i32>().is_err());
569
570 let r2str = r2.downcast::<&'static str>();
571 assert!(r2str.is_ok());
572 assert_eq!(r2str.unwrap(), Arc::new("abc"));
573 }
574
575 #[test]
test_array_from_slice()576 fn test_array_from_slice() {
577 let v = vec![1, 2, 3];
578 let r: Arc<[u32]> = Arc::from(v);
579
580 let a: Result<Arc<[u32; 3]>, _> = r.clone().try_into();
581 assert!(a.is_ok());
582
583 let a: Result<Arc<[u32; 2]>, _> = r.clone().try_into();
584 assert!(a.is_err());
585 }
586
587 #[test]
test_arc_cyclic_with_zero_refs()588 fn test_arc_cyclic_with_zero_refs() {
589 struct ZeroRefs {
590 inner: Weak<ZeroRefs>,
591 }
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() }
596 });
597
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);
602 }
603
604 #[test]
test_arc_new_cyclic_one_ref()605 fn test_arc_new_cyclic_one_ref() {
606 struct OneRef {
607 inner: Weak<OneRef>,
608 }
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() }
613 });
614
615 assert_eq!(Arc::strong_count(&one_ref), 1);
616 assert_eq!(Arc::weak_count(&one_ref), 1);
617
618 let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap();
619 assert!(Arc::ptr_eq(&one_ref, &one_ref2));
620
621 assert_eq!(Arc::strong_count(&one_ref), 2);
622 assert_eq!(Arc::weak_count(&one_ref), 1);
623 }
624
625 #[test]
test_arc_cyclic_two_refs()626 fn test_arc_cyclic_two_refs() {
627 struct TwoRefs {
628 inner1: Weak<TwoRefs>,
629 inner2: Weak<TwoRefs>,
630 }
631 let two_refs = Arc::new_cyclic(|inner| {
632 assert_eq!(inner.strong_count(), 0);
633 assert!(inner.upgrade().is_none());
634
635 let inner1 = inner.clone();
636 let inner2 = inner1.clone();
637
638 TwoRefs { inner1, inner2 }
639 });
640
641 assert_eq!(Arc::strong_count(&two_refs), 1);
642 assert_eq!(Arc::weak_count(&two_refs), 2);
643
644 let two_refs1 = Weak::upgrade(&two_refs.inner1).unwrap();
645 assert!(Arc::ptr_eq(&two_refs, &two_refs1));
646
647 let two_refs2 = Weak::upgrade(&two_refs.inner2).unwrap();
648 assert!(Arc::ptr_eq(&two_refs, &two_refs2));
649
650 assert_eq!(Arc::strong_count(&two_refs), 3);
651 assert_eq!(Arc::weak_count(&two_refs), 2);
652 }
653
654 /// Test for Arc::drop bug (https://github.com/rust-lang/rust/issues/55005)
655 #[test]
656 #[cfg(miri)] // relies on Stacked Borrows in Miri
arc_drop_dereferenceable_race()657 fn arc_drop_dereferenceable_race() {
658 // The bug seems to take up to 700 iterations to reproduce with most seeds (tested 0-9).
659 for _ in 0..750 {
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
664 let mut i = 0;
665 while i < 256 {
666 i += 1;
667 }
668 drop(arc_1);
669 thread.join().unwrap();
670 }
671 }
672