ketama-hash-ring 11.2.0

Zero-dependency consistent hashing suite implementing Jump Consistent Hash, weighted Ketama virtual-node rings, and Google Maglev O(1) lookup tables.
Documentation
use super::*;

/// Computes a fast 64-bit hash of a byte slice with a seed using FNV-1a + SplitMix64 finalization.
///
/// # Arguments
///
/// - `&[u8]` - Key bytes to hash.
/// - `u64` - Seed value for independent hash functions.
///
/// # Returns
///
/// - `u64` - Well-avalanched 64-bit digest.
#[inline(always)]
pub fn hash_bytes_seeded(bytes: &[u8], seed: u64) -> u64 {
    let mut h: u64 = FNV_OFFSET_BASIS ^ seed;
    for &byte in bytes {
        h ^= u64::from(byte);
        h = h.wrapping_mul(FNV_PRIME);
    }
    h = h.wrapping_add(SPLITMIX_INC);
    h = (h ^ (h >> 30)).wrapping_mul(SPLITMIX_M1);
    h = (h ^ (h >> 27)).wrapping_mul(SPLITMIX_M2);
    h ^ (h >> 31)
}

/// Computes a fast 64-bit hash of a byte slice with zero seed.
///
/// # Arguments
///
/// - `&[u8]` - Key bytes to hash.
///
/// # Returns
///
/// - `u64` - 64-bit digest.
#[inline(always)]
pub fn hash_bytes(bytes: &[u8]) -> u64 {
    hash_bytes_seeded(bytes, 0)
}

/// Hashes any [`Hash`] key into a 64-bit digest suitable for consistent hashing.
///
/// # Arguments
///
/// - `&K` - Key reference implementing [`Hash`].
///
/// # Returns
///
/// - `u64` - 64-bit hash digest.
#[inline(always)]
pub fn hash_key<K>(key: &K) -> u64
where
    K: Hash + ?Sized,
{
    let mut hasher: DefaultHasher = DefaultHasher::new();
    key.hash(&mut hasher);
    hasher.finish()
}

/// Computes the Lamping-Veach Jump Consistent Hash mapping `key` to `[0, buckets)`.
///
/// Zero-allocation, O(ln N) time, and mathematically minimal key movement when `buckets` changes.
/// Returns `0` when `buckets <= 1`.
///
/// # Arguments
///
/// - `u64` - 64-bit hashed key.
/// - `u32` - Total number of buckets.
///
/// # Returns
///
/// - `u32` - Selected bucket index in `0..buckets.max(1)`.
#[inline(always)]
pub fn jump_consistent_hash(mut key: u64, buckets: u32) -> u32 {
    if buckets <= 1 {
        return 0;
    }
    let limit: i64 = i64::from(buckets);
    let mut b: i64 = -1;
    let mut j: i64 = 0;
    while j < limit {
        b = j;
        key = key.wrapping_mul(JUMP_MULTIPLIER).wrapping_add(1);
        let denom: f64 = ((key >> 33) + 1) as f64;
        j = (((b + 1) as f64) * (JUMP_SCALE / denom)) as i64;
    }
    b as u32
}