8 import java.util.zip.CRC32
9 import scala.collection.mutable.ArrayBuffer
10 import scala.collection.mutable.Map
16 var sortedKeys: List[Long] = List()
17 var cluster = new ArrayBuffer[Redis]
18 val ring = Map[Long, Redis]()
20 // Adds the node to the hashRing
21 // including a number of replicas.
22 def addNode(node: Redis) = {
24 (1 to replicas).foreach{ replica =>
25 val key = calculateChecksum(node+":"+replica)
27 sortedKeys = sortedKeys ::: List(key)
29 sortedKeys = sortedKeys.sort(_ < _)
32 // get the node in the hash ring for this key
33 def getNode(key: String) = getNodePos(key)._1
35 def getNodePos(key: String): (Redis, Int) = {
36 val crc = calculateChecksum(key)
37 val idx = binarySearch(crc)
38 (ring(sortedKeys(idx)), idx)
41 // TODO this should perform a Bynary search
42 def binarySearch(value: Long): Int = {
43 var upper = (sortedKeys.length -1)
48 while(lower <= upper){
49 idx = (lower + upper) / 2
50 comp = sortedKeys(idx)
52 if(comp == value) { return idx }
53 if(comp < value) { upper = idx -1 }
54 if(comp > value) { lower = idx +1 }
59 // Computes the CRC-32 of the given String
60 def calculateChecksum(value: String): Long = {
61 val checksum = new CRC32
62 checksum.update(value.getBytes)