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