-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_transport_message.go
73 lines (64 loc) · 2.02 KB
/
binary_transport_message.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
package main
import (
"bytes"
"encoding/binary"
)
// Message to send to other nodes
type BinaryTransportMessage struct {
Version uint32 // Message format (e.g. 1)
Type BinaryTransportMessageType // Sort message
Len uint32 // Length of data
Data []byte // Actual data
}
// This version
const BINARY_TRANSPORT_MESSAGE_VERSION uint32 = 1
// Message type
type BinaryTransportMessageType uint32
// Message types
const (
EmptyBinaryTransportMessageType BinaryTransportMessageType = iota // 0 = not set
ShardIdxBinaryTransportMessageType // 1 = shard index
FileBinaryTransportMessageType // 2 = file binary transport
CreateShardBinaryTransportMessageType // 3 = create shard (replication)
)
// To bytes
func (this *BinaryTransportMessage) Bytes() []byte {
if this.Type < 1 || this.Len < 1 {
panic("Can not convert empty message to bytes")
}
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, this.Version) // meta version
binary.Write(buf, binary.BigEndian, this.Type) // type
binary.Write(buf, binary.BigEndian, this.Len) // data length
if this.Data != nil {
buf.Write(this.Data)
}
return buf.Bytes()
}
// From bytes
func (this *BinaryTransportMessage) FromBytes(b []byte) {
buf := bytes.NewReader(b)
var err error
err = binary.Read(buf, binary.BigEndian, &this.Version) // meta version
panicErr(err)
err = binary.Read(buf, binary.BigEndian, &this.Type) // type
panicErr(err)
err = binary.Read(buf, binary.BigEndian, &this.Len) // length
panicErr(err)
// Read data
this.Data = make([]byte, this.Len)
buf.Read(this.Data)
}
// New message
func newBinaryTransportMessage(t BinaryTransportMessageType, data []byte) *BinaryTransportMessage {
var l uint32 = 0
if data != nil {
l = uint32(len(data))
}
return &BinaryTransportMessage{
Version: BINARY_TRANSPORT_MESSAGE_VERSION,
Type: t,
Len: l,
Data: data,
}
}