/
profile.go
83 lines (67 loc) · 1.5 KB
/
profile.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
package isolate
import (
"bytes"
"fmt"
"sync"
"github.com/tinylib/msgp/msgp"
)
const (
typeKey = "type"
)
var (
ErrNoTypeField = fmt.Errorf("profile does not contain `%s` field", typeKey)
ErrTwiceDecodedTo = fmt.Errorf("DecodeTo is called twice")
)
var profilesPool = sync.Pool{
New: func() interface{} {
return make([]byte, 0, 1024)
},
}
type RawProfile interface {
DecodeTo(v msgp.Decodable) error
}
func NewRawProfile(i interface{}) (RawProfile, error) {
var err error
p := cocaineProfile{}
p.buff, err = msgp.AppendIntf(p.buff, i)
return &p, err
}
func NewRawProfileFromBytes(b []byte) RawProfile {
p := &cocaineProfile{
buff: b,
}
return p
}
func newCocaineProfile() *cocaineProfile {
buff := profilesPool.Get().([]byte)
buff = buff[:0]
return &cocaineProfile{buff: buff}
}
type cocaineProfile struct {
buff []byte
}
func (p *cocaineProfile) Type() (string, error) {
raw := msgp.Locate(typeKey, p.buff)
if len(raw) == 0 {
return "", ErrNoTypeField
}
t, _, err := msgp.ReadStringBytes(raw)
return t, err
}
func (p *cocaineProfile) Write(b []byte) (int, error) {
p.buff = append(p.buff, b...)
return len(b), nil
}
// DecodeTo unpacks []byte to some profile. Profile must not be used after DecodeTo
func (p *cocaineProfile) DecodeTo(v msgp.Decodable) error {
if p.buff != nil {
err := msgp.Decode(bytes.NewReader(p.buff), v)
profilesPool.Put(p.buff)
p.buff = nil
return err
}
return ErrTwiceDecodedTo
}
func (p *cocaineProfile) String() string {
return string(p.buff)
}