-
Notifications
You must be signed in to change notification settings - Fork 0
/
label.go
66 lines (55 loc) · 1.27 KB
/
label.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
package gogossip
import (
"encoding/binary"
"errors"
"math/rand"
"time"
)
var (
errTooShort = errors.New("bytes too short")
)
// Label: packetType(1 byte) + encryptType(1 byte)
var labelTotalSize = binary.Size(label{})
type label struct {
packetType packetType
encryptType EncryptType
// tempSize [4]byte
}
func (l label) combine(buf []byte) ([]byte, error) {
if binary.Size(l) != labelTotalSize {
return nil, errTooShort
}
b := make([]byte, 0, labelTotalSize+len(buf))
b = append(b, l.bytes()...)
b = append(b, buf...)
return b, nil
}
func (l label) bytes() []byte {
b := make([]byte, labelTotalSize)
b[0] = byte(l.packetType)
b[1] = byte(l.encryptType)
// copy(b[2:6], l.tempSize[:])
return b
}
func bytesToLabel(buf []byte) *label {
if len(buf) != labelTotalSize {
return nil
}
// var tempSize [4]byte
// copy(tempSize[:], buf[2:4])
return &label{
packetType(buf[0]), EncryptType(buf[1]), // tempSize,
}
}
func splitLabel(buf []byte) (*label, []byte, error) {
if len(buf) < labelTotalSize {
return nil, nil, errTooShort
}
return bytesToLabel(buf[:labelTotalSize]), buf[labelTotalSize:], nil
}
func idGenerator() [8]byte {
var buf [8]byte
random := rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
random.Read(buf[:])
return buf
}