/
msgpack.go
87 lines (72 loc) · 1.43 KB
/
msgpack.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
package mc_msgpack
import (
"io"
mc "github.com/ipsn/go-ipfs/gxlibs/github.com/multiformats/go-multicodec"
gocodec "github.com/ugorji/go/codec"
)
const HeaderPath = "/msgpack"
var Header = mc.Header([]byte(HeaderPath))
type codec struct {
mc bool
handle *gocodec.MsgpackHandle
}
func Codec(h *gocodec.MsgpackHandle) mc.Codec {
return &codec{
mc: false,
handle: h,
}
}
func DefaultMsgpackHandle() *gocodec.MsgpackHandle {
return &gocodec.MsgpackHandle{}
}
func Multicodec(h *gocodec.MsgpackHandle) mc.Multicodec {
return &codec{
mc: true,
handle: h,
}
}
func (c *codec) Encoder(w io.Writer) mc.Encoder {
return &encoder{
w: w,
mc: c.mc,
enc: gocodec.NewEncoder(w, c.handle),
}
}
func (c *codec) Decoder(r io.Reader) mc.Decoder {
return &decoder{
r: r,
mc: c.mc,
dec: gocodec.NewDecoder(r, c.handle),
}
}
func (c *codec) Header() []byte {
return Header
}
type encoder struct {
w io.Writer
mc bool
enc *gocodec.Encoder
}
type decoder struct {
r io.Reader
mc bool
dec *gocodec.Decoder
}
func (c *encoder) Encode(v interface{}) error {
// if multicodec, write the header first
if c.mc {
if _, err := c.w.Write(Header); err != nil {
return err
}
}
return c.enc.Encode(v)
}
func (c *decoder) Decode(v interface{}) error {
// if multicodec, consume the header first
if c.mc {
if err := mc.ConsumeHeader(c.r, Header); err != nil {
return err
}
}
return c.dec.Decode(v)
}