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));
106 let x = Arc::new(Box::new("hello"));
109 let x_ptr = Arc::into_raw(x);
112 assert_eq!(**x_ptr, "hello");
114 let x = Arc::from_raw(x_ptr);
115 assert_eq!(**x, "hello");
117 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
122 fn test_into_from_raw_unsized() {
123 use std::fmt::Display;
124 use std::string::ToString;
126 let arc: Arc<str> = Arc::from("foo");
128 let ptr = Arc::into_raw(arc.clone());
129 let arc2 = unsafe { Arc::from_raw(ptr) };
131 assert_eq!(unsafe { &*ptr }, "foo");
132 assert_eq!(arc, arc2);
134 let arc: Arc<dyn Display> = Arc::new(123);
136 let ptr = Arc::into_raw(arc.clone());
137 let arc2 = unsafe { Arc::from_raw(ptr) };
139 assert_eq!(unsafe { &*ptr }.to_string(), "123");
140 assert_eq!(arc2.to_string(), "123");
144 fn into_from_weak_raw() {
145 let x = Arc::new(Box::new("hello"));
146 let y = Arc::downgrade(&x);
148 let y_ptr = Weak::into_raw(y);
150 assert_eq!(**y_ptr, "hello");
152 let y = Weak::from_raw(y_ptr);
153 let y_up = Weak::upgrade(&y).unwrap();
154 assert_eq!(**y_up, "hello");
157 assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
162 fn test_into_from_weak_raw_unsized() {
163 use std::fmt::Display;
164 use std::string::ToString;
166 let arc: Arc<str> = Arc::from("foo");
167 let weak: Weak<str> = Arc::downgrade(&arc);
169 let ptr = Weak::into_raw(weak.clone());
170 let weak2 = unsafe { Weak::from_raw(ptr) };
172 assert_eq!(unsafe { &*ptr }, "foo");
173 assert!(weak.ptr_eq(&weak2));
175 let arc: Arc<dyn Display> = Arc::new(123);
176 let weak: Weak<dyn Display> = Arc::downgrade(&arc);
178 let ptr = Weak::into_raw(weak.clone());
179 let weak2 = unsafe { Weak::from_raw(ptr) };
181 assert_eq!(unsafe { &*ptr }.to_string(), "123");
182 assert!(weak.ptr_eq(&weak2));
186 fn test_cowarc_clone_make_mut() {
187 let mut cow0 = Arc::new(75);
188 let mut cow1 = cow0.clone();
189 let mut cow2 = cow1.clone();
191 assert!(75 == *Arc::make_mut(&mut cow0));
192 assert!(75 == *Arc::make_mut(&mut cow1));
193 assert!(75 == *Arc::make_mut(&mut cow2));
195 *Arc::make_mut(&mut cow0) += 1;
196 *Arc::make_mut(&mut cow1) += 2;
197 *Arc::make_mut(&mut cow2) += 3;
199 assert!(76 == *cow0);
200 assert!(77 == *cow1);
201 assert!(78 == *cow2);
203 // none should point to the same backing memory
204 assert!(*cow0 != *cow1);
205 assert!(*cow0 != *cow2);
206 assert!(*cow1 != *cow2);
210 fn test_cowarc_clone_unique2() {
211 let mut cow0 = Arc::new(75);
212 let cow1 = cow0.clone();
213 let cow2 = cow1.clone();
215 assert!(75 == *cow0);
216 assert!(75 == *cow1);
217 assert!(75 == *cow2);
219 *Arc::make_mut(&mut cow0) += 1;
220 assert!(76 == *cow0);
221 assert!(75 == *cow1);
222 assert!(75 == *cow2);
224 // cow1 and cow2 should share the same contents
225 // cow0 should have a unique reference
226 assert!(*cow0 != *cow1);
227 assert!(*cow0 != *cow2);
228 assert!(*cow1 == *cow2);
232 fn test_cowarc_clone_weak() {
233 let mut cow0 = Arc::new(75);
234 let cow1_weak = Arc::downgrade(&cow0);
236 assert!(75 == *cow0);
237 assert!(75 == *cow1_weak.upgrade().unwrap());
239 *Arc::make_mut(&mut cow0) += 1;
241 assert!(76 == *cow0);
242 assert!(cow1_weak.upgrade().is_none());
248 let y = Arc::downgrade(&x);
249 assert!(y.upgrade().is_some());
255 let y = Arc::downgrade(&x);
257 assert!(y.upgrade().is_none());
261 fn weak_self_cyclic() {
263 x: Mutex<Option<Weak<Cycle>>>,
266 let a = Arc::new(Cycle { x: Mutex::new(None) });
267 let b = Arc::downgrade(&a.clone());
268 *a.x.lock().unwrap() = Some(b);
270 // hopefully we don't double-free (or leak)...
275 let mut canary = atomic::AtomicUsize::new(0);
276 let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
278 assert!(canary.load(Acquire) == 1);
283 let mut canary = atomic::AtomicUsize::new(0);
284 let arc = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
285 let arc_weak = Arc::downgrade(&arc);
286 assert!(canary.load(Acquire) == 0);
288 assert!(canary.load(Acquire) == 1);
293 fn test_strong_count() {
295 assert!(Arc::strong_count(&a) == 1);
296 let w = Arc::downgrade(&a);
297 assert!(Arc::strong_count(&a) == 1);
298 let b = w.upgrade().expect("");
299 assert!(Arc::strong_count(&b) == 2);
300 assert!(Arc::strong_count(&a) == 2);
303 assert!(Arc::strong_count(&b) == 1);
305 assert!(Arc::strong_count(&b) == 2);
306 assert!(Arc::strong_count(&c) == 2);
310 fn test_weak_count() {
312 assert!(Arc::strong_count(&a) == 1);
313 assert!(Arc::weak_count(&a) == 0);
314 let w = Arc::downgrade(&a);
315 assert!(Arc::strong_count(&a) == 1);
316 assert!(Arc::weak_count(&a) == 1);
318 assert!(Arc::weak_count(&a) == 2);
321 assert!(Arc::strong_count(&a) == 1);
322 assert!(Arc::weak_count(&a) == 0);
324 assert!(Arc::strong_count(&a) == 2);
325 assert!(Arc::weak_count(&a) == 0);
326 let d = Arc::downgrade(&c);
327 assert!(Arc::weak_count(&c) == 1);
328 assert!(Arc::strong_count(&c) == 2);
338 assert_eq!(format!("{a:?}"), "5");
341 // Make sure deriving works with Arc<T>
342 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
349 let x: Arc<[i32]> = Arc::new([1, 2, 3]);
350 assert_eq!(format!("{x:?}"), "[1, 2, 3]");
351 let y = Arc::downgrade(&x.clone());
353 assert!(y.upgrade().is_none());
357 fn test_maybe_thin_unsized() {
358 // If/when custom thin DSTs exist, this test should be updated to use one
359 use std::ffi::{CStr, CString};
361 let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
362 assert_eq!(format!("{x:?}"), "\"swordfish\"");
363 let y: Weak<CStr> = Arc::downgrade(&x);
366 // At this point, the weak points to a dropped DST
367 assert!(y.upgrade().is_none());
368 // But we still need to be able to get the alloc layout to drop.
369 // CStr has no drop glue, but custom DSTs might, and need to work.
374 fn test_from_owned() {
376 let foo_arc = Arc::from(foo);
377 assert!(123 == *foo_arc);
382 let foo: Weak<usize> = Weak::new();
383 assert!(foo.upgrade().is_none());
388 let five = Arc::new(5);
389 let same_five = five.clone();
390 let other_five = Arc::new(5);
392 assert!(Arc::ptr_eq(&five, &same_five));
393 assert!(!Arc::ptr_eq(&five, &other_five));
397 #[cfg_attr(target_os = "emscripten", ignore)]
398 fn test_weak_count_locked() {
399 let mut a = Arc::new(atomic::AtomicBool::new(false));
401 let t = thread::spawn(move || {
403 let count = if cfg!(miri) { 1000 } else { 1000000 };
405 Arc::get_mut(&mut a);
407 a.store(true, SeqCst);
410 while !a2.load(SeqCst) {
411 let n = Arc::weak_count(&a2);
412 assert!(n < 2, "bad weak count: {}", n);
413 #[cfg(miri)] // Miri's scheduler does not guarantee liveness, and thus needs this hint.
414 std::hint::spin_loop();
421 let r: Arc<str> = Arc::from("foo");
423 assert_eq!(&r[..], "foo");
427 fn test_copy_from_slice() {
428 let s: &[u32] = &[1, 2, 3];
429 let r: Arc<[u32]> = Arc::from(s);
431 assert_eq!(&r[..], [1, 2, 3]);
435 fn test_clone_from_slice() {
436 #[derive(Clone, Debug, Eq, PartialEq)]
439 let s: &[X] = &[X(1), X(2), X(3)];
440 let r: Arc<[X]> = Arc::from(s);
442 assert_eq!(&r[..], s);
447 fn test_clone_from_slice_panic() {
448 use std::string::{String, ToString};
450 struct Fail(u32, String);
452 impl Clone for Fail {
453 fn clone(&self) -> Fail {
457 Fail(self.0, self.1.clone())
462 &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())];
464 // Should panic, but not cause memory corruption
465 let _r: Arc<[Fail]> = Arc::from(s);
470 let b: Box<u32> = Box::new(123);
471 let r: Arc<u32> = Arc::from(b);
477 fn test_from_box_str() {
478 use std::string::String;
480 let s = String::from("foo").into_boxed_str();
481 let r: Arc<str> = Arc::from(s);
483 assert_eq!(&r[..], "foo");
487 fn test_from_box_slice() {
488 let s = vec![1, 2, 3].into_boxed_slice();
489 let r: Arc<[u32]> = Arc::from(s);
491 assert_eq!(&r[..], [1, 2, 3]);
495 fn test_from_box_trait() {
496 use std::fmt::Display;
497 use std::string::ToString;
499 let b: Box<dyn Display> = Box::new(123);
500 let r: Arc<dyn Display> = Arc::from(b);
502 assert_eq!(r.to_string(), "123");
506 fn test_from_box_trait_zero_sized() {
509 let b: Box<dyn Debug> = Box::new(());
510 let r: Arc<dyn Debug> = Arc::from(b);
512 assert_eq!(format!("{r:?}"), "()");
517 let v = vec![1, 2, 3];
518 let r: Arc<[u32]> = Arc::from(v);
520 assert_eq!(&r[..], [1, 2, 3]);
527 let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::MAX);
528 let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
530 assert!(r1.clone().downcast::<u32>().is_err());
532 let r1i32 = r1.downcast::<i32>();
533 assert!(r1i32.is_ok());
534 assert_eq!(r1i32.unwrap(), Arc::new(i32::MAX));
536 assert!(r2.clone().downcast::<i32>().is_err());
538 let r2str = r2.downcast::<&'static str>();
539 assert!(r2str.is_ok());
540 assert_eq!(r2str.unwrap(), Arc::new("abc"));
544 fn test_array_from_slice() {
545 let v = vec![1, 2, 3];
546 let r: Arc<[u32]> = Arc::from(v);
548 let a: Result<Arc<[u32; 3]>, _> = r.clone().try_into();
551 let a: Result<Arc<[u32; 2]>, _> = r.clone().try_into();
556 fn test_arc_cyclic_with_zero_refs() {
558 inner: Weak<ZeroRefs>,
560 let zero_refs = Arc::new_cyclic(|inner| {
561 assert_eq!(inner.strong_count(), 0);
562 assert!(inner.upgrade().is_none());
563 ZeroRefs { inner: Weak::new() }
566 assert_eq!(Arc::strong_count(&zero_refs), 1);
567 assert_eq!(Arc::weak_count(&zero_refs), 0);
568 assert_eq!(zero_refs.inner.strong_count(), 0);
569 assert_eq!(zero_refs.inner.weak_count(), 0);
573 fn test_arc_new_cyclic_one_ref() {
577 let one_ref = Arc::new_cyclic(|inner| {
578 assert_eq!(inner.strong_count(), 0);
579 assert!(inner.upgrade().is_none());
580 OneRef { inner: inner.clone() }
583 assert_eq!(Arc::strong_count(&one_ref), 1);
584 assert_eq!(Arc::weak_count(&one_ref), 1);
586 let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap();
587 assert!(Arc::ptr_eq(&one_ref, &one_ref2));
589 assert_eq!(Arc::strong_count(&one_ref), 2);
590 assert_eq!(Arc::weak_count(&one_ref), 1);
594 fn test_arc_cyclic_two_refs() {
596 inner1: Weak<TwoRefs>,
597 inner2: Weak<TwoRefs>,
599 let two_refs = Arc::new_cyclic(|inner| {
600 assert_eq!(inner.strong_count(), 0);
601 assert!(inner.upgrade().is_none());
603 let inner1 = inner.clone();
604 let inner2 = inner1.clone();
606 TwoRefs { inner1, inner2 }
609 assert_eq!(Arc::strong_count(&two_refs), 1);
610 assert_eq!(Arc::weak_count(&two_refs), 2);
612 let two_refs1 = Weak::upgrade(&two_refs.inner1).unwrap();
613 assert!(Arc::ptr_eq(&two_refs, &two_refs1));
615 let two_refs2 = Weak::upgrade(&two_refs.inner2).unwrap();
616 assert!(Arc::ptr_eq(&two_refs, &two_refs2));
618 assert_eq!(Arc::strong_count(&two_refs), 3);
619 assert_eq!(Arc::weak_count(&two_refs), 2);