-
Notifications
You must be signed in to change notification settings - Fork 5
/
ballot.go
69 lines (56 loc) · 1.49 KB
/
ballot.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
57
58
59
60
61
62
63
64
65
66
67
68
69
package BigBFT
import (
"fmt"
"strconv"
"strings"
"github.com/salemmohammed/BigBFT/log"
)
// Ballot is ballot number type combines 32 bits of natual number and 32 bits of node id into uint64
type Ballot uint64
// NewBallot generates ballot number in format <n, zone, node>
func NewBallot(n int, id ID) Ballot {
return Ballot(n<<32 | id.Zone()<<16 | id.Node())
}
func NewBallotFromString(b string) Ballot {
var s, id string
if strings.Contains(b, ".") {
split := strings.SplitN(b, ".", 2)
s = split[0]
id = split[1]
} else {
s = b
}
n, err := strconv.ParseUint(s, 10, 64)
if err != nil {
log.Errorf("Failed to convert counter %s to uint64\n", s)
}
return NewBallot(int(n), ID(id))
}
// N returns first 32 bit of ballot
func (b Ballot) N() int {
return int(uint64(b) >> 32)
}
// ID return node id as last 32 bits of ballot
func (b Ballot) ID() ID {
zone := int(uint32(b) >> 16)
node := int(uint16(b))
return NewID(zone, node)
}
// Next generates the next ballot number given node id
func (b *Ballot) Next(id ID) {
*b = NewBallot(b.N()+1, id)
}
func (b Ballot) String() string {
return fmt.Sprintf("%d.%s", b.N(), b.ID())
}
// NextBallot generates next ballot number given current ballot bumber and node id
func NextBallot(ballot int, id ID) int {
n := id.Zone()<<16 | id.Node()
return (ballot>>32+1)<<32 | n
}
// LeaderID return the node id from ballot number
func LeaderID(ballot int) ID {
zone := uint32(ballot) >> 16
node := uint16(ballot)
return NewID(int(zone), int(node))
}