-
Notifications
You must be signed in to change notification settings - Fork 0
/
codecs.go
41 lines (35 loc) · 1.23 KB
/
codecs.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
package qp
import (
"encoding/json"
)
// Codec defines types that can marshal and unmarshal data to and from
// bytes.
type Codec interface {
// Marshal takes an object and creates a byte slice representation
// of the object in the underlying data format.
Marshal(object interface{}) ([]byte, error)
// Unmarshal takes a bytes slice of data in the underlying data format
// and decodes it into the provided object
Unmarshal(data []byte, to interface{}) error
}
type codec struct {
marshal func(object interface{}) ([]byte, error)
unmarshal func(data []byte, to interface{}) error
}
func (c *codec) Marshal(object interface{}) ([]byte, error) {
return c.marshal(object)
}
func (c *codec) Unmarshal(data []byte, to interface{}) error {
return c.unmarshal(data, to)
}
// NewCodec makes a new Codec with the specified marshal and
// unmarshal functions.
func NewCodec(marshal func(object interface{}) ([]byte, error), unmarshal func(data []byte, to interface{}) error) Codec {
return &codec{marshal: marshal, unmarshal: unmarshal}
}
// JSON is a Codec that talks JSON.
var JSON = NewCodec(func(object interface{}) ([]byte, error) {
return json.Marshal(object)
}, func(data []byte, to interface{}) error {
return json.Unmarshal(data, to)
})