1 use core
::alloc
::Layout
;
2 use core
::mem
::size_of
;
3 use core
::ptr
::{self, NonNull}
;
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
)));
17 fn layout_round_up_to_align_edge_cases() {
18 const MAX_SIZE
: usize = isize::MAX
as usize;
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
{
29 Layout
::from_size_align(size
, align
).is_ok(),
30 size
.next_multiple_of(align
) <= MAX_SIZE
,
37 fn layout_array_edge_cases() {
39 for_type
::<[i32; 0b10101]>();
40 for_type
::<[u8; 0b1010101]>();
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());
46 const MAX_SIZE
: usize = isize::MAX
as usize;
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());
54 assert_eq
!(Layout
::array
::<T
>(n
).is_ok(), n
* size_of
::<T
>() <= MAX_SIZE
);
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) }");
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.
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
);