-
Notifications
You must be signed in to change notification settings - Fork 0
/
wire_reply.go
84 lines (66 loc) · 1.69 KB
/
wire_reply.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
package mongowire
import (
"bytes"
"errors"
"github.com/tychoish/birch"
)
func NewReply(cursorID int64, flags, startingFrom, numReturned int32, docs []birch.Document) Message {
return &ReplyMessage{
header: MessageHeader{
RequestID: 19,
OpCode: OP_REPLY,
},
Flags: flags,
CursorId: cursorID,
StartingFrom: startingFrom,
NumberReturned: numReturned,
Docs: docs,
}
}
// because its a response
func (m *ReplyMessage) HasResponse() bool { return false }
func (m *ReplyMessage) Header() MessageHeader { return m.header }
func (m *ReplyMessage) Scope() *OpScope { return nil }
func (m *ReplyMessage) Serialize() []byte {
size := 16 /* header */ + 20 /* reply header */
for _, d := range m.Docs {
size += getDocSize(&d)
}
m.header.Size = int32(size)
buf := bytes.NewBuffer(make([]byte, 0, size))
m.header.WriteTo(buf)
writeInt32(m.Flags, buf)
writeInt64(m.CursorId, buf)
writeInt32(m.StartingFrom, buf)
writeInt32(m.NumberReturned, buf)
for _, d := range m.Docs {
d.WriteTo(buf)
}
return buf.Bytes()
}
func (h *MessageHeader) parseReplyMessage(buf []byte) (Message, error) {
var loc int
if len(buf) < 20 {
return nil, errors.New("invalid reply message -- message must have length of at least 20 bytes")
}
rm := &ReplyMessage{
header: *h,
}
rm.Flags = readInt32(buf[loc:])
loc += 4
rm.CursorId = readInt64(buf[loc:])
loc += 8
rm.StartingFrom = readInt32(buf[loc:])
loc += 4
rm.NumberReturned = readInt32(buf[loc:])
loc += 4
for loc < len(buf) {
doc, err := birch.ReadDocument(buf[loc:])
if err != nil {
return nil, err
}
rm.Docs = append(rm.Docs, *doc.Copy())
loc += getDocSize(doc)
}
return rm, nil
}