/
marshal.go
87 lines (71 loc) · 1.82 KB
/
marshal.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
// Package json provides a simpler JSON marshaller for strings and ints only.
package json
import (
"bytes"
"encoding/json"
"regexp"
"strconv"
"github.com/keys-pub/keys/encoding"
"github.com/pkg/errors"
)
type stringEntry struct {
key string
value string
}
type intEntry struct {
key string
value int
}
// String ...
func String(key string, value string) encoding.TextMarshaler {
return stringEntry{key: key, value: value}
}
// Int ...
func Int(key string, value int) encoding.TextMarshaler {
return intEntry{key: key, value: value}
}
var isAlphaNumericDot = regexp.MustCompile(`^[a-zA-Z0-9.]+$`).MatchString
var needsEscape = regexp.MustCompile(`^[\"]+$`).MatchString
func (e stringEntry) MarshalText() ([]byte, error) {
if !isAlphaNumericDot(e.key) {
return nil, errors.Errorf("invalid character in key")
}
if needsEscape(e.value) {
return nil, errors.Errorf("invalid character in value")
}
if !encoding.IsASCII([]byte(e.value)) {
return nil, errors.Errorf("invalid character in value")
}
return []byte(`"` + e.key + `":"` + e.value + `"`), nil
}
func (e intEntry) MarshalText() ([]byte, error) {
if !isAlphaNumericDot(e.key) {
return nil, errors.Errorf("invalid character in key")
}
b := []byte{}
b = append(b, '"')
b = append(b, []byte(e.key)...)
b = append(b, '"', ':')
b = append(b, []byte(strconv.Itoa(e.value))...)
return b, nil
}
// Marshal values.
func Marshal(vals ...encoding.TextMarshaler) ([]byte, error) {
out := make([][]byte, 0, len(vals))
for _, val := range vals {
b, err := val.MarshalText()
if err != nil {
return nil, err
}
out = append(out, b)
}
b := []byte{}
b = append(b, '{')
b = append(b, bytes.Join(out, []byte{','})...)
b = append(b, '}')
return b, nil
}
// Unmarshal bytes.
func Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}