-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtyped_codec.go
More file actions
96 lines (78 loc) · 1.95 KB
/
typed_codec.go
File metadata and controls
96 lines (78 loc) · 1.95 KB
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
91
92
93
94
95
96
package klevdb
import (
"encoding/binary"
"encoding/json"
"errors"
)
// Codec is interface satisfied by all codecs
type Codec[T any] interface {
Encode(t T, empty bool) (b []byte, err error)
Decode(b []byte) (t T, empty bool, err error)
}
// JsonCodec supports coding values as JSON
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
}
// StringOptCodec supports coding an optional string, e.g. differentiates between "" and nil strings
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
}
// StringCodec supports coding a string
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
}
var errShortBuffer = errors.New("varint: short buffer")
var errOverflow = errors.New("varint: overflow")
func (c varintCodec) Decode(b []byte) (int64, bool, error) {
if b == nil {
return 0, true, nil
}
t, n := binary.Varint(b)
switch {
case n == 0:
return 0, true, errShortBuffer
case n < 0:
return 0, true, errOverflow
default:
return t, false, nil
}
}
// VarintCodec supports coding integers as varint
var VarintCodec = varintCodec{}