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
use num::basic::signeds::PrimitiveSigned;
use num::basic::unsigneds::PrimitiveUnsigned;
use num::logic::traits::{CheckedHammingDistance, CountOnes, HammingDistance};
fn hamming_distance_unsigned<T: PrimitiveUnsigned>(x: T, y: T) -> u64 {
CountOnes::count_ones(x ^ y)
}
macro_rules! impl_hamming_distance_unsigned {
($t:ident) => {
impl HammingDistance<$t> for $t {
#[inline]
fn hamming_distance(self, other: $t) -> u64 {
hamming_distance_unsigned(self, other)
}
}
};
}
apply_to_unsigneds!(impl_hamming_distance_unsigned);
fn checked_hamming_distance_signed<T: PrimitiveSigned>(x: T, y: T) -> Option<u64> {
if (x >= T::ZERO) == (y >= T::ZERO) {
Some(CountOnes::count_ones(x ^ y))
} else {
None
}
}
macro_rules! impl_checked_hamming_distance_signed {
($t:ident) => {
impl CheckedHammingDistance<$t> for $t {
#[inline]
fn checked_hamming_distance(self, other: $t) -> Option<u64> {
checked_hamming_distance_signed(self, other)
}
}
};
}
apply_to_signeds!(impl_checked_hamming_distance_signed);