-
Notifications
You must be signed in to change notification settings - Fork 781
/
util.go
32 lines (28 loc) · 855 Bytes
/
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
package ring
import (
"math/rand"
"sort"
"time"
)
// GenerateTokens make numTokens random tokens, none of which clash
// with takenTokens. Assumes takenTokens is sorted.
func GenerateTokens(numTokens int, takenTokens []uint32) []uint32 {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
tokens := []uint32{}
for i := 0; i < numTokens; {
candidate := r.Uint32()
j := sort.Search(len(takenTokens), func(i int) bool {
return takenTokens[i] >= candidate
})
if j < len(takenTokens) && takenTokens[j] == candidate {
continue
}
tokens = append(tokens, candidate)
i++
}
return tokens
}
type sortableUint32 []uint32
func (ts sortableUint32) Len() int { return len(ts) }
func (ts sortableUint32) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
func (ts sortableUint32) Less(i, j int) bool { return ts[i] < ts[j] }