]> git.lizzy.rs Git - rust.git/blob - tests/run-pass-noseed/ptr_int_casts.rs
c279024f35eabd442390b329f48867f0f1b191d4
[rust.git] / tests / run-pass-noseed / ptr_int_casts.rs
1 use std::mem;
2 use std::ptr;
3
4 fn eq_ref<T>(x: &T, y: &T) -> bool {
5     x as *const _ == y as *const _
6 }
7
8 fn f() -> i32 { 42 }
9
10 fn main() {
11     // int-ptr-int
12     assert_eq!(1 as *const i32 as usize, 1);
13     assert_eq!((1 as *const i32).wrapping_offset(4) as usize, 1 + 4*4);
14
15     // negative overflowing wrapping_offset (going through memory because
16     // this used to trigger an ICE on 32bit)
17     let val = &mut ptr::null();
18     *val = (1 as *const u8).wrapping_offset(-4);
19     assert_eq!(*val as usize, usize::max_value() - 2);
20
21     {   // ptr-int-ptr
22         let x = 13;
23         let mut y = &x as &_ as *const _ as usize;
24         y += 13;
25         y -= 13;
26         let y = y as *const _;
27         assert!(eq_ref(&x, unsafe { &*y }));
28     }
29
30     {   // fnptr-int-fnptr
31         let x : fn() -> i32 = f;
32         let y : *mut u8 = unsafe { mem::transmute(x as fn() -> i32) };
33         let mut y = y as usize;
34         y += 13;
35         y -= 13;
36         let x : fn() -> i32 = unsafe { mem::transmute(y as *mut u8) };
37         assert_eq!(x(), 42);
38     }
39
40     // involving types other than usize
41     assert_eq!((-1i32) as usize as *const i32 as usize, (-1i32) as usize);
42 }