-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmpub.go
123 lines (98 loc) · 2.49 KB
/
mpub.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 nsq
import (
"bufio"
"encoding/binary"
"io"
"github.com/pkg/errors"
)
// MPub represents the MPUB command.
type MPub struct {
// Topic must be set to the name of the topic to which the messages will be
// published.
Topic string
// Messages is the list of raw messages to publish.
Messages [][]byte
}
// Name returns the name of the command in order to satisfy the Command
// interface.
func (c MPub) Name() string {
return "MPUB"
}
// Write serializes the command to the given buffered output, satisfies the
// Command interface.
func (c MPub) Write(w *bufio.Writer) (err error) {
for _, s := range [...]string{
"MPUB ",
c.Topic,
"\n",
} {
if _, err = w.WriteString(s); err != nil {
err = errors.Wrap(err, "writing MPUB command")
return
}
}
var size uint32
for _, m := range c.Messages {
size += uint32(len(m))
}
if err = binary.Write(w, binary.BigEndian, size); err != nil {
err = errors.Wrap(err, "writing MPUB body size")
return
}
if err = binary.Write(w, binary.BigEndian, uint32(len(c.Messages))); err != nil {
err = errors.Wrap(err, "writing MPUB message count")
return
}
for _, m := range c.Messages {
if err = binary.Write(w, binary.BigEndian, uint32(len(m))); err != nil {
err = errors.Wrap(err, "writing MPUB message size")
return
}
if _, err = w.Write(m); err != nil {
err = errors.Wrap(err, "writing MPUB message data")
return
}
}
return
}
func readMPub(line string, r *bufio.Reader) (cmd MPub, err error) {
var topic string
var count uint32
var messages [][]byte
topic, line = readNextWord(line)
if len(topic) == 0 {
err = errors.New("missing topic in MPUB command")
return
}
if len(line) != 0 {
err = errors.New("too many arguments found in MPUB command")
return
}
if err = binary.Read(r, binary.BigEndian, &count); err != nil {
err = errors.Wrap(err, "reading MPUB body size")
return
}
if err = binary.Read(r, binary.BigEndian, &count); err != nil {
err = errors.Wrap(err, "reading MPUB message count")
return
}
for messages = make([][]byte, 0, int(count)); count != 0; count-- {
var size uint32
var data []byte
if err = binary.Read(r, binary.BigEndian, &size); err != nil {
err = errors.Wrap(err, "reading MPUB message size")
return
}
data = make([]byte, int(size))
if _, err = io.ReadFull(r, data); err != nil {
err = errors.Wrap(err, "reading MPUB message data")
return
}
messages = append(messages, data)
}
cmd = MPub{
Topic: topic,
Messages: messages,
}
return
}