1- fn f ( ) -> i32 { 42 }
1+ #![ feature( ptr_offset_from) ]
2+ use std:: { mem, ptr} ;
23
34fn main ( ) {
5+ test_offset_from ( ) ;
6+ test_vec_into_iter ( ) ;
7+ ptr_arith_offset ( ) ;
8+ ptr_arith_offset_overflow ( ) ;
9+ ptr_offset ( ) ;
10+ }
11+
12+ fn test_offset_from ( ) { unsafe {
13+ let buf = [ 0u32 ; 4 ] ;
14+
15+ let x = buf. as_ptr ( ) as * const u8 ;
16+ let y = x. offset ( 12 ) ;
17+
18+ assert_eq ! ( y. offset_from( x) , 12 ) ;
19+ assert_eq ! ( x. offset_from( y) , -12 ) ;
20+ assert_eq ! ( ( y as * const u32 ) . offset_from( x as * const u32 ) , 12 /4 ) ;
21+ assert_eq ! ( ( x as * const u32 ) . offset_from( y as * const u32 ) , -12 /4 ) ;
22+
23+ let x = ( ( ( x as usize ) * 2 ) / 2 ) as * const u8 ;
24+ assert_eq ! ( y. offset_from( x) , 12 ) ;
25+ assert_eq ! ( x. offset_from( y) , -12 ) ;
26+ } }
27+
28+ // This also internally uses offset_from.
29+ fn test_vec_into_iter ( ) {
30+ let v = Vec :: < i32 > :: new ( ) ;
31+ let i = v. into_iter ( ) ;
32+ i. size_hint ( ) ;
33+ }
34+
35+ fn ptr_arith_offset ( ) {
36+ let v = [ 1i16 , 2 ] ;
37+ let x = & v as * const [ i16 ] as * const i16 ;
38+ let x = x. wrapping_offset ( 1 ) ;
39+ assert_eq ! ( unsafe { * x } , 2 ) ;
40+ }
41+
42+ fn ptr_arith_offset_overflow ( ) {
43+ let v = [ 1i16 , 2 ] ;
44+ let x = & mut ptr:: null ( ) ; // going through memory as there are more sanity checks along that path
45+ * x = v. as_ptr ( ) . wrapping_offset ( 1 ) ; // ptr to the 2nd element
46+ // Adding 2*isize::max and then 1 is like substracting 1
47+ * x = x. wrapping_offset ( isize:: MAX ) ;
48+ * x = x. wrapping_offset ( isize:: MAX ) ;
49+ * x = x. wrapping_offset ( 1 ) ;
50+ assert_eq ! ( unsafe { * * x } , 1 ) ;
51+ }
52+
53+ fn ptr_offset ( ) {
54+ fn f ( ) -> i32 { 42 }
55+
456 let v = [ 1i16 , 2 ] ;
557 let x = & v as * const [ i16 ; 2 ] as * const i16 ;
658 let x = unsafe { x. offset ( 1 ) } ;
@@ -10,7 +62,7 @@ fn main() {
1062 unsafe {
1163 let p = f as fn ( ) -> i32 as usize ;
1264 let x = ( p as * mut u32 ) . offset ( 0 ) as usize ;
13- let f: fn ( ) -> i32 = std :: mem:: transmute ( x) ;
65+ let f: fn ( ) -> i32 = mem:: transmute ( x) ;
1466 assert_eq ! ( f( ) , 42 ) ;
1567 }
1668}
0 commit comments