forked from alecthomas/go_serialization_benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structdef-mum.go
90 lines (72 loc) · 1.59 KB
/
structdef-mum.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
90
package goserbench
import (
"fmt"
"time"
"github.com/itsmontoya/mum"
)
func newMumSerializer() *mumSerializer {
var m mumSerializer
m.w = mum.NewWriter(make([]byte, 0, 67))
m.r = mum.NewReader(nil)
return &m
}
type mumSerializer struct {
w *mum.Writer
r *mum.Reader
}
func (m *mumSerializer) Marshal(value interface{}) (bs []byte, err error) {
encodee, ok := value.(mum.Encodee)
if !ok {
err = fmt.Errorf("invalid type, expected %t and received %t", encodee, value)
return
}
if err = m.w.Encode(encodee); err != nil {
return
}
bs = m.w.Bytes()
m.w.Reset()
return
}
func (m *mumSerializer) Unmarshal(bs []byte, value interface{}) (err error) {
decodee, ok := value.(mum.Decodee)
if !ok {
err = fmt.Errorf("invalid type, expected %t and received %t", decodee, value)
return
}
m.r.SetBuffer(bs)
return m.r.Decode(decodee)
}
// MarshalMum is an encoding helper func
func (a *A) MarshalMum(enc *mum.Encoder) (err error) {
enc.String(a.Name)
enc.Int64(a.BirthDay.UnixNano())
enc.String(a.Phone)
enc.Int(a.Siblings)
enc.Bool(a.Spouse)
enc.Float64(a.Money)
return
}
// UnmarshalMum is an decoding helper func
func (a *A) UnmarshalMum(dec *mum.Decoder) (err error) {
if a.Name, err = dec.String(); err != nil {
return
}
var unixNano int64
if unixNano, err = dec.Int64(); err != nil {
return
}
a.BirthDay = time.Unix(0, unixNano)
if a.Phone, err = dec.String(); err != nil {
return
}
if a.Siblings, err = dec.Int(); err != nil {
return
}
if a.Spouse, err = dec.Bool(); err != nil {
return
}
if a.Money, err = dec.Float64(); err != nil {
return
}
return
}