-
Notifications
You must be signed in to change notification settings - Fork 1
/
typed_codec.go
85 lines (67 loc) · 1.55 KB
/
typed_codec.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
package klevdb
import (
"encoding/binary"
"encoding/json"
"github.com/klev-dev/kleverr"
)
type Codec[T any] interface {
Encode(t T, empty bool) (b []byte, err error)
Decode(b []byte) (t T, empty bool, err error)
}
type JsonCodec[T any] struct{}
func (c JsonCodec[T]) Encode(t T, empty bool) ([]byte, error) {
if empty {
return nil, nil
}
return json.Marshal(t)
}
func (c JsonCodec[T]) Decode(b []byte) (T, bool, error) {
var t T
if b == nil {
return t, true, nil
}
err := json.Unmarshal(b, &t)
return t, false, err
}
type stringOptCodec struct{}
func (c stringOptCodec) Encode(t string, empty bool) ([]byte, error) {
if empty {
return nil, nil
}
return json.Marshal(t)
}
func (c stringOptCodec) Decode(b []byte) (string, bool, error) {
if b == nil {
return "", true, nil
}
var s string
err := json.Unmarshal(b, &s)
return s, false, err
}
var StringOptCodec = stringOptCodec{}
type stringCodec struct{}
func (c stringCodec) Encode(t string, empty bool) ([]byte, error) {
return []byte(t), nil
}
func (c stringCodec) Decode(b []byte) (string, bool, error) {
return string(b), false, nil
}
var StringCodec = stringCodec{}
type varintCodec struct{}
func (c varintCodec) Encode(t int64, empty bool) ([]byte, error) {
if empty {
return nil, nil
}
return binary.AppendVarint(nil, t), nil
}
func (c varintCodec) Decode(b []byte) (int64, bool, error) {
if b == nil {
return 0, true, nil
}
t, n := binary.Varint(b)
if n <= 0 {
return 0, true, kleverr.Newf("invalid varint: %d", n)
}
return t, false, nil
}
var VarintCodec = varintCodec{}