-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigest.go
123 lines (101 loc) · 2.22 KB
/
digest.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package scuttlebutt
import (
"bytes"
"encoding/binary"
)
type digest struct {
NodeMaxVersion map[Node]version
}
func newDigest() *digest {
return &digest{NodeMaxVersion: make(map[Node]version)}
}
func (d *digest) addNode(node Node, maxVersion version) {
d.NodeMaxVersion[node] = maxVersion
}
func (d *digest) getNodeMaxVersion(node Node) (version, bool) {
if v, ok := d.NodeMaxVersion[node]; ok {
return v, ok
}
return 0, false
}
func (d *digest) serialize() ([]byte, error) {
var b bytes.Buffer
b.Grow(d.serializedSize())
err := binary.Write(&b, binary.BigEndian, uint16(len(d.NodeMaxVersion)))
if err != nil {
return nil, err
}
for k, v := range d.NodeMaxVersion {
if err := k.serializeTo(&b); err != nil {
return nil, err
}
err = binary.Write(&b, binary.BigEndian, uint64(v))
if err != nil {
return nil, err
}
}
return b.Bytes(), nil
}
func (d *digest) serializedSize() int {
bytes := 2
for k := range d.NodeMaxVersion {
bytes += k.serializedSize() + 8
}
return bytes
}
func (d *digest) deserialize(buf []byte) error {
b := bytes.NewBuffer(buf)
var elem uint16
if err := binary.Read(b, binary.BigEndian, &elem); err != nil {
return err
}
d.NodeMaxVersion = make(map[Node]version, elem)
for i := 0; i < int(elem); i++ {
node := Node{}
if err := node.deserializeFrom(b); err != nil {
return err
}
var ver uint64
if err := binary.Read(b, binary.BigEndian, &ver); err != nil {
return err
}
d.NodeMaxVersion[node] = version(ver)
}
return nil
}
type digestWriter struct {
digest *digest
mtu int
full bool
bytes int
node Node
}
func newDigestWriter(mtu int) *digestWriter {
return &digestWriter{digest: newDigest(), mtu: mtu, full: false, bytes: 2}
}
func (dw *digestWriter) addBytes(n int) bool {
if dw.full {
return false
}
bytes := dw.bytes + n
if bytes > dw.mtu {
dw.full = true
return false
}
dw.bytes = bytes
return true
}
func (dw *digestWriter) addNode(node Node, maxVersion version) bool {
if node == dw.node {
panic("Node already exists")
}
if !dw.addBytes(node.serializedSize() + 8) {
return false
}
dw.node = node
dw.digest.addNode(node, maxVersion)
return true
}
func (dw *digestWriter) getDigest() *digest {
return dw.digest
}