1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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);
}
}
}