lib/consistent_hashing/ring.rb in consistent-hashing-0.0.1 vs lib/consistent_hashing/ring.rb in consistent-hashing-0.1.0
- old
+ new
@@ -1,10 +1,13 @@
require 'digest/md5'
+require 'set'
module ConsistentHashing
+
+ # Public: the hash ring containing all configured nodes
+ #
class Ring
- attr_reader :ring
# Public: returns a new ring object
def initialize(nodes = [], replicas = 3)
@replicas = replicas
@sorted_keys = []
@@ -25,11 +28,11 @@
def add(node)
@replicas.times do |i|
# generate the key of this (virtual) point in the hash
key = hash_key(node, i)
- @ring[key] = node
+ @ring[key] = VirtualPoint.new(node, key)
@sorted_keys << key
end
@sorted_keys.sort!
@@ -48,22 +51,44 @@
end
self
end
- # Public: gets the node for an arbitrary key
+ # Public: gets the point for an arbitrary key
#
#
- def node_for(key)
- return [nil, 0] if @ring.empty?
+ def point_for(key)
+ return nil if @ring.empty?
key = hash_key(key)
@sorted_keys.each do |i|
- return [@ring[i], i] if key <= i
+ return @ring[i] if key <= i
end
- [@ring[@sorted_keys[0]], 0]
+ @ring[@sorted_keys[0]]
+ end
+
+ # Public: gets the node where to store the key
+ #
+ # Returns: the node Object
+ def node_for(key)
+ point_for(key).node
+ end
+
+ # Public: get all nodes in the ring
+ #
+ # Returns: an Array of the nodes in the ring
+ def nodes
+ nodes = points.map { |point| point.node }
+ nodes.uniq
+ end
+
+ # Public: gets all points in the ring
+ #
+ # Returns: an Array of the points in the ring
+ def points
+ @ring.map { |point| point[1] }
end
protected
# Internal: hashes the key
\ No newline at end of file