Class: ConsistentHashing::Ring

Inherits:
Object
  • Object
show all
Defined in:
lib/ch/ring.rb

Instance Method Summary collapse

Constructor Details

#initializeRing

Returns a new instance of Ring.



6
7
8
# File 'lib/ch/ring.rb', line 6

def initialize
  @tree = AVLTree.new
end

Instance Method Details

#add_node(node, position = nil) ⇒ Object

a node can be inserted into multiple positions



11
12
13
14
15
# File 'lib/ch/ring.rb', line 11

def add_node(node, position=nil)
  position ||= hash_for_key(node)

  @tree[position] = node
end

#delete_node(node) ⇒ Object



21
22
23
# File 'lib/ch/ring.rb', line 21

def delete_node(node)
  @tree.each_key { |key| @tree.delete(key) if @tree[key] == node }
end

#delete_node_at_position(position) ⇒ Object



17
18
19
# File 'lib/ch/ring.rb', line 17

def delete_node_at_position(position)
  @tree.delete(position)
end

#hash_for_key(key) ⇒ Object



41
42
43
# File 'lib/ch/ring.rb', line 41

def hash_for_key(key)
  Digest::SHA1.hexdigest(key.to_s).hex
end

#node_for_key(key) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/ch/ring.rb', line 25

def node_for_key(key)
  return nil if @tree.empty?
  key = hash_for_key(key)
  _, value = @tree.next_gte_pair(key)
  _, value = @tree.minimum_pair unless value
  value
end

#nodesObject



33
34
35
# File 'lib/ch/ring.rb', line 33

def nodes
  @tree.values.uniq
end

#positionsObject



37
38
39
# File 'lib/ch/ring.rb', line 37

def positions
  @tree.keys
end