-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson.go
131 lines (107 loc) · 2.19 KB
/
json.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package orderedmap
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
)
// MarshalJSON implements json.Marshaler interface
// to marshall a sorted list of key-value pairs into an object.
func (o OrderedMap[K, V]) MarshalJSON() ([]byte, error) {
if o == nil {
return []byte(`null`), nil
}
if len(o) == 0 {
return []byte(`{}`), nil
}
var buf bytes.Buffer
if err := buf.WriteByte('{'); err != nil {
return nil, err
}
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
for i, p := range o {
if i != 0 {
if err := buf.WriteByte(','); err != nil {
return nil, err
}
}
if err := enc.Encode(p.Key); err != nil {
return nil, err
}
if err := buf.WriteByte(':'); err != nil {
return nil, err
}
if err := enc.Encode(p.Val); err != nil {
return nil, err
}
}
if err := buf.WriteByte('}'); err != nil {
return nil, err
}
return bytes.TrimRight(buf.Bytes(), "\n"), nil
}
// UnmarshalJSON implements json.Unmarshaler interface
// to unmarshal an object into a sorted list of key-value pairs.
func (o *OrderedMap[K, V]) UnmarshalJSON(data []byte) error {
var m map[K]V
err := json.Unmarshal(data, &m)
if err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(data))
t, err := dec.Token()
if err != nil {
return err
}
if t != json.Delim('{') {
return errors.New("expected start of object")
}
for {
t, err := dec.Token()
if err != nil {
return err
}
if t == json.Delim('}') {
break
}
key, ok := t.(K)
if !ok {
return fmt.Errorf("expected object key to be %T, got %T", key, t)
}
*o = append(*o, Pair[K, V]{
Key: key,
Val: m[key],
})
// ignored value
if err := skipJSONValue(dec); err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
}
return nil
}
var errJSONEnd = errors.New("invalid end of json array or object")
func skipJSONValue(dec *json.Decoder) error {
t, err := dec.Token()
if err != nil {
return err
}
switch t {
case json.Delim('['), json.Delim('{'):
for {
if err := skipJSONValue(dec); err != nil {
if errors.Is(err, errJSONEnd) {
break
}
return err
}
}
case json.Delim(']'), json.Delim('}'):
return errJSONEnd
}
return nil
}