| 1 |
use core::hash::Hasher; |
| 2 |
use siphasher::sip::SipHasher13; |
| 3 |
|
| 4 |
use crate::{HashKey, PhfHash, PortableSipHasher}; |
| 5 |
|
| 6 |
/// `key` is from `phf_generator::ptrhash::HashState`. |
| 7 |
#[inline] |
| 8 |
pub fn hash<T: ?Sized + PhfHash>(x: &T, key: &HashKey) -> u64 { |
| 9 |
let mut hasher = PortableSipHasher::new(SipHasher13::new_with_keys(0, *key)); |
| 10 |
x.phf_hash(&mut hasher); |
| 11 |
hasher.finish() |
| 12 |
} |
| 13 |
|
| 14 |
#[inline] |
| 15 |
pub fn hash_pilot(seed: u64, pilot: u8) -> u64 { |
| 16 |
const C: u64 = 0x517cc1b727220a95; |
| 17 |
|
| 18 |
C.wrapping_mul(seed ^ u64::from(pilot)) |
| 19 |
} |
| 20 |
|
| 21 |
/// Return an index into `phf_generator::ptrhash::HashState::map`. |
| 22 |
/// |
| 23 |
/// * `seed` is from `phf_generator::ptrhash::HashState::seed`. |
| 24 |
/// * `hash` is from `hash()` in this crate. |
| 25 |
/// * `pilots` is from `phf_generator::ptrhash::HashState::pilots`. |
| 26 |
/// * `remap` is from `phf_generator::ptrhash::HashState::remap`. |
| 27 |
/// * `len` is the length of `phf_generator::ptrhash::HashState::map`. |
| 28 |
#[inline] |
| 29 |
pub fn get_index(seed: u64, hash: u64, pilots: &[u8], remap: &[u32], len: usize) -> u32 { |
| 30 |
let pilots_len = pilots.len() as u32; |
| 31 |
let slots_len = (len + remap.len()) as u32; |
| 32 |
|
| 33 |
let bucket = fast_reduct32(low(hash), pilots_len) as usize; |
| 34 |
let pilot_hash = hash_pilot(seed, pilots[bucket]); |
| 35 |
let index = fast_reduct32(high(hash) ^ high(pilot_hash) ^ low(pilot_hash), slots_len); |
| 36 |
let index = index as usize; |
| 37 |
|
| 38 |
if index < len { |
| 39 |
index as u32 |
| 40 |
} else { |
| 41 |
remap[index - len] |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ |
| 46 |
#[inline] |
| 47 |
pub fn fast_reduct32(x: u32, limit: u32) -> u32 { |
| 48 |
(((x as u64) * (limit as u64)) >> 32) as u32 |
| 49 |
} |
| 50 |
|
| 51 |
#[inline] |
| 52 |
fn low(v: u64) -> u32 { |
| 53 |
v as u32 |
| 54 |
} |
| 55 |
|
| 56 |
#[inline] |
| 57 |
fn high(v: u64) -> u32 { |
| 58 |
(v >> 32) as u32 |
| 59 |
} |