-
Notifications
You must be signed in to change notification settings - Fork 46
/
util.go
56 lines (48 loc) · 1.19 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package chord
import (
"bytes"
"crypto/sha1"
"errors"
"math/rand"
"time"
)
var (
ERR_NO_SUCCESSOR = errors.New("cannot find successor")
ERR_NODE_EXISTS = errors.New("node with id already exists")
ERR_KEY_NOT_FOUND = errors.New("key not found")
)
func isEqual(a, b []byte) bool {
return bytes.Compare(a, b) == 0
}
func isPowerOfTwo(num int) bool {
return (num != 0) && ((num & (num - 1)) == 0)
}
func randStabilize(min, max time.Duration) time.Duration {
r := rand.Float64()
return time.Duration((r * float64(max-min)) + float64(min))
}
// check if key is between a and b, right inclusive
func betweenRightIncl(key, a, b []byte) bool {
return between(key, a, b) || bytes.Equal(key, b)
}
// Checks if a key is STRICTLY between two ID's exclusively
func between(key, a, b []byte) bool {
switch bytes.Compare(a, b) {
case 1:
return bytes.Compare(a, key) == -1 || bytes.Compare(b, key) >= 0
case -1:
return bytes.Compare(a, key) == -1 && bytes.Compare(b, key) >= 0
case 0:
return bytes.Compare(a, key) != 0
}
return false
}
// For testing
func GetHashID(key string) []byte {
h := sha1.New()
if _, err := h.Write([]byte(key)); err != nil {
return nil
}
val := h.Sum(nil)
return val
}