Skip to main content

ketama_hash_ring/ring/
impl.rs

1use super::*;
2
3/// Default construction for [`ConsistentHashRing`].
4impl<N> Default for ConsistentHashRing<N> {
5    /// Creates an empty ring with [`DEFAULT_VIRTUAL_NODES`] virtual nodes per unit weight.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Empty consistent hash ring.
10    fn default() -> Self {
11        Self::new(DEFAULT_VIRTUAL_NODES)
12    }
13}
14
15/// Core ring management and lookup operations for [`ConsistentHashRing`].
16impl<N> ConsistentHashRing<N> {
17    /// Creates an empty consistent hash ring with `virtual_nodes` virtual slots per unit weight.
18    ///
19    /// # Arguments
20    ///
21    /// - `usize` - Virtual nodes per weight unit (clamped to `>= 1`).
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Empty ring.
26    pub fn new(virtual_nodes: usize) -> Self {
27        Self {
28            virtual_nodes: virtual_nodes.max(1),
29            nodes: Vec::new(),
30            ring_hashes: Vec::new(),
31            ring_nodes: Vec::new(),
32        }
33    }
34
35    /// Returns the number of physical nodes currently in the ring.
36    ///
37    /// # Returns
38    ///
39    /// - `usize` - Count of physical nodes.
40    #[inline(always)]
41    pub fn len(&self) -> usize {
42        let Self { nodes, .. } = self;
43        nodes.len()
44    }
45
46    /// Returns whether the ring has zero physical nodes.
47    ///
48    /// # Returns
49    ///
50    /// - `bool` - `true` when empty.
51    #[inline(always)]
52    pub fn is_empty(&self) -> bool {
53        self.len() == 0
54    }
55
56    /// Returns the total number of virtual points on the hash ring.
57    ///
58    /// # Returns
59    ///
60    /// - `usize` - Virtual ring entry count.
61    #[inline(always)]
62    pub fn virtual_len(&self) -> usize {
63        let Self { ring_hashes, .. } = self;
64        ring_hashes.len()
65    }
66
67    /// Branchless lower-bound binary search over sorted `ring_hashes`.
68    ///
69    /// # Arguments
70    ///
71    /// - `&[u64]` - Sorted virtual-node hashes.
72    /// - `u64` - Target key hash.
73    ///
74    /// # Returns
75    ///
76    /// - `usize` - First index where `hashes[idx] >= target`, or `hashes.len()`.
77    #[inline(always)]
78    fn lower_bound(hashes: &[u64], target: u64) -> usize {
79        let mut size: usize = hashes.len();
80        let mut base: usize = 0;
81        while size > 1 {
82            let half: usize = size >> 1;
83            let mid: usize = base + half;
84            let cmp: bool = unsafe { *hashes.get_unchecked(mid) < target };
85            base = if cmp { mid } else { base };
86            size -= half;
87        }
88        base + usize::from(unsafe { *hashes.get_unchecked(base) < target })
89    }
90
91    /// Inserts or replaces a physical node with unit weight (`1`).
92    ///
93    /// # Arguments
94    ///
95    /// - `S` - Stable node identifier string.
96    /// - `N` - Node payload value.
97    pub fn add_node<S>(&mut self, id: S, value: N)
98    where
99        S: Into<String>,
100    {
101        self.add_weighted_node(id, value, 1);
102    }
103
104    /// Inserts or replaces a physical node with an explicit relative `weight` (`>= 1`).
105    ///
106    /// # Arguments
107    ///
108    /// - `S` - Stable node identifier string.
109    /// - `N` - Node payload value.
110    /// - `usize` - Positive weight scaling virtual node count.
111    pub fn add_weighted_node<S>(&mut self, id: S, value: N, weight: usize)
112    where
113        S: Into<String>,
114    {
115        let id_str: String = id.into();
116        let effective_weight: usize = weight.max(1);
117        let Self { nodes, .. } = self;
118        if let Some(existing) = nodes.iter_mut().find(|n: &&mut RingNode<N>| n.id == id_str) {
119            let same_weight: bool = existing.weight == effective_weight;
120            existing.value = value;
121            existing.weight = effective_weight;
122            if !same_weight {
123                self.rebuild_ring();
124            }
125            return;
126        }
127        let node_idx: usize = nodes.len();
128        nodes.push(RingNode {
129            id: id_str,
130            weight: effective_weight,
131            value,
132        });
133        self.merge_new_node(node_idx);
134    }
135
136    /// Removes the physical node matching `id` if present.
137    ///
138    /// # Arguments
139    ///
140    /// - `&str` - Node identifier to remove.
141    ///
142    /// # Returns
143    ///
144    /// - `Option<N>` - The removed node payload, or `None` if absent.
145    pub fn remove_node(&mut self, id: &str) -> Option<N> {
146        let Self { nodes, .. } = self;
147        let pos: usize = nodes.iter().position(|n: &RingNode<N>| n.id == id)?;
148        let removed: RingNode<N> = nodes.swap_remove(pos);
149        self.rebuild_ring();
150        Some(removed.value)
151    }
152
153    /// Resolves the primary physical node responsible for `key`.
154    ///
155    /// # Arguments
156    ///
157    /// - `&[u8]` - Key bytes to route.
158    ///
159    /// # Returns
160    ///
161    /// - `Option<&N>` - Borrowed reference to the owning node, or `None` if empty.
162    #[inline]
163    pub fn get(&self, key: &[u8]) -> Option<&N> {
164        let Self {
165            nodes,
166            ring_hashes,
167            ring_nodes,
168            ..
169        } = self;
170        if ring_hashes.is_empty() {
171            return None;
172        }
173        let target: u64 = hash_bytes(key);
174        let idx: usize = Self::lower_bound(ring_hashes, target);
175        let slot: usize = if idx == ring_hashes.len() { 0 } else { idx };
176        let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
177        nodes.get(node_idx).map(|n: &RingNode<N>| &n.value)
178    }
179
180    /// Resolves up to `count` distinct physical nodes clockwise around the ring for `key`.
181    ///
182    /// # Arguments
183    ///
184    /// - `&[u8]` - Key bytes to route.
185    /// - `usize` - Desired number of distinct replica nodes.
186    ///
187    /// # Returns
188    ///
189    /// - `Vec<&N>` - Up to `count.min(self.len())` distinct nodes in preference order.
190    pub fn get_replicas(&self, key: &[u8], count: usize) -> Vec<&N> {
191        let Self {
192            nodes,
193            ring_hashes,
194            ring_nodes,
195            ..
196        } = self;
197        let node_count: usize = nodes.len();
198        let wanted: usize = count.min(node_count);
199        let ring_len: usize = ring_hashes.len();
200        if wanted == 0 || ring_len == 0 {
201            return Vec::new();
202        }
203        let target: u64 = hash_bytes(key);
204        let start_raw: usize = Self::lower_bound(ring_hashes, target);
205        let mut slot: usize = if start_raw == ring_len { 0 } else { start_raw };
206        let mut out: Vec<&N> = Vec::with_capacity(wanted);
207        if node_count <= 256 {
208            let mut seen: [u64; 4] = [0u64; 4];
209            let mut visited: usize = 0;
210            while visited < ring_len && out.len() < wanted {
211                let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
212                let word: &mut u64 = unsafe { seen.get_unchecked_mut(node_idx >> 6) };
213                let bit: u64 = 1u64 << (node_idx & 63);
214                if (*word & bit) == 0 {
215                    *word |= bit;
216                    out.push(unsafe { &nodes.get_unchecked(node_idx).value });
217                }
218                slot += 1;
219                if slot == ring_len {
220                    slot = 0;
221                }
222                visited += 1;
223            }
224            return out;
225        }
226        let mut seen: HashSet<usize> = HashSet::with_capacity(wanted);
227        let mut visited: usize = 0;
228        while visited < ring_len && out.len() < wanted {
229            let node_idx: usize = unsafe { *ring_nodes.get_unchecked(slot) as usize };
230            if seen.insert(node_idx) {
231                out.push(&nodes[node_idx].value);
232            }
233            slot += 1;
234            if slot == ring_len {
235                slot = 0;
236            }
237            visited += 1;
238        }
239        out
240    }
241
242    /// Incrementally merges virtual points for one newly appended physical node into the sorted ring.
243    ///
244    /// # Arguments
245    ///
246    /// - `usize` - Index of the newly appended node in `self.nodes`.
247    fn merge_new_node(&mut self, node_idx: usize) {
248        let Self {
249            virtual_nodes,
250            nodes,
251            ring_hashes,
252            ring_nodes,
253        } = self;
254        let node: &RingNode<N> = &nodes[node_idx];
255        let vcount: usize = node.weight.saturating_mul(*virtual_nodes);
256        let id_bytes: &[u8] = node.id.as_bytes();
257        let mut new_points: Vec<u64> = Vec::with_capacity(vcount);
258        for v in 0..vcount {
259            new_points.push(hash_bytes_seeded(id_bytes, (v as u64).wrapping_add(1)));
260        }
261        new_points.sort_unstable();
262        let old_len: usize = ring_hashes.len();
263        let node_u32: u32 = node_idx as u32;
264        if old_len == 0 {
265            *ring_hashes = new_points;
266            *ring_nodes = vec![node_u32; vcount];
267            return;
268        }
269        let total: usize = old_len + vcount;
270        let mut merged_hashes: Vec<u64> = Vec::with_capacity(total);
271        let mut merged_nodes: Vec<u32> = Vec::with_capacity(total);
272        let mut i: usize = 0;
273        let mut j: usize = 0;
274        while i < old_len && j < vcount {
275            let oh: u64 = ring_hashes[i];
276            let nh: u64 = new_points[j];
277            if oh <= nh {
278                merged_hashes.push(oh);
279                merged_nodes.push(ring_nodes[i]);
280                i += 1;
281            } else {
282                merged_hashes.push(nh);
283                merged_nodes.push(node_u32);
284                j += 1;
285            }
286        }
287        if i < old_len {
288            merged_hashes.extend_from_slice(&ring_hashes[i..]);
289            merged_nodes.extend_from_slice(&ring_nodes[i..]);
290        } else if j < vcount {
291            merged_hashes.extend_from_slice(&new_points[j..]);
292            merged_nodes.resize(total, node_u32);
293        }
294        *ring_hashes = merged_hashes;
295        *ring_nodes = merged_nodes;
296    }
297
298    /// Rebuilds and sorts all virtual node hash points across physical nodes.
299    fn rebuild_ring(&mut self) {
300        let Self {
301            virtual_nodes,
302            nodes,
303            ring_hashes,
304            ring_nodes,
305        } = self;
306        let total_vnodes: usize = nodes
307            .iter()
308            .map(|n: &RingNode<N>| n.weight.saturating_mul(*virtual_nodes))
309            .sum();
310        let mut pairs: Vec<(u64, u32)> = Vec::with_capacity(total_vnodes);
311        for (node_idx, node) in nodes.iter().enumerate() {
312            let vcount: usize = node.weight.saturating_mul(*virtual_nodes);
313            let id_bytes: &[u8] = node.id.as_bytes();
314            let node_u32: u32 = node_idx as u32;
315            for v in 0..vcount {
316                let point: u64 = hash_bytes_seeded(id_bytes, (v as u64).wrapping_add(1));
317                pairs.push((point, node_u32));
318            }
319        }
320        pairs.sort_unstable_by_key(|(h, idx): &(u64, u32)| (*h, *idx));
321        ring_hashes.clear();
322        ring_nodes.clear();
323        ring_hashes.reserve(pairs.len());
324        ring_nodes.reserve(pairs.len());
325        for (h, idx) in pairs {
326            ring_hashes.push(h);
327            ring_nodes.push(idx);
328        }
329    }
330}