-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
67 lines (59 loc) · 1.23 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
57
58
59
60
61
62
63
64
65
66
67
package alternator
import (
"bytes"
"crypto/sha1"
"encoding/gob"
"io"
"math/rand"
"net"
"os"
)
func intMax(a, b int) int {
if a >= b {
return a
}
return b
}
// GenID generates the ID of a node given its address.
func GenID(address string) Key {
h := sha1.New()
rand.Seed(initSeed)
io.WriteString(h, address)
return SliceToKey(h.Sum(nil))
}
// bytesToMetadata converts a byte array into a metadata struct
func bytesToMetadata(data []byte) (md Metadata) {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
dec.Decode(&md)
return md
}
func bytesToPendingPut(data []byte) (pp PendingPut) {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
dec.Decode(&pp)
return pp
}
// serialize serializes an object into an array of bytes
func serialize(obj interface{}) []byte {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(obj)
checkErr("serialization failed", err)
return buf.Bytes()
}
func getIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}