]> git.lizzy.rs Git - rust.git/blob - library/core/tests/const_ptr.rs
Rollup merge of #82246 - jesusprubio:add-long-explanation-e0549, r=GuillaumeGomez
[rust.git] / library / core / tests / const_ptr.rs
1 // Aligned to two bytes
2 const DATA: [u16; 2] = [u16::from_ne_bytes([0x01, 0x23]), u16::from_ne_bytes([0x45, 0x67])];
3
4 const fn unaligned_ptr() -> *const u16 {
5     // Since DATA.as_ptr() is aligned to two bytes, adding 1 byte to that produces an unaligned *const u16
6     unsafe { (DATA.as_ptr() as *const u8).add(1) as *const u16 }
7 }
8
9 #[test]
10 fn read() {
11     use core::ptr;
12
13     const FOO: i32 = unsafe { ptr::read(&42 as *const i32) };
14     assert_eq!(FOO, 42);
15
16     const ALIGNED: i32 = unsafe { ptr::read_unaligned(&42 as *const i32) };
17     assert_eq!(ALIGNED, 42);
18
19     const UNALIGNED_PTR: *const u16 = unaligned_ptr();
20
21     const UNALIGNED: u16 = unsafe { ptr::read_unaligned(UNALIGNED_PTR) };
22     assert_eq!(UNALIGNED, u16::from_ne_bytes([0x23, 0x45]));
23 }
24
25 #[test]
26 fn const_ptr_read() {
27     const FOO: i32 = unsafe { (&42 as *const i32).read() };
28     assert_eq!(FOO, 42);
29
30     const ALIGNED: i32 = unsafe { (&42 as *const i32).read_unaligned() };
31     assert_eq!(ALIGNED, 42);
32
33     const UNALIGNED_PTR: *const u16 = unaligned_ptr();
34
35     const UNALIGNED: u16 = unsafe { UNALIGNED_PTR.read_unaligned() };
36     assert_eq!(UNALIGNED, u16::from_ne_bytes([0x23, 0x45]));
37 }
38
39 #[test]
40 fn mut_ptr_read() {
41     const FOO: i32 = unsafe { (&42 as *const i32 as *mut i32).read() };
42     assert_eq!(FOO, 42);
43
44     const ALIGNED: i32 = unsafe { (&42 as *const i32 as *mut i32).read_unaligned() };
45     assert_eq!(ALIGNED, 42);
46
47     const UNALIGNED_PTR: *mut u16 = unaligned_ptr() as *mut u16;
48
49     const UNALIGNED: u16 = unsafe { UNALIGNED_PTR.read_unaligned() };
50     assert_eq!(UNALIGNED, u16::from_ne_bytes([0x23, 0x45]));
51 }