-
Notifications
You must be signed in to change notification settings - Fork 0
/
msgpack.go
53 lines (41 loc) · 993 Bytes
/
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
package codec
import (
"bytes"
"io"
"github.com/tinylib/msgp/msgp"
"github.com/vmihailenco/msgpack/v5"
)
// msgpack 协议
type MsgpackCoder struct {
}
func NewMsgpackCoder() *MsgpackCoder {
return &MsgpackCoder{}
}
func (m *MsgpackCoder) Marshal(v any) ([]byte, error) {
if m, ok := v.(msgp.Marshaler); ok {
return m.MarshalMsg(nil)
}
var buf bytes.Buffer
enc := msgpack.NewEncoder(&buf)
err := enc.Encode(v)
return buf.Bytes(), err
}
func (m *MsgpackCoder) MarshalTo(v any, w io.Writer) (err error) {
enc := msgpack.NewEncoder(w)
return enc.Encode(v)
}
func (m *MsgpackCoder) Unmarshal(data []byte, v any) (err error) {
if m, ok := v.(msgp.Unmarshaler); ok {
_, err = m.UnmarshalMsg(data)
return
}
dec := msgpack.NewDecoder(bytes.NewReader(data))
return dec.Decode(v)
}
func (m *MsgpackCoder) UnmarshalFrom(r io.Reader, v any) (err error) {
dec := msgpack.NewDecoder(r)
return dec.Decode(v)
}
func (m *MsgpackCoder) String() string {
return "Msgpack"
}