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::*;

/// Default construction for [`ConsistentHashRing`].
impl<N> Default for ConsistentHashRing<N> {
    /// Creates an empty ring with [`DEFAULT_VIRTUAL_NODES`] virtual nodes per unit weight.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty consistent hash ring.
    fn default() -> Self {
        Self::new(DEFAULT_VIRTUAL_NODES)
    }
}

/// Core ring management and lookup operations for [`ConsistentHashRing`].
impl<N> ConsistentHashRing<N> {
    /// Creates an empty consistent hash ring with `virtual_nodes` virtual slots per unit weight.
    ///
    /// # Arguments
    ///
    /// - `usize` - Virtual nodes per weight unit (clamped to `>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Empty ring.
    pub fn new(virtual_nodes: usize) -> Self {
        Self {
            virtual_nodes: virtual_nodes.max(1),
            nodes: Vec::new(),
            ring_hashes: Vec::new(),
            ring_nodes: Vec::new(),
        }
    }

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

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

    /// Returns the total number of virtual points on the hash ring.
    ///
    /// # Returns
    ///
    /// - `usize` - Virtual ring entry count.
    #[inline(always)]
    pub fn virtual_len(&self) -> usize {
        let Self { ring_hashes, .. } = self;
        ring_hashes.len()
    }

    /// Branchless lower-bound binary search over sorted `ring_hashes`.
    ///
    /// # Arguments
    ///
    /// - `&[u64]` - Sorted virtual-node hashes.
    /// - `u64` - Target key hash.
    ///
    /// # Returns
    ///
    /// - `usize` - First index where `hashes[idx] >= target`, or `hashes.len()`.
    #[inline(always)]
    fn lower_bound(hashes: &[u64], target: u64) -> usize {
        let mut size: usize = hashes.len();
        let mut base: usize = 0;
        while size > 1 {
            let half: usize = size >> 1;
            let mid: usize = base + half;
            let cmp: bool = unsafe { *hashes.get_unchecked(mid) < target };
            base = if cmp { mid } else { base };
            size -= half;
        }
        base + usize::from(unsafe { *hashes.get_unchecked(base) < target })
    }

    /// Inserts or replaces a physical node with unit weight (`1`).
    ///
    /// # Arguments
    ///
    /// - `S` - Stable node identifier string.
    /// - `N` - Node payload value.
    pub fn add_node<S>(&mut self, id: S, value: N)
    where
        S: Into<String>,
    {
        self.add_weighted_node(id, value, 1);
    }

    /// Inserts or replaces a physical node with an explicit relative `weight` (`>= 1`).
    ///
    /// # Arguments
    ///
    /// - `S` - Stable node identifier string.
    /// - `N` - Node payload value.
    /// - `usize` - Positive weight scaling virtual node count.
    pub fn add_weighted_node<S>(&mut self, id: S, value: N, weight: usize)
    where
        S: Into<String>,
    {
        let id_str: String = id.into();
        let effective_weight: usize = weight.max(1);
        let Self { nodes, .. } = self;
        if let Some(existing) = nodes.iter_mut().find(|n: &&mut RingNode<N>| n.id == id_str) {
            let same_weight: bool = existing.weight == effective_weight;
            existing.value = value;
            existing.weight = effective_weight;
            if !same_weight {
                self.rebuild_ring();
            }
            return;
        }
        let node_idx: usize = nodes.len();
        nodes.push(RingNode {
            id: id_str,
            weight: effective_weight,
            value,
        });
        self.merge_new_node(node_idx);
    }

    /// Removes the physical node matching `id` if present.
    ///
    /// # Arguments
    ///
    /// - `&str` - Node identifier to remove.
    ///
    /// # Returns
    ///
    /// - `Option<N>` - The removed node payload, or `None` if absent.
    pub fn remove_node(&mut self, id: &str) -> Option<N> {
        let Self { nodes, .. } = self;
        let pos: usize = nodes.iter().position(|n: &RingNode<N>| n.id == id)?;
        let removed: RingNode<N> = nodes.swap_remove(pos);
        self.rebuild_ring();
        Some(removed.value)
    }

    /// Resolves the primary physical node responsible for `key`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Key bytes to route.
    ///
    /// # Returns
    ///
    /// - `Option<&N>` - Borrowed reference to the owning node, or `None` if empty.
    #[inline]
    pub fn get(&self, key: &[u8]) -> Option<&N> {
        let Self {
            nodes,
            ring_hashes,
            ring_nodes,
            ..
        } = self;
        if ring_hashes.is_empty() {
            return None;
        }
        let target: u64 = hash_bytes(key);
        let idx: usize = Self::lower_bound(ring_hashes, target);
        let slot: usize = if idx == ring_hashes.len() { 0 } else { idx };
        let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
        nodes.get(node_idx).map(|n: &RingNode<N>| &n.value)
    }

    /// Resolves up to `count` distinct physical nodes clockwise around the ring for `key`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Key bytes to route.
    /// - `usize` - Desired number of distinct replica nodes.
    ///
    /// # Returns
    ///
    /// - `Vec<&N>` - Up to `count.min(self.len())` distinct nodes in preference order.
    pub fn get_replicas(&self, key: &[u8], count: usize) -> Vec<&N> {
        let Self {
            nodes,
            ring_hashes,
            ring_nodes,
            ..
        } = self;
        let node_count: usize = nodes.len();
        let wanted: usize = count.min(node_count);
        let ring_len: usize = ring_hashes.len();
        if wanted == 0 || ring_len == 0 {
            return Vec::new();
        }
        let target: u64 = hash_bytes(key);
        let start_raw: usize = Self::lower_bound(ring_hashes, target);
        let mut slot: usize = if start_raw == ring_len { 0 } else { start_raw };
        let mut out: Vec<&N> = Vec::with_capacity(wanted);
        if node_count <= 256 {
            let mut seen: [u64; 4] = [0u64; 4];
            let mut visited: usize = 0;
            while visited < ring_len && out.len() < wanted {
                let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
                let word: &mut u64 = unsafe { seen.get_unchecked_mut(node_idx >> 6) };
                let bit: u64 = 1u64 << (node_idx & 63);
                if (*word & bit) == 0 {
                    *word |= bit;
                    out.push(unsafe { &nodes.get_unchecked(node_idx).value });
                }
                slot += 1;
                if slot == ring_len {
                    slot = 0;
                }
                visited += 1;
            }
            return out;
        }
        let mut seen: HashSet<usize> = HashSet::with_capacity(wanted);
        let mut visited: usize = 0;
        while visited < ring_len && out.len() < wanted {
            let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
            if seen.insert(node_idx) {
                out.push(&nodes[node_idx].value);
            }
            slot += 1;
            if slot == ring_len {
                slot = 0;
            }
            visited += 1;
        }
        out
    }

    /// Incrementally merges virtual points for one newly appended physical node into the sorted ring.
    ///
    /// # Arguments
    ///
    /// - `usize` - Index of the newly appended node in `self.nodes`.
    fn merge_new_node(&mut self, node_idx: usize) {
        let Self {
            virtual_nodes,
            nodes,
            ring_hashes,
            ring_nodes,
        } = self;
        let node: &RingNode<N> = &nodes[node_idx];
        let vcount: usize = node.weight.saturating_mul(*virtual_nodes);
        let id_bytes: &[u8] = node.id.as_bytes();
        let mut new_points: Vec<u64> = Vec::with_capacity(vcount);
        for v in 0..vcount {
            new_points.push(hash_bytes_seeded(id_bytes, (v as u64).wrapping_add(1)));
        }
        new_points.sort_unstable();
        let old_len: usize = ring_hashes.len();
        let node_u32: u32 = node_idx as u32;
        if old_len == 0 {
            *ring_hashes = new_points;
            *ring_nodes = vec![node_u32; vcount];
            return;
        }
        let total: usize = old_len + vcount;
        let mut merged_hashes: Vec<u64> = Vec::with_capacity(total);
        let mut merged_nodes: Vec<u32> = Vec::with_capacity(total);
        let mut i: usize = 0;
        let mut j: usize = 0;
        while i < old_len && j < vcount {
            let oh: u64 = ring_hashes[i];
            let nh: u64 = new_points[j];
            if oh <= nh {
                merged_hashes.push(oh);
                merged_nodes.push(ring_nodes[i]);
                i += 1;
            } else {
                merged_hashes.push(nh);
                merged_nodes.push(node_u32);
                j += 1;
            }
        }
        if i < old_len {
            merged_hashes.extend_from_slice(&ring_hashes[i..]);
            merged_nodes.extend_from_slice(&ring_nodes[i..]);
        } else if j < vcount {
            merged_hashes.extend_from_slice(&new_points[j..]);
            merged_nodes.resize(total, node_u32);
        }
        *ring_hashes = merged_hashes;
        *ring_nodes = merged_nodes;
    }

    /// Rebuilds and sorts all virtual node hash points across physical nodes.
    fn rebuild_ring(&mut self) {
        let Self {
            virtual_nodes,
            nodes,
            ring_hashes,
            ring_nodes,
        } = self;
        let total_vnodes: usize = nodes
            .iter()
            .map(|n: &RingNode<N>| n.weight.saturating_mul(*virtual_nodes))
            .sum();
        let mut pairs: Vec<(u64, u32)> = Vec::with_capacity(total_vnodes);
        for (node_idx, node) in nodes.iter().enumerate() {
            let vcount: usize = node.weight.saturating_mul(*virtual_nodes);
            let id_bytes: &[u8] = node.id.as_bytes();
            let node_u32: u32 = node_idx as u32;
            for v in 0..vcount {
                let point: u64 = hash_bytes_seeded(id_bytes, (v as u64).wrapping_add(1));
                pairs.push((point, node_u32));
            }
        }
        pairs.sort_unstable_by_key(|(h, idx): &(u64, u32)| (*h, *idx));
        ring_hashes.clear();
        ring_nodes.clear();
        ring_hashes.reserve(pairs.len());
        ring_nodes.reserve(pairs.len());
        for (h, idx) in pairs {
            ring_hashes.push(h);
            ring_nodes.push(idx);
        }
    }
}