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
//! The two value widths: `u64` and `[u64; 4]`.
use std::fmt;
use std::hash::Hash;
use crate::error::{Error, Result};
mod sealed {
pub trait Sealed {}
impl Sealed for u64 {}
impl Sealed for [u64; 4] {}
}
/// A fixed-width value to search: `u64` for 64 bits, or `[u64; 4]` for 256 bits.
///
/// A 256-bit value is four 64-bit words, most significant first: word 0 holds the first 16 hex
/// digits of its hex form. The trait is sealed; the crate implements it for these two types only.
pub trait Value: Copy + Eq + Ord + Hash + fmt::Debug + Send + Sync + 'static + sealed::Sealed {
/// The width in bits: 64 or 256.
const BITS: u32;
/// The width in 64-bit words: 1 or 4.
const WORDS: usize;
/// The Hamming distance to another value: how many bits differ.
fn distance(&self, other: &Self) -> u32;
/// Word `index` of the value, most significant first.
///
/// # Panics
///
/// Panics if `index` isn't below [`WORDS`](Self::WORDS).
fn word(&self, index: usize) -> u64;
/// The value from its words, most significant first.
///
/// # Panics
///
/// Panics if `words` doesn't hold exactly [`WORDS`](Self::WORDS) words.
fn from_words(words: &[u64]) -> Self;
/// Whether every bit is 0.
fn is_zero(&self) -> bool;
/// The value as lower-case hex, most significant digit first: 16 or 64 digits.
fn to_hex(&self) -> String {
let mut hex = String::with_capacity(Self::WORDS * 16);
for index in 0..Self::WORDS {
use fmt::Write;
let _ = write!(hex, "{:016x}", self.word(index));
}
hex
}
/// Read a value from hex, most significant digit first, in either case.
///
/// # Errors
///
/// [`Error::InvalidHex`] if the string isn't exactly 16 or 64 hex digits, as the width needs.
fn from_hex(hex: &str) -> Result<Self> {
let expected = Self::WORDS * 16;
if hex.len() != expected || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(Error::InvalidHex { expected });
}
let mut words = [0u64; 4];
for (index, word) in words.iter_mut().take(Self::WORDS).enumerate() {
*word = u64::from_str_radix(&hex[index * 16..index * 16 + 16], 16)
.map_err(|_| Error::InvalidHex { expected })?;
}
Ok(Self::from_words(&words[..Self::WORDS]))
}
/// Append the value to `out` as an unsigned little-endian integer: 8 or 32 bytes, least
/// significant byte first. This is how a snapshot file stores it.
fn write_le(&self, out: &mut Vec<u8>) {
for index in (0..Self::WORDS).rev() {
out.extend_from_slice(&self.word(index).to_le_bytes());
}
}
/// Read a value written by [`write_le`](Self::write_le).
///
/// # Panics
///
/// Panics if `bytes` isn't exactly 8 or 32 bytes, as the width needs.
fn read_le(bytes: &[u8]) -> Self {
assert_eq!(bytes.len(), Self::WORDS * 8, "a value is {} bytes", Self::WORDS * 8);
let mut words = [0u64; 4];
for (index, chunk) in bytes.as_chunks::<8>().0.iter().enumerate() {
let word = u64::from_le_bytes(*chunk);
words[Self::WORDS - 1 - index] = word;
}
Self::from_words(&words[..Self::WORDS])
}
}
impl Value for u64 {
const BITS: u32 = 64;
const WORDS: usize = 1;
fn distance(&self, other: &Self) -> u32 {
(self ^ other).count_ones()
}
#[track_caller]
fn word(&self, index: usize) -> u64 {
assert_eq!(index, 0, "a 64-bit value has one word");
*self
}
#[track_caller]
fn from_words(words: &[u64]) -> Self {
assert_eq!(words.len(), 1, "a 64-bit value has one word");
words[0]
}
fn is_zero(&self) -> bool {
*self == 0
}
}
impl Value for [u64; 4] {
const BITS: u32 = 256;
const WORDS: usize = 4;
fn distance(&self, other: &Self) -> u32 {
self.iter().zip(other).map(|(a, b)| (a ^ b).count_ones()).sum()
}
#[track_caller]
fn word(&self, index: usize) -> u64 {
self[index]
}
#[track_caller]
fn from_words(words: &[u64]) -> Self {
words.try_into().expect("a 256-bit value has four words")
}
fn is_zero(&self) -> bool {
*self == [0; 4]
}
}