ketama-hash-ring 11.1.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::*;

/// Construction and O(1) lookup operations for [`MaglevHash`].
impl<N> MaglevHash<N> {
    /// Builds a Maglev lookup table with [`DEFAULT_MAGLEV_TABLE_SIZE`] slots.
    ///
    /// # Arguments
    ///
    /// - `Vec<(String, N)>` - Named backend nodes `(id, value)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Populated Maglev consistent hash table.
    pub fn new(nodes: Vec<(String, N)>) -> Self {
        Self::with_table_size(nodes, DEFAULT_MAGLEV_TABLE_SIZE)
    }

    /// Builds a Maglev lookup table with a prime table size `>= min_table_size`.
    ///
    /// # Arguments
    ///
    /// - `Vec<(String, N)>` - Named backend nodes `(id, value)`.
    /// - `usize` - Minimum lookup table size (rounded up to the next prime).
    ///
    /// # Returns
    ///
    /// - `Self` - Populated Maglev consistent hash table.
    pub fn with_table_size(nodes: Vec<(String, N)>, min_table_size: usize) -> Self {
        let m: usize = next_prime(min_table_size);
        let lookup: Vec<usize> = Self::populate(&nodes, m);
        Self {
            table_size: m,
            nodes,
            lookup,
        }
    }

    /// Returns the prime lookup table size `M`.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of entries in the Maglev lookup table.
    #[inline(always)]
    pub fn table_size(&self) -> usize {
        let Self { table_size, .. } = self;
        *table_size
    }

    /// Returns the number of backend nodes.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of backend nodes.
    #[inline(always)]
    pub fn len(&self) -> usize {
        let Self { nodes, .. } = self;
        nodes.len()
    }

    /// Returns whether zero backend nodes are configured.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Performs an O(1) Maglev lookup for `key`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Key bytes to route.
    ///
    /// # Returns
    ///
    /// - `Option<&N>` - Selected backend node or `None` if empty.
    #[inline(always)]
    pub fn get(&self, key: &[u8]) -> Option<&N> {
        let Self {
            table_size,
            nodes,
            lookup,
        } = self;
        if nodes.is_empty() || lookup.is_empty() {
            return None;
        }
        let slot: usize = (hash_bytes(key) as usize) % *table_size;
        let idx: usize = lookup[slot];
        nodes.get(idx).map(|(_, v): &(String, N)| v)
    }

    /// Populates the Maglev preference table of prime size `m` across `nodes`.
    ///
    /// # Arguments
    ///
    /// - `&[(String, N)]` - Backend nodes.
    /// - `usize` - Prime table size `m`.
    ///
    /// # Returns
    ///
    /// - `Vec<usize>` - Populated lookup table of length `m` (or empty when `nodes` is empty).
    fn populate(nodes: &[(String, N)], m: usize) -> Vec<usize> {
        let n: usize = nodes.len();
        if n == 0 {
            return Vec::new();
        }
        let mut offsets: Vec<usize> = Vec::with_capacity(n);
        let mut skips: Vec<usize> = Vec::with_capacity(n);
        for (name, _) in nodes {
            let bytes: &[u8] = name.as_bytes();
            let offset: usize = (hash_bytes_seeded(bytes, MAGLEV_SEED_OFFSET) as usize) % m;
            let skip: usize = (hash_bytes_seeded(bytes, MAGLEV_SEED_SKIP) as usize) % (m - 1) + 1;
            offsets.push(offset);
            skips.push(skip);
        }
        let mut next: Vec<usize> = vec![0usize; n];
        let mut entry: Vec<usize> = vec![MAGLEV_EMPTY_SLOT; m];
        let mut filled: usize = 0;
        while filled < m {
            for i in 0..n {
                let mut c: usize = (offsets[i] + next[i] * skips[i]) % m;
                while entry[c] != MAGLEV_EMPTY_SLOT {
                    next[i] += 1;
                    c = (offsets[i] + next[i] * skips[i]) % m;
                }
                entry[c] = i;
                next[i] += 1;
                filled += 1;
                if filled == m {
                    break;
                }
            }
        }
        entry
    }
}