/
msgpack.go
51 lines (43 loc) · 1.32 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
package msgpack
// From Algorand go-algorand
// github.com/algorand/go-algorand-sdk/encoding/msgpack but using plain go-codec
// as we don't need canonical
// but we need codecgen for performance!
import (
"io"
"github.com/ugorji/go/codec"
)
// CodecHandle is used to instantiate msgpack encoders and decoders
// with our settings (canonical, paranoid about decoding errors)
var CodecHandle *codec.MsgpackHandle
// init configures our msgpack encoder and decoder
func init() {
CodecHandle = new(codec.MsgpackHandle)
CodecHandle.ErrorIfNoField = true
CodecHandle.ErrorIfNoArrayExpand = true
CodecHandle.Canonical = true
CodecHandle.RecursiveEmptyCheck = true
CodecHandle.WriteExt = true
CodecHandle.PositiveIntUnsigned = true
}
// Encode returns a msgpack-encoded byte buffer for a given object
func Encode(obj interface{}) []byte {
var b []byte
enc := codec.NewEncoderBytes(&b, CodecHandle)
enc.MustEncode(obj)
return b
}
// Decode attempts to decode a msgpack-encoded byte buffer into an
// object instance pointed to by objptr
func Decode(b []byte, objptr interface{}) error {
dec := codec.NewDecoderBytes(b, CodecHandle)
err := dec.Decode(objptr)
if err != nil {
return err
}
return nil
}
// NewDecoder returns a msgpack decoder
func NewDecoder(r io.Reader) *codec.Decoder {
return codec.NewDecoder(r, CodecHandle)
}