]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/sync/tests.rs
Rollup merge of #105375 - WaffleLapkin:docfix, r=cjgillot
[rust.git] / library / alloc / src / sync / tests.rs
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 {
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)]
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]
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]
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]
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]
105 fn into_from_raw() {
106     let x = Arc::new(Box::new("hello"));
107     let y = x.clone();
108
109     let x_ptr = Arc::into_raw(x);
110     drop(y);
111     unsafe {
112         assert_eq!(**x_ptr, "hello");
113
114         let x = Arc::from_raw(x_ptr);
115         assert_eq!(**x, "hello");
116
117         assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
118     }
119 }
120
121 #[test]
122 fn test_into_from_raw_unsized() {
123     use std::fmt::Display;
124     use std::string::ToString;
125
126     let arc: Arc<str> = Arc::from("foo");
127
128     let ptr = Arc::into_raw(arc.clone());
129     let arc2 = unsafe { Arc::from_raw(ptr) };
130
131     assert_eq!(unsafe { &*ptr }, "foo");
132     assert_eq!(arc, arc2);
133
134     let arc: Arc<dyn Display> = Arc::new(123);
135
136     let ptr = Arc::into_raw(arc.clone());
137     let arc2 = unsafe { Arc::from_raw(ptr) };
138
139     assert_eq!(unsafe { &*ptr }.to_string(), "123");
140     assert_eq!(arc2.to_string(), "123");
141 }
142
143 #[test]
144 fn into_from_weak_raw() {
145     let x = Arc::new(Box::new("hello"));
146     let y = Arc::downgrade(&x);
147
148     let y_ptr = Weak::into_raw(y);
149     unsafe {
150         assert_eq!(**y_ptr, "hello");
151
152         let y = Weak::from_raw(y_ptr);
153         let y_up = Weak::upgrade(&y).unwrap();
154         assert_eq!(**y_up, "hello");
155         drop(y_up);
156
157         assert_eq!(Arc::try_unwrap(x).map(|x| *x), Ok("hello"));
158     }
159 }
160
161 #[test]
162 fn test_into_from_weak_raw_unsized() {
163     use std::fmt::Display;
164     use std::string::ToString;
165
166     let arc: Arc<str> = Arc::from("foo");
167     let weak: Weak<str> = Arc::downgrade(&arc);
168
169     let ptr = Weak::into_raw(weak.clone());
170     let weak2 = unsafe { Weak::from_raw(ptr) };
171
172     assert_eq!(unsafe { &*ptr }, "foo");
173     assert!(weak.ptr_eq(&weak2));
174
175     let arc: Arc<dyn Display> = Arc::new(123);
176     let weak: Weak<dyn Display> = Arc::downgrade(&arc);
177
178     let ptr = Weak::into_raw(weak.clone());
179     let weak2 = unsafe { Weak::from_raw(ptr) };
180
181     assert_eq!(unsafe { &*ptr }.to_string(), "123");
182     assert!(weak.ptr_eq(&weak2));
183 }
184
185 #[test]
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();
190
191     assert!(75 == *Arc::make_mut(&mut cow0));
192     assert!(75 == *Arc::make_mut(&mut cow1));
193     assert!(75 == *Arc::make_mut(&mut cow2));
194
195     *Arc::make_mut(&mut cow0) += 1;
196     *Arc::make_mut(&mut cow1) += 2;
197     *Arc::make_mut(&mut cow2) += 3;
198
199     assert!(76 == *cow0);
200     assert!(77 == *cow1);
201     assert!(78 == *cow2);
202
203     // none should point to the same backing memory
204     assert!(*cow0 != *cow1);
205     assert!(*cow0 != *cow2);
206     assert!(*cow1 != *cow2);
207 }
208
209 #[test]
210 fn test_cowarc_clone_unique2() {
211     let mut cow0 = Arc::new(75);
212     let cow1 = cow0.clone();
213     let cow2 = cow1.clone();
214
215     assert!(75 == *cow0);
216     assert!(75 == *cow1);
217     assert!(75 == *cow2);
218
219     *Arc::make_mut(&mut cow0) += 1;
220     assert!(76 == *cow0);
221     assert!(75 == *cow1);
222     assert!(75 == *cow2);
223
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);
229 }
230
231 #[test]
232 fn test_cowarc_clone_weak() {
233     let mut cow0 = Arc::new(75);
234     let cow1_weak = Arc::downgrade(&cow0);
235
236     assert!(75 == *cow0);
237     assert!(75 == *cow1_weak.upgrade().unwrap());
238
239     *Arc::make_mut(&mut cow0) += 1;
240
241     assert!(76 == *cow0);
242     assert!(cow1_weak.upgrade().is_none());
243 }
244
245 #[test]
246 fn test_live() {
247     let x = Arc::new(5);
248     let y = Arc::downgrade(&x);
249     assert!(y.upgrade().is_some());
250 }
251
252 #[test]
253 fn test_dead() {
254     let x = Arc::new(5);
255     let y = Arc::downgrade(&x);
256     drop(x);
257     assert!(y.upgrade().is_none());
258 }
259
260 #[test]
261 fn weak_self_cyclic() {
262     struct Cycle {
263         x: Mutex<Option<Weak<Cycle>>>,
264     }
265
266     let a = Arc::new(Cycle { x: Mutex::new(None) });
267     let b = Arc::downgrade(&a.clone());
268     *a.x.lock().unwrap() = Some(b);
269
270     // hopefully we don't double-free (or leak)...
271 }
272
273 #[test]
274 fn drop_arc() {
275     let mut canary = atomic::AtomicUsize::new(0);
276     let x = Arc::new(Canary(&mut canary as *mut atomic::AtomicUsize));
277     drop(x);
278     assert!(canary.load(Acquire) == 1);
279 }
280
281 #[test]
282 fn drop_arc_weak() {
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);
287     drop(arc);
288     assert!(canary.load(Acquire) == 1);
289     drop(arc_weak);
290 }
291
292 #[test]
293 fn test_strong_count() {
294     let a = Arc::new(0);
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);
301     drop(w);
302     drop(a);
303     assert!(Arc::strong_count(&b) == 1);
304     let c = b.clone();
305     assert!(Arc::strong_count(&b) == 2);
306     assert!(Arc::strong_count(&c) == 2);
307 }
308
309 #[test]
310 fn test_weak_count() {
311     let a = Arc::new(0);
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);
317     let x = w.clone();
318     assert!(Arc::weak_count(&a) == 2);
319     drop(w);
320     drop(x);
321     assert!(Arc::strong_count(&a) == 1);
322     assert!(Arc::weak_count(&a) == 0);
323     let c = a.clone();
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);
329
330     drop(a);
331     drop(c);
332     drop(d);
333 }
334
335 #[test]
336 fn show_arc() {
337     let a = Arc::new(5);
338     assert_eq!(format!("{a:?}"), "5");
339 }
340
341 // Make sure deriving works with Arc<T>
342 #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Debug, Default)]
343 struct Foo {
344     inner: Arc<i32>,
345 }
346
347 #[test]
348 fn test_unsized() {
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());
352     drop(x);
353     assert!(y.upgrade().is_none());
354 }
355
356 #[test]
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};
360
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);
364     drop(x);
365
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.
370     drop(y);
371 }
372
373 #[test]
374 fn test_from_owned() {
375     let foo = 123;
376     let foo_arc = Arc::from(foo);
377     assert!(123 == *foo_arc);
378 }
379
380 #[test]
381 fn test_new_weak() {
382     let foo: Weak<usize> = Weak::new();
383     assert!(foo.upgrade().is_none());
384 }
385
386 #[test]
387 fn test_ptr_eq() {
388     let five = Arc::new(5);
389     let same_five = five.clone();
390     let other_five = Arc::new(5);
391
392     assert!(Arc::ptr_eq(&five, &same_five));
393     assert!(!Arc::ptr_eq(&five, &other_five));
394 }
395
396 #[test]
397 #[cfg_attr(target_os = "emscripten", ignore)]
398 fn test_weak_count_locked() {
399     let mut a = Arc::new(atomic::AtomicBool::new(false));
400     let a2 = a.clone();
401     let t = thread::spawn(move || {
402         // Miri is too slow
403         let count = if cfg!(miri) { 1000 } else { 1000000 };
404         for _i in 0..count {
405             Arc::get_mut(&mut a);
406         }
407         a.store(true, SeqCst);
408     });
409
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();
415     }
416     t.join().unwrap();
417 }
418
419 #[test]
420 fn test_from_str() {
421     let r: Arc<str> = Arc::from("foo");
422
423     assert_eq!(&r[..], "foo");
424 }
425
426 #[test]
427 fn test_copy_from_slice() {
428     let s: &[u32] = &[1, 2, 3];
429     let r: Arc<[u32]> = Arc::from(s);
430
431     assert_eq!(&r[..], [1, 2, 3]);
432 }
433
434 #[test]
435 fn test_clone_from_slice() {
436     #[derive(Clone, Debug, Eq, PartialEq)]
437     struct X(u32);
438
439     let s: &[X] = &[X(1), X(2), X(3)];
440     let r: Arc<[X]> = Arc::from(s);
441
442     assert_eq!(&r[..], s);
443 }
444
445 #[test]
446 #[should_panic]
447 fn test_clone_from_slice_panic() {
448     use std::string::{String, ToString};
449
450     struct Fail(u32, String);
451
452     impl Clone for Fail {
453         fn clone(&self) -> Fail {
454             if self.0 == 2 {
455                 panic!();
456             }
457             Fail(self.0, self.1.clone())
458         }
459     }
460
461     let s: &[Fail] =
462         &[Fail(0, "foo".to_string()), Fail(1, "bar".to_string()), Fail(2, "baz".to_string())];
463
464     // Should panic, but not cause memory corruption
465     let _r: Arc<[Fail]> = Arc::from(s);
466 }
467
468 #[test]
469 fn test_from_box() {
470     let b: Box<u32> = Box::new(123);
471     let r: Arc<u32> = Arc::from(b);
472
473     assert_eq!(*r, 123);
474 }
475
476 #[test]
477 fn test_from_box_str() {
478     use std::string::String;
479
480     let s = String::from("foo").into_boxed_str();
481     let r: Arc<str> = Arc::from(s);
482
483     assert_eq!(&r[..], "foo");
484 }
485
486 #[test]
487 fn test_from_box_slice() {
488     let s = vec![1, 2, 3].into_boxed_slice();
489     let r: Arc<[u32]> = Arc::from(s);
490
491     assert_eq!(&r[..], [1, 2, 3]);
492 }
493
494 #[test]
495 fn test_from_box_trait() {
496     use std::fmt::Display;
497     use std::string::ToString;
498
499     let b: Box<dyn Display> = Box::new(123);
500     let r: Arc<dyn Display> = Arc::from(b);
501
502     assert_eq!(r.to_string(), "123");
503 }
504
505 #[test]
506 fn test_from_box_trait_zero_sized() {
507     use std::fmt::Debug;
508
509     let b: Box<dyn Debug> = Box::new(());
510     let r: Arc<dyn Debug> = Arc::from(b);
511
512     assert_eq!(format!("{r:?}"), "()");
513 }
514
515 #[test]
516 fn test_from_vec() {
517     let v = vec![1, 2, 3];
518     let r: Arc<[u32]> = Arc::from(v);
519
520     assert_eq!(&r[..], [1, 2, 3]);
521 }
522
523 #[test]
524 fn test_downcast() {
525     use std::any::Any;
526
527     let r1: Arc<dyn Any + Send + Sync> = Arc::new(i32::MAX);
528     let r2: Arc<dyn Any + Send + Sync> = Arc::new("abc");
529
530     assert!(r1.clone().downcast::<u32>().is_err());
531
532     let r1i32 = r1.downcast::<i32>();
533     assert!(r1i32.is_ok());
534     assert_eq!(r1i32.unwrap(), Arc::new(i32::MAX));
535
536     assert!(r2.clone().downcast::<i32>().is_err());
537
538     let r2str = r2.downcast::<&'static str>();
539     assert!(r2str.is_ok());
540     assert_eq!(r2str.unwrap(), Arc::new("abc"));
541 }
542
543 #[test]
544 fn test_array_from_slice() {
545     let v = vec![1, 2, 3];
546     let r: Arc<[u32]> = Arc::from(v);
547
548     let a: Result<Arc<[u32; 3]>, _> = r.clone().try_into();
549     assert!(a.is_ok());
550
551     let a: Result<Arc<[u32; 2]>, _> = r.clone().try_into();
552     assert!(a.is_err());
553 }
554
555 #[test]
556 fn test_arc_cyclic_with_zero_refs() {
557     struct ZeroRefs {
558         inner: Weak<ZeroRefs>,
559     }
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() }
564     });
565
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);
570 }
571
572 #[test]
573 fn test_arc_new_cyclic_one_ref() {
574     struct OneRef {
575         inner: Weak<OneRef>,
576     }
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() }
581     });
582
583     assert_eq!(Arc::strong_count(&one_ref), 1);
584     assert_eq!(Arc::weak_count(&one_ref), 1);
585
586     let one_ref2 = Weak::upgrade(&one_ref.inner).unwrap();
587     assert!(Arc::ptr_eq(&one_ref, &one_ref2));
588
589     assert_eq!(Arc::strong_count(&one_ref), 2);
590     assert_eq!(Arc::weak_count(&one_ref), 1);
591 }
592
593 #[test]
594 fn test_arc_cyclic_two_refs() {
595     struct TwoRefs {
596         inner1: Weak<TwoRefs>,
597         inner2: Weak<TwoRefs>,
598     }
599     let two_refs = Arc::new_cyclic(|inner| {
600         assert_eq!(inner.strong_count(), 0);
601         assert!(inner.upgrade().is_none());
602
603         let inner1 = inner.clone();
604         let inner2 = inner1.clone();
605
606         TwoRefs { inner1, inner2 }
607     });
608
609     assert_eq!(Arc::strong_count(&two_refs), 1);
610     assert_eq!(Arc::weak_count(&two_refs), 2);
611
612     let two_refs1 = Weak::upgrade(&two_refs.inner1).unwrap();
613     assert!(Arc::ptr_eq(&two_refs, &two_refs1));
614
615     let two_refs2 = Weak::upgrade(&two_refs.inner2).unwrap();
616     assert!(Arc::ptr_eq(&two_refs, &two_refs2));
617
618     assert_eq!(Arc::strong_count(&two_refs), 3);
619     assert_eq!(Arc::weak_count(&two_refs), 2);
620 }
621
622 /// Test for Arc::drop bug (https://github.com/rust-lang/rust/issues/55005)
623 #[test]
624 #[cfg(miri)] // relies on Stacked Borrows in Miri
625 fn arc_drop_dereferenceable_race() {
626     // The bug seems to take up to 700 iterations to reproduce with most seeds (tested 0-9).
627     for _ in 0..750 {
628         let arc_1 = Arc::new(());
629         let arc_2 = arc_1.clone();
630         let thread = thread::spawn(|| drop(arc_2));
631         // Spin a bit; makes the race more likely to appear
632         let mut i = 0;
633         while i < 256 {
634             i += 1;
635         }
636         drop(arc_1);
637         thread.join().unwrap();
638     }
639 }