github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/consense/dpoa/comm/paxnum.go (about) 1 package comm 2 3 import ( 4 "strconv" 5 "strings" 6 "fmt" 7 8 "github.com/sixexorg/magnetic-ring/log" 9 ) 10 11 type ID string 12 13 func NewID(zone, node int) ID { 14 if zone < 0 { 15 zone = -zone 16 } 17 if node < 0 { 18 node = -node 19 } 20 21 return ID(strconv.Itoa(zone) + "." + strconv.Itoa(node)) 22 } 23 24 func (i ID) Zone() int { 25 if !strings.Contains(string(i), ".") { 26 //log.Warningf("id %s does not contain \".\"\n", i) 27 return 0 28 } 29 s := strings.Split(string(i), ".")[0] 30 zone, err := strconv.ParseUint(s, 10, 64) 31 if err != nil { 32 log.Error("Failed to convert Zone %s to int\n", s) 33 } 34 return int(zone) 35 } 36 37 func (i ID) Node() int { 38 var s string 39 if !strings.Contains(string(i), ".") { 40 //log.Warningf("id %s does not contain \".\"\n", i) 41 s = string(i) 42 } else { 43 s = strings.Split(string(i), ".")[1] 44 } 45 node, err := strconv.ParseUint(s, 10, 64) 46 if err != nil { 47 log.Error("Failed to convert Node %s to int\n", s) 48 } 49 return int(node) 50 } 51 52 type Ballot uint64 53 54 func NewBallot(n int, id ID) Ballot { 55 return Ballot(n<<32 | id.Zone()<<16 | id.Node()) 56 } 57 58 func (b Ballot) N() int { 59 return int(uint64(b) >> 32) 60 } 61 62 func (b Ballot) ID() ID { 63 zone := int(uint32(b) >> 16) 64 node := int(uint16(b)) 65 return NewID(zone, node) 66 } 67 68 func (b *Ballot) Next(id ID) { 69 *b = NewBallot(b.N()+1, id) 70 } 71 72 func (b Ballot) String() string { 73 return fmt.Sprintf("%d.%s", b.N(), b.ID()) 74 } 75 76 func NextBallot(ballot int, id ID) int { 77 n := id.Zone()<<16 | id.Node() 78 return (ballot>>32+1)<<32 | n 79 } 80 81 func LeaderID(ballot int) ID { 82 zone := uint32(ballot) >> 16 83 node := uint16(ballot) 84 return NewID(int(zone), int(node)) 85 } 86 87