]> git.lizzy.rs Git - rust.git/blob - library/alloc/tests/boxed.rs
Rollup merge of #91947 - ibraheemdev:io-error-other, r=joshtriplett
[rust.git] / library / alloc / tests / boxed.rs
1 use std::cell::Cell;
2 use std::mem::MaybeUninit;
3 use std::ptr::NonNull;
4
5 #[test]
6 fn uninitialized_zero_size_box() {
7     assert_eq!(
8         &*Box::<()>::new_uninit() as *const _,
9         NonNull::<MaybeUninit<()>>::dangling().as_ptr(),
10     );
11     assert_eq!(
12         Box::<[()]>::new_uninit_slice(4).as_ptr(),
13         NonNull::<MaybeUninit<()>>::dangling().as_ptr(),
14     );
15     assert_eq!(
16         Box::<[String]>::new_uninit_slice(0).as_ptr(),
17         NonNull::<MaybeUninit<String>>::dangling().as_ptr(),
18     );
19 }
20
21 #[derive(Clone, PartialEq, Eq, Debug)]
22 struct Dummy {
23     _data: u8,
24 }
25
26 #[test]
27 fn box_clone_and_clone_from_equivalence() {
28     for size in (0..8).map(|i| 2usize.pow(i)) {
29         let control = vec![Dummy { _data: 42 }; size].into_boxed_slice();
30         let clone = control.clone();
31         let mut copy = vec![Dummy { _data: 84 }; size].into_boxed_slice();
32         copy.clone_from(&control);
33         assert_eq!(control, clone);
34         assert_eq!(control, copy);
35     }
36 }
37
38 /// This test might give a false positive in case the box reallocates,
39 /// but the allocator keeps the original pointer.
40 ///
41 /// On the other hand, it won't give a false negative: If it fails, then the
42 /// memory was definitely not reused.
43 #[test]
44 fn box_clone_from_ptr_stability() {
45     for size in (0..8).map(|i| 2usize.pow(i)) {
46         let control = vec![Dummy { _data: 42 }; size].into_boxed_slice();
47         let mut copy = vec![Dummy { _data: 84 }; size].into_boxed_slice();
48         let copy_raw = copy.as_ptr() as usize;
49         copy.clone_from(&control);
50         assert_eq!(copy.as_ptr() as usize, copy_raw);
51     }
52 }
53
54 #[test]
55 fn box_deref_lval() {
56     let x = Box::new(Cell::new(5));
57     x.set(1000);
58     assert_eq!(x.get(), 1000);
59 }