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

/// 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: 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, .. } = self;
        ring.len()
    }

    /// 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) {
            existing.value = value;
            existing.weight = effective_weight;
        } else {
            nodes.push(RingNode {
                id: id_str,
                weight: effective_weight,
                value,
            });
        }
        self.rebuild_ring();
    }

    /// 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, .. } = self;
        if ring.is_empty() {
            return None;
        }
        let target: u64 = hash_bytes(key);
        let idx: usize = ring.partition_point(|(h, _): &(u64, usize)| *h < target);
        let slot: usize = if idx == ring.len() { 0 } else { idx };
        let node_idx: usize = ring[slot].1;
        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, .. } = self;
        let wanted: usize = count.min(nodes.len());
        if wanted == 0 || ring.is_empty() {
            return Vec::new();
        }
        let target: u64 = hash_bytes(key);
        let start: usize = ring.partition_point(|(h, _): &(u64, usize)| *h < target);
        let mut out: Vec<&N> = Vec::with_capacity(wanted);
        let mut seen: HashSet<usize> = HashSet::with_capacity(wanted);
        let ring_len: usize = ring.len();
        let mut step: usize = 0;
        while step < ring_len && out.len() < wanted {
            let slot: usize = (start + step) % ring_len;
            let node_idx: usize = ring[slot].1;
            if seen.insert(node_idx) {
                out.push(&nodes[node_idx].value);
            }
            step += 1;
        }
        out
    }

    /// Rebuilds and sorts all virtual node hash points across physical nodes.
    fn rebuild_ring(&mut self) {
        let Self {
            virtual_nodes,
            nodes,
            ring,
        } = self;
        let total_vnodes: usize = nodes
            .iter()
            .map(|n: &RingNode<N>| n.weight.saturating_mul(*virtual_nodes))
            .sum();
        ring.clear();
        ring.reserve(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();
            for v in 0..vcount {
                let point: u64 = hash_bytes_seeded(id_bytes, (v as u64).wrapping_add(1));
                ring.push((point, node_idx));
            }
        }
        ring.sort_unstable_by_key(|(h, idx): &(u64, usize)| (*h, *idx));
    }
}