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