-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
76 lines (58 loc) · 1.59 KB
/
writer.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
package binproto
import (
"bufio"
"encoding/binary"
)
// A Writer implements convenience methods for writing
// requests or responses to a binary protocol network connection.
type Writer struct {
wd *bufio.Writer
}
// NewWriter returns a new Writer writing to w.
func NewWriter(wd *bufio.Writer) *Writer {
return &Writer{wd: wd}
}
// WriteMessage writes a variable number of messages to w.
func (w *Writer) WriteMessage(messages ...*Message) error {
var err error
if len(messages) == 1 {
i := messages[0]
_, err = w.wd.Write(send(i.ID, i.Channel, i.Data))
} else {
_, err = w.wd.Write(sendBatch(messages))
}
if err != nil {
return err
}
if err := w.wd.Flush(); err != nil {
return err
}
return nil
}
func send(id int, ch rune, data []byte) []byte {
header := uint64(id)<<4 | uint64(ch)
length := len(data) + encodingLength(header)
payload := make([]byte, encodingLength(uint64(length))+length)
n := binary.PutUvarint(payload, uint64(length))
n += binary.PutUvarint(payload[n:], header)
copy(payload[n:], data)
return payload
}
func sendBatch(items []*Message) []byte {
offset := 0
var length int
for _, v := range items {
// 16 is >= the max size of the varints
length += 16 + encodingLength(uint64(len(v.Data)))
}
payload := make([]byte, length)
for _, v := range items {
header := uint64(v.ID<<4) | uint64(v.Channel)
l := uint64(len(v.Data) + encodingLength(header))
offset += binary.PutUvarint(payload[offset:], l)
offset += binary.PutUvarint(payload[offset:], header)
copy(payload[offset:], v.Data)
offset += len(v.Data)
}
return payload[0:offset]
}