Skip to content

Commit ccc4c1a

Browse files
committed
consistent hashing algorithm (untested)
1 parent d1943d5 commit ccc4c1a

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

src/Datastructure/Table/ConsistentHashTable.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,35 @@
3939
class ConsistentHashTable {
4040

4141
private $nodes;
42+
private $ringSize = PHP_INT_MAX;
4243

4344
public function __construct() {
44-
$this->nodes = [];
45+
$this->nodes = new HashTable();
46+
}
47+
48+
public function getNode($key) {
49+
$angle = $this->getAngle($this->getHash($key));
50+
$i = $angle;
51+
52+
while ($i >= 0) {
53+
54+
if ($this->nodes->containsKey($i)) {
55+
return $this->nodes->get($i);
56+
}
57+
$i--;
58+
}
59+
60+
return null;
61+
}
62+
63+
public function addNode($key, $node) {
64+
$angle = $this->getAngle($this->getHash($key));
65+
$this->nodes->put($angle, $node);
66+
}
67+
68+
private function getAngle(int $hash): int {
69+
// (1633428562 / 10^10) * 360
70+
return ($hash / $this->ringSize) * 360;
4571
}
4672

4773
/**

0 commit comments

Comments
 (0)