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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#![deny(missing_docs)]
#![cfg_attr(test, feature(test))]
#[cfg(test)]
extern crate test;
use std::ops;
pub mod raw;
#[cfg(test)]
mod tests;
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Hash {
hash: u64,
}
impl Hash {
#[inline]
pub fn new(string: &str) -> Hash {
let string = string.as_bytes();
let mut b = 0;
let first_byte = raw::map_first(*string.get(0).unwrap_or(&0)) as u64;
let mut res = 0;
let mut n = 1u8;
loop {
b += 1;
if n == 0 || b >= string.len() {
break;
}
if let Some(x) = raw::filter(res as u8, string[b]) {
res <<= 8;
res |= x as u64;
n <<= 1;
}
}
Hash {
hash: res | (first_byte << 56),
}
}
}
impl Into<u64> for Hash {
#[inline]
fn into(self) -> u64 {
self.hash
}
}
impl ops::Sub for Hash {
type Output = Difference;
#[inline]
fn sub(self, rhs: Hash) -> Difference {
Difference {
xor: self.hash ^ rhs.hash,
}
}
}
#[derive(Copy, Clone)]
pub struct Difference {
xor: u64,
}
impl Difference {
#[inline]
pub fn dist(self) -> u32 {
(self.xor as u8).count_ones() as u32
+ ((self.xor >> 8 ) as u8).count_ones() as u32 * 2
+ ((self.xor >> 16) as u8).count_ones() as u32 * 3
+ ((self.xor >> 24) as u8).count_ones() as u32 * 5
+ ((self.xor >> 32) as u8).count_ones() as u32 * 8
+ ((self.xor >> 40) as u8).count_ones() as u32 * 13
+ ((self.xor >> 48) as u8).count_ones() as u32 * 21
+ ((self.xor >> 56) as u8).count_ones() as u32 * 34
}
#[inline]
pub fn xor(self) -> u64 {
self.xor
}
#[inline]
pub fn hamming(self) -> u32 {
self.xor.count_ones()
}
#[inline]
pub fn similar(self) -> bool {
self.dist() < 15
}
}
#[deprecated]
pub fn similar(a: &str, b: &str) -> bool {
(Hash::new(a) - Hash::new(b)).similar()
}