@@ -44,49 +44,21 @@ def remove_node(node)
44
44
45
45
# get the node in the hash ring for this key
46
46
def get_node ( key )
47
- get_node_pos ( key ) [ 0 ]
48
- end
49
-
50
- def get_node_pos ( key )
51
- return [ nil , nil ] if @ring . empty?
52
-
53
47
hash = hash_for ( key )
54
- idx = HashRing . binary_search ( @sorted_keys , hash )
55
- [ @ring [ @sorted_keys [ idx ] ] , idx ]
48
+ idx = binary_search ( @sorted_keys , hash )
49
+ @ring [ @sorted_keys [ idx ] ]
56
50
end
57
51
58
52
def iter_nodes ( key )
59
53
return [ nil , nil ] if @ring . empty?
60
54
61
- _ , pos = get_node_pos ( key )
55
+ crc = hash_for ( key )
56
+ pos = binary_search ( @sorted_keys , crc )
62
57
@ring . size . times do |n |
63
58
yield @ring [ @sorted_keys [ ( pos + n ) % @ring . size ] ]
64
59
end
65
60
end
66
61
67
- # Find the closest index in HashRing with value <= the given value
68
- def self . binary_search ( ary , value )
69
- upper = ary . size - 1
70
- lower = 0
71
- idx = 0
72
-
73
- while lower <= upper
74
- idx = ( lower + upper ) / 2
75
- comp = ary [ idx ] <=> value
76
-
77
- if comp == 0
78
- return idx
79
- elsif comp > 0
80
- upper = idx - 1
81
- else
82
- lower = idx + 1
83
- end
84
- end
85
-
86
- upper = ary . size - 1 if upper < 0
87
- upper
88
- end
89
-
90
62
private
91
63
92
64
def hash_for ( key )
@@ -96,5 +68,22 @@ def hash_for(key)
96
68
def server_hash_for ( key )
97
69
Digest ::MD5 . digest ( key ) . unpack1 ( "L>" )
98
70
end
71
+
72
+ # Find the closest index in HashRing with value <= the given value
73
+ def binary_search ( ary , value )
74
+ upper = ary . size
75
+ lower = 0
76
+
77
+ while lower < upper
78
+ mid = ( lower + upper ) / 2
79
+ if ary [ mid ] > value
80
+ upper = mid
81
+ else
82
+ lower = mid + 1
83
+ end
84
+ end
85
+
86
+ upper - 1
87
+ end
99
88
end
100
89
end
0 commit comments