1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#[inline(always)]
pub fn read_int(buf: &[u8]) -> u64 {
let ptr = buf.as_ptr();
unsafe {
match buf.len() {
1 => *ptr as u64,
2 => (*(ptr as *const u16)).to_le() as u64,
3 => {
let a = (*(ptr as *const u16)).to_le() as u64;
let b = *ptr.offset(2) as u64;
a | (b << 16)
},
4 => (*(ptr as *const u32)).to_le() as u64,
5 => {
let a = (*(ptr as *const u32)).to_le() as u64;
let b = *ptr.offset(4) as u64;
a | (b << 32)
},
6 => {
let a = (*(ptr as *const u32)).to_le() as u64;
let b = (*(ptr.offset(4) as *const u16)).to_le() as u64;
a | (b << 32)
},
7 => {
let a = (*(ptr as *const u32)).to_le() as u64;
let b = (*(ptr.offset(4) as *const u16)).to_le() as u64;
let c = *ptr.offset(6) as u64;
a | (b << 32) | (c << 48)
},
_ => 0,
}
}
}
#[inline(always)]
pub unsafe fn read_u64(ptr: *const u8) -> u64 {
#[cfg(target_pointer_width = "32")]
{
(*(ptr as *const u32)).to_le() as u64 | ((*(ptr.offset(4) as *const u32)).to_le() as u64) << 32
}
#[cfg(target_pointer_width = "64")]
{
(*(ptr as *const u64)).to_le()
}
}
pub fn diffuse(mut x: u64) -> u64 {
x = x.wrapping_mul(0x6eed0e9da4d94a4f);
let a = x >> 32;
let b = x >> 60;
x ^= a >> b;
x = x.wrapping_mul(0x6eed0e9da4d94a4f);
x
}
pub fn undiffuse(mut x: u64) -> u64 {
x = x.wrapping_mul(0x2f72b4215a3d8caf);
let a = x >> 32;
let b = x >> 60;
x ^= a >> b;
x = x.wrapping_mul(0x2f72b4215a3d8caf);
x
}
#[cfg(test)]
mod tests {
use super::*;
fn diffuse_test(x: u64, y: u64) {
assert_eq!(diffuse(x), y);
assert_eq!(x, undiffuse(y));
assert_eq!(undiffuse(diffuse(x)), x);
}
#[test]
fn read_int_() {
assert_eq!(read_int(&[2, 3]), 770);
assert_eq!(read_int(&[3, 2]), 515);
assert_eq!(read_int(&[3, 2, 5]), 328195);
}
#[test]
fn read_u64_() {
unsafe {
assert_eq!(read_u64([1, 0, 0, 0, 0, 0, 0, 0].as_ptr()), 1);
assert_eq!(read_u64([2, 1, 0, 0, 0, 0, 0, 0].as_ptr()), 258);
}
}
#[test]
fn diffuse_test_vectors() {
diffuse_test(94203824938, 17289265692384716055);
diffuse_test(0xDEADBEEF, 12110756357096144265);
diffuse_test(0, 0);
diffuse_test(1, 15197155197312260123);
diffuse_test(2, 1571904453004118546);
diffuse_test(3, 16467633989910088880);
}
}