This repository has been archived by the owner on Dec 5, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 323
/
bsoncoders.go
89 lines (66 loc) · 1.57 KB
/
bsoncoders.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
package bsonrpc
import (
"fmt"
"github.com/skynetservices/skynet/log"
"io"
"labix.org/v2/mgo/bson"
)
type Encoder struct {
w io.Writer
}
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w: w}
}
func (e *Encoder) Encode(v interface{}) (err error) {
buf, err := bson.Marshal(v)
if err != nil {
return
}
n, err := e.w.Write(buf)
if err != nil {
return
}
if l := len(buf); n != l {
err = fmt.Errorf("Wrote %d bytes, should have wrote %d", n, l)
}
log.Println(log.TRACE, fmt.Sprintf("RPC Wrote %d bytes of %d to connection from buffer: ", n, len(buf)), buf)
return
}
type Decoder struct {
r io.Reader
}
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
func (d *Decoder) Decode(pv interface{}) (err error) {
var lbuf [4]byte
n, err := d.r.Read(lbuf[:])
if n != 4 {
err = fmt.Errorf("Corrupted BSON stream: could only read %d", n)
return
}
log.Println(log.TRACE, fmt.Sprintf("Read %d bytes of 4 byte length from connection, received bytes: ", n), lbuf)
if err != nil {
return
}
length := (int(lbuf[0]) << 0) |
(int(lbuf[1]) << 8) |
(int(lbuf[2]) << 16) |
(int(lbuf[3]) << 24)
log.Println(log.TRACE, "Message length parsed as: ", length)
buf := make([]byte, length)
copy(buf[0:4], lbuf[:])
n, err = io.ReadFull(d.r, buf[4:])
log.Println(log.TRACE, fmt.Sprintf("Read %d bytes of %d from connection, received bytes: ", n+4, length), buf)
if err != nil {
return
}
if n+4 != length {
err = fmt.Errorf("Expected %d bytes, read %d", length, n)
return
}
if pv != nil {
err = bson.Unmarshal(buf, pv)
}
return
}