]> git.proxmox.com Git - rustc.git/blob - library/core/tests/alloc.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / library / core / tests / alloc.rs
1 use core::alloc::Layout;
2 use core::mem::size_of;
3 use core::ptr::{self, NonNull};
4
5 #[test]
6 fn const_unchecked_layout() {
7 const SIZE: usize = 0x2000;
8 const ALIGN: usize = 0x1000;
9 const LAYOUT: Layout = unsafe { Layout::from_size_align_unchecked(SIZE, ALIGN) };
10 const DANGLING: NonNull<u8> = LAYOUT.dangling();
11 assert_eq!(LAYOUT.size(), SIZE);
12 assert_eq!(LAYOUT.align(), ALIGN);
13 assert_eq!(Some(DANGLING), NonNull::new(ptr::invalid_mut(ALIGN)));
14 }
15
16 #[test]
17 fn layout_round_up_to_align_edge_cases() {
18 const MAX_SIZE: usize = isize::MAX as usize;
19
20 for shift in 0..usize::BITS {
21 let align = 1_usize << shift;
22 let edge = (MAX_SIZE + 1) - align;
23 let low = edge.saturating_sub(10);
24 let high = edge.saturating_add(10);
25 assert!(Layout::from_size_align(low, align).is_ok());
26 assert!(Layout::from_size_align(high, align).is_err());
27 for size in low..=high {
28 assert_eq!(
29 Layout::from_size_align(size, align).is_ok(),
30 size.next_multiple_of(align) <= MAX_SIZE,
31 );
32 }
33 }
34 }
35
36 #[test]
37 fn layout_array_edge_cases() {
38 for_type::<i64>();
39 for_type::<[i32; 0b10101]>();
40 for_type::<[u8; 0b1010101]>();
41
42 // Make sure ZSTs don't lead to divide-by-zero
43 assert_eq!(Layout::array::<()>(usize::MAX).unwrap(), Layout::from_size_align(0, 1).unwrap());
44
45 fn for_type<T>() {
46 const MAX_SIZE: usize = isize::MAX as usize;
47
48 let edge = (MAX_SIZE + 1) / size_of::<T>();
49 let low = edge.saturating_sub(10);
50 let high = edge.saturating_add(10);
51 assert!(Layout::array::<T>(low).is_ok());
52 assert!(Layout::array::<T>(high).is_err());
53 for n in low..=high {
54 assert_eq!(Layout::array::<T>(n).is_ok(), n * size_of::<T>() <= MAX_SIZE);
55 }
56 }
57 }
58
59 #[test]
60 fn layout_debug_shows_log2_of_alignment() {
61 // `Debug` is not stable, but here's what it does right now
62 let layout = Layout::from_size_align(24576, 8192).unwrap();
63 let s = format!("{:?}", layout);
64 assert_eq!(s, "Layout { size: 24576, align: 8192 (1 << 13) }");
65 }
66
67 // Running this normally doesn't do much, but it's also run in Miri, which
68 // will double-check that these are allowed by the validity invariants.
69 #[test]
70 fn layout_accepts_all_valid_alignments() {
71 for align in 0..usize::BITS {
72 let layout = Layout::from_size_align(0, 1_usize << align).unwrap();
73 assert_eq!(layout.align(), 1_usize << align);
74 }
75 }