]> git.lizzy.rs Git - rust.git/blob - src/test/ui/consts/const-eval/ub-nonnull.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / test / ui / consts / const-eval / ub-nonnull.rs
1 #![feature(rustc_attrs, const_transmute)]
2 #![allow(const_err, invalid_value)] // make sure we cannot allow away the errors tested here
3
4 use std::mem;
5 use std::ptr::NonNull;
6 use std::num::{NonZeroU8, NonZeroUsize};
7
8 const NON_NULL: NonNull<u8> = unsafe { mem::transmute(1usize) };
9 const NON_NULL_PTR: NonNull<u8> = unsafe { mem::transmute(&1) };
10
11 const NULL_PTR: NonNull<u8> = unsafe { mem::transmute(0usize) };
12 //~^ ERROR it is undefined behavior to use this value
13
14 #[deny(const_err)] // this triggers a `const_err` so validation does not even happen
15 const OUT_OF_BOUNDS_PTR: NonNull<u8> = { unsafe {
16     let ptr: &[u8; 256] = mem::transmute(&0u8); // &0 gets promoted so it does not dangle
17     // Use address-of-element for pointer arithmetic. This could wrap around to NULL!
18     let out_of_bounds_ptr = &ptr[255]; //~ ERROR any use of this value will cause an error
19     mem::transmute(out_of_bounds_ptr)
20 } };
21
22 const NULL_U8: NonZeroU8 = unsafe { mem::transmute(0u8) };
23 //~^ ERROR it is undefined behavior to use this value
24 const NULL_USIZE: NonZeroUsize = unsafe { mem::transmute(0usize) };
25 //~^ ERROR it is undefined behavior to use this value
26
27 #[repr(C)]
28 union MaybeUninit<T: Copy> {
29     uninit: (),
30     init: T,
31 }
32 const UNINIT: NonZeroU8 = unsafe { MaybeUninit { uninit: () }.init };
33 //~^ ERROR it is undefined behavior to use this value
34
35 // Also test other uses of rustc_layout_scalar_valid_range_start
36
37 #[rustc_layout_scalar_valid_range_start(10)]
38 #[rustc_layout_scalar_valid_range_end(30)]
39 struct RestrictedRange1(u32);
40 const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) };
41 //~^ ERROR it is undefined behavior to use this value
42
43 #[rustc_layout_scalar_valid_range_start(30)]
44 #[rustc_layout_scalar_valid_range_end(10)]
45 struct RestrictedRange2(u32);
46 const BAD_RANGE2: RestrictedRange2 = unsafe { RestrictedRange2(20) };
47 //~^ ERROR it is undefined behavior to use this value
48
49 fn main() {}