-
Notifications
You must be signed in to change notification settings - Fork 30
/
messaging.go
63 lines (54 loc) · 1.04 KB
/
messaging.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
package main
import (
"encoding/binary"
"encoding/json"
"io"
"unsafe"
)
var nativeEndian binary.ByteOrder
func init() {
var one int16 = 1
b := (*byte)(unsafe.Pointer(&one))
if *b == 0 {
nativeEndian = binary.BigEndian
} else {
nativeEndian = binary.LittleEndian
}
}
type encoder struct {
w io.Writer
}
func newEncoder(w io.Writer) *encoder {
return &encoder{w: w}
}
func (e *encoder) Encode(v interface{}) error {
buf, err := json.Marshal(v)
if err != nil {
return err
}
msgLen := uint32(len(buf))
if err := binary.Write(e.w, nativeEndian, &msgLen); err != nil {
return err
}
if _, err := e.w.Write(buf); err != nil {
return err
}
return nil
}
type decoder struct {
r io.Reader
}
func newDecoder(r io.Reader) *decoder {
return &decoder{r: r}
}
func (d *decoder) Decode(v interface{}) error {
var msgLen uint32
if err := binary.Read(d.r, nativeEndian, &msgLen); err != nil {
return err
}
buf := make([]byte, msgLen)
if _, err := io.ReadFull(d.r, buf); err != nil {
return err
}
return json.Unmarshal(buf, v)
}