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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
/*!
# Dactyl: Hashing
*/
use std::hash::{
BuildHasherDefault,
Hasher,
};
/// # No-Hash (Passthrough) Hash State.
///
/// Hashing can be expensive, and is totally unnecessary for most numeric or
/// pre-hashed types. (You don't need a hash to tell you that `1_u8` is
/// different than `2_u8`!)
///
/// `NoHash` is a drop in replacement for the standard library's hasher used in
/// [`HashMap`](std::collections::HashMap) and [`HashSet`](std::collections::HashSet) that lets
/// the values speak for themselves (e.g. `hash(13_u16) == 13_u64`), bringing a
/// free performance boost.
///
/// This idea isn't new, but unlike the hashers offered by [`nohash`](https://crates.io/crates/nohash) or [`prehash`](https://crates.io/crates/prehash),
/// `NoHash` does not limit itself to primitives or require any custom trait
/// implementations.
///
/// It "just works" for any type whose [`std::hash::Hash`] implementation writes
/// a single <= 64-bit integer via one of the following:
/// * [`write_i8`](std::hash::Hasher::write_i8)
/// * [`write_i16`](std::hash::Hasher::write_i16)
/// * [`write_i32`](std::hash::Hasher::write_i32)
/// * [`write_i64`](std::hash::Hasher::write_i64)
/// * [`write_isize`](std::hash::Hasher::write_isize) (if the target pointer width is <= 64)
/// * [`write_u8`](std::hash::Hasher::write_u8)
/// * [`write_u16`](std::hash::Hasher::write_u16)
/// * [`write_u32`](std::hash::Hasher::write_u32)
/// * [`write_u64`](std::hash::Hasher::write_u64)
/// * [`write_usize`](std::hash::Hasher::write_usize) (if the target pointer width is <= 64)
///
/// In other words, `NoHash` can always be used for `i8`, `i16`, `i32`, `i64`,
/// `u8`, `u16`, `u32`, `u64`, all their `NonZero` and [`Wrapping`](std::num::Wrapping) counterparts,
/// and any custom types that derive their hashes from one of these types.
///
/// (`isize` and `usize` will work on most platforms too, just not those with
/// monstrous 128-bit pointer widths.)
///
/// ## Examples
///
/// ```
/// use dactyl::NoHash;
/// use std::collections::{HashMap, HashSet};
///
/// let mut set: HashSet<u32, NoHash> = HashSet::default();
/// assert!(set.insert(0_u32));
/// assert!(set.insert(1_u32));
/// assert!(set.insert(2_u32));
/// assert!(! set.insert(2_u32)); // Not unique!
///
/// let mut set: HashMap<i8, &str, NoHash> = HashMap::default();
/// assert_eq!(set.insert(-2_i8, "Hello"), None);
/// assert_eq!(set.insert(-1_i8, "World"), None);
/// assert_eq!(set.insert(0_i8, "How"), None);
/// assert_eq!(set.insert(1_i8, "Are"), None);
/// assert_eq!(set.insert(1_i8, "You?"), Some("Are")); // Not unique!
/// ```
///
/// This can also be used with custom types that implement `Hash` in such a
/// way that only a single specialized `write_*` call occurs.
///
/// ```
/// use dactyl::NoHash;
/// use std::{
/// collections::HashSet,
/// hash::{Hash, Hasher},
/// };
///
/// struct Person {
/// name: String,
/// id: u64,
/// }
///
/// impl Eq for Person {}
///
/// impl Hash for Person {
/// fn hash<H: Hasher>(&self, state: &mut H) {
/// state.write_u64(self.id);
/// // Note: `self.id.hash(state)` would also work because it just
/// // calls `write_u64` under-the-hood.
/// }
/// }
///
/// impl PartialEq for Person {
/// fn eq(&self, b: &Self) -> bool { self.id == b.id }
/// }
///
/// let mut set: HashSet<Person, NoHash> = HashSet::default();
/// assert!(set.insert(Person { name: "Jane".to_owned(), id: 5 }));
/// assert!(set.insert(Person { name: "Joan".to_owned(), id: 6 }));
/// assert!(! set.insert(Person { name: "Jack".to_owned(), id: 6 })); // Duplicate ID.
/// ```
///
/// ## Panics
///
/// `NoHash` does **not** support slices, `i128`, or `u128` as they cannot be
/// losslessly converted to `u64`. If a `Hash` implementation tries to make use
/// of those write methods, it will panic. On 128-bit platforms, attempts to hash
/// `isize` or `usize` will likewise result in a panic.
///
/// `NoHash` will also panic if a `Hash` implementation writes two or more
/// values to the hasher — as a tuple would, for example — but only for `debug`
/// builds. When building in release mode, `NoHash` will simply pass-through
/// the last integer written to it, ignoring everything else.
pub type NoHash = BuildHasherDefault<NoHasher>;
#[derive(Debug, Default, Copy, Clone)]
/// # Passthrough Hasher.
///
/// See [`NoHash`] for usage details.
pub struct NoHasher(u64);
macro_rules! write_unsigned {
($($fn:ident, $ty:ty),+ $(,)?) => ($(
#[inline]
#[doc = concat!("# Write `", stringify!($ty), "`")]
fn $fn(&mut self, val: $ty) {
debug_assert!(self.0 == 0, "cannot call `Hasher::write_*` more than once");
self.0 = val as u64;
}
)+);
}
macro_rules! write_signed {
($($fn:ident, $ty1:ty, $ty2:ty),+ $(,)?) => ($(
#[inline]
#[doc = concat!("# Write `", stringify!($ty1), "`")]
fn $fn(&mut self, val: $ty1) {
debug_assert!(self.0 == 0, "cannot call `Hasher::write_*` more than once");
self.0 = (val as $ty2) as u64;
}
)+);
}
impl Hasher for NoHasher {
#[cold]
/// # Write.
fn write(&mut self, _bytes: &[u8]) {
unimplemented!("NoHash only implements the type-specific write methods (like `write_u16`)");
}
write_unsigned!(
write_u8, u8,
write_u16, u16,
write_u32, u32,
);
write_signed!(
write_i8, i8, u8,
write_i16, i16, u16,
write_i32, i32, u32,
);
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32", target_pointer_width = "64"))]
write_unsigned!(write_usize, usize);
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32", target_pointer_width = "64"))]
write_signed!(write_isize, isize, usize);
#[inline]
/// # Real Write.
fn write_u64(&mut self, val: u64) { self.0 = val; }
#[inline]
/// # Finish.
fn finish(&self) -> u64 { self.0 }
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
collections::HashSet,
num::{
NonZeroU8,
Wrapping,
},
};
#[test]
fn t_nonzero() {
// This just verifies that nonzero types hash the way they're supposed
// to, i.e. as the underlying type.
let mut set: HashSet<NonZeroU8, NoHash> = (1..=u8::MAX).filter_map(NonZeroU8::new).collect();
assert_eq!(set.len(), 255);
assert_eq!(set.insert(NonZeroU8::new(1).unwrap()), false); // Should already be there.
}
#[test]
fn t_wrapping() {
// This just verifies that Wrapping hashes its inner value directly.
let mut set: HashSet<Wrapping<u8>, NoHash> = (0..=u8::MAX).map(Wrapping).collect();
assert_eq!(set.len(), 256);
assert_eq!(set.insert(Wrapping(0)), false); // Should already be there.
}
#[test]
fn t_u8() {
let mut set: HashSet<u8, NoHash> = (0..=u8::MAX).collect();
assert_eq!(set.len(), 256);
assert_eq!(set.insert(0), false); // Should already be there.
let mut set: HashSet<i8, NoHash> = (i8::MIN..=i8::MAX).collect();
assert_eq!(set.len(), 256);
assert_eq!(set.insert(0), false); // Should already be there.
}
#[cfg(not(miri))]
#[test]
fn t_u16() {
let mut set: HashSet<u16, NoHash> = (0..=u16::MAX).collect();
assert_eq!(set.len(), 65_536);
assert_eq!(set.insert(0), false); // Should already be there.
let mut set: HashSet<i16, NoHash> = (i16::MIN..=i16::MAX).collect();
assert_eq!(set.len(), 65_536);
assert_eq!(set.insert(0), false); // Should already be there.
}
macro_rules! sanity_check_signed {
($ty:ty) => (
let mut set: HashSet<$ty, NoHash> = HashSet::default();
assert_eq!(set.insert(<$ty>::MIN), true);
assert_eq!(set.insert(-2), true);
assert_eq!(set.insert(-1), true);
assert_eq!(set.insert(0), true);
assert_eq!(set.insert(1), true);
assert_eq!(set.insert(2), true);
assert_eq!(set.insert(<$ty>::MAX), true);
assert_eq!(set.insert(0), false); // Should already be there.
);
}
macro_rules! sanity_check_unsigned {
($ty:ty) => (
let mut set: HashSet<$ty, NoHash> = HashSet::default();
assert_eq!(set.insert(0), true);
assert_eq!(set.insert(1), true);
assert_eq!(set.insert(2), true);
assert_eq!(set.insert(<$ty>::MAX), true);
assert_eq!(set.insert(0), false); // Should already be there.
);
}
#[cfg(miri)]
#[test]
fn t_u16() {
sanity_check_unsigned!(u16);
sanity_check_signed!(i16);
}
#[test]
fn t_u32() {
sanity_check_unsigned!(u32);
sanity_check_signed!(i32);
}
#[test]
fn t_u64() {
sanity_check_unsigned!(u64);
sanity_check_signed!(i64);
}
#[cfg(any(target_pointer_width = "16", target_pointer_width = "32", target_pointer_width = "64"))]
#[test]
fn t_usize() {
sanity_check_unsigned!(usize);
sanity_check_signed!(isize);
}
#[test]
#[should_panic]
fn t_u128() {
let mut set: HashSet<u128, NoHash> = HashSet::default();
set.insert(0);
}
#[cfg(debug_assertions)]
#[test]
#[should_panic]
fn t_double_write() {
// In debug mode, attempts to write twice will panic.
let mut set: HashSet<(u8, u8), NoHash> = HashSet::default();
set.insert((1_u8, 2_u8));
}
#[cfg(not(debug_assertions))]
#[test]
fn t_double_write() {
// In non-debug mode, the last integer written is used for hashing.
let mut set: HashSet<(u8, u8), NoHash> = HashSet::default();
assert!(set.insert((1_u8, 2_u8)));
assert!(set.insert((1_u8, 3_u8)));
assert!(set.insert((0_u8, 3_u8))); // 3 appears twice.
}
#[test]
#[should_panic]
fn t_write_bytes() {
let mut set: HashSet<&str, NoHash> = HashSet::default();
set.insert("hello");
}
}