Skip to content

Commit 99af77b

Browse files
committed
added phantom example
1 parent aedef22 commit 99af77b

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ in a controlled repository now.
2525
* `addy.rs`: trait def/impl example
2626
* `bno-salad.rs`: trait salad example from Blandy and Orendorff
2727
* `custom_sum.rs`: sum example with custom `Sum` type
28+
* `phantom.rs`: phantom type example

phantom.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)