forked from tolsen/mongonet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wire_command.go
96 lines (78 loc) · 1.98 KB
/
wire_command.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
package mongonet
func (m *CommandMessage) HasResponse() bool {
return true
}
func (m *CommandMessage) IsExhaust() bool {
return false
}
func (m *CommandMessage) Header() MessageHeader {
return m.header
}
func (m *CommandMessage) Serialize() []byte {
size := 16 /* header */
size += len(m.DB) + 1
size += len(m.CmdName) + 1
size += int(m.CommandArgs.Size)
size += int(m.Metadata.Size)
for _, d := range m.InputDocs {
size += int(d.Size)
}
m.header.Size = int32(size)
buf := make([]byte, size)
m.header.WriteInto(buf)
loc := 16
writeCString(m.DB, buf, &loc)
writeCString(m.CmdName, buf, &loc)
m.CommandArgs.Copy(&loc, buf)
m.Metadata.Copy(&loc, buf)
for _, d := range m.InputDocs {
d.Copy(&loc, buf)
}
return buf
}
func parseCommandMessage(header MessageHeader, buf []byte) (Message, error) {
cmd := &CommandMessage{}
cmd.header = header
var err error
cmd.DB, err = readCString(buf)
if err != nil {
return cmd, err
}
if len(buf) < len(cmd.DB)+1 {
return cmd, NewStackErrorf("invalid command message -- message length is too short.")
}
buf = buf[len(cmd.DB)+1:]
cmd.CmdName, err = readCString(buf)
if err != nil {
return cmd, err
}
if len(buf) < len(cmd.CmdName)+1 {
return cmd, NewStackErrorf("invalid command message -- message length is too short.")
}
buf = buf[len(cmd.CmdName)+1:]
cmd.CommandArgs, err = parseSimpleBSON(buf)
if err != nil {
return cmd, err
}
if len(buf) < int(cmd.CommandArgs.Size) {
return cmd, NewStackErrorf("invalid command message -- message length is too short.")
}
buf = buf[cmd.CommandArgs.Size:]
cmd.Metadata, err = parseSimpleBSON(buf)
if err != nil {
return cmd, err
}
if len(buf) < int(cmd.Metadata.Size) {
return cmd, NewStackErrorf("invalid command message -- message length is too short.")
}
buf = buf[cmd.Metadata.Size:]
for len(buf) > 0 {
doc, err := parseSimpleBSON(buf)
if err != nil {
return cmd, err
}
buf = buf[doc.Size:]
cmd.InputDocs = append(cmd.InputDocs, doc)
}
return cmd, nil
}