File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -25,3 +25,4 @@ in a controlled repository now.
25
25
* ` addy.rs ` : trait def/impl example
26
26
* ` bno-salad.rs ` : trait salad example from Blandy and Orendorff
27
27
* ` custom_sum.rs ` : sum example with custom ` Sum ` type
28
+ * ` phantom.rs ` : phantom type example
Original file line number Diff line number Diff line change
1
+ use std:: marker:: PhantomData ;
2
+
3
+ #[ derive( Debug ) ]
4
+ struct Hash < T > {
5
+ h : u128 ,
6
+ p : PhantomData < T > ,
7
+ }
8
+
9
+ unsafe fn hasher ( start : * const u8 , nbytes : usize ) -> u128 {
10
+ let mut result: u128 = 0 ;
11
+ for i in 0 ..nbytes {
12
+ let b = * start. offset ( i as isize ) ;
13
+ result += b as u128 ;
14
+ }
15
+ result
16
+ }
17
+
18
+ impl < T > Hash < T > {
19
+ fn hash ( val : T ) -> Hash < T > {
20
+ let h = unsafe { hasher (
21
+ std:: ptr:: addr_of!( val) as * const u8 ,
22
+ std:: mem:: size_of :: < T > ( ) ,
23
+ ) } ;
24
+ Hash { h, p : PhantomData }
25
+ }
26
+ }
27
+
28
+ fn main ( ) {
29
+ let h1 = Hash :: hash ( ( 0i32 , ) ) ;
30
+ println ! ( "{:?}" , h1) ;
31
+ let h2 = Hash :: hash ( ( 0u32 , ) ) ;
32
+ println ! ( "{:?}" , h2) ;
33
+ // Can't even compare these, since they are of
34
+ // different type.
35
+ // println!("{}", h1 == h2);
36
+ }
You can’t perform that action at this time.
0 commit comments