gunk-dev/the-valley

json.go

sourcee31b215de739main's published tip history
7.5 KiB
1package change
2
3import (
4 "errors"
5 "fmt"
6 "strconv"
7 "unicode/utf16"
8 "unicode/utf8"
9)
10
11// This file is a JSON reader stricter than encoding/json, which accepts a
12// duplicate key and silently replaces bytes that are not UTF-8. A record
13// in which one key appears twice reads differently to two readers that
14// keep different copies, so the reader here refuses it, at any depth.
15//
16// It reads the JSON a record is written in and nothing more. Every value
17// is an object, an array, a string or a number, and true, false and null
18// are read as values of their own kind, so the schema can refuse them by
19// name. A number is kept as its text, and the schema decides whether it
20// is an integer in range.
21
22// maxDepth is how deeply values may nest. A record nests three deep: the
23// record, its versions, and one version.
24const maxDepth = 8
25
26// kind is the kind of a JSON value.
27type kind int
28
29const (
30 kindObject kind = iota
31 kindArray
32 kindString
33 kindNumber
34 kindLiteral // true, false or null
35)
36
37func (k kind) String() string {
38 return [...]string{"an object", "an array", "a string", "a number", "a literal"}[k]
39}
40
41// value is one JSON value as read.
42type value struct {
43 kind kind
44 text string // a string's content, a number's or a literal's text
45 keys []string // an object's keys, in the order they appear
46 fields map[string]*value // an object's values
47 items []*value // an array's values
48}
49
50// readJSON reads data as exactly one JSON value, with only white space
51// around it.
52func readJSON(data []byte) (*value, error) {
53 if !utf8.Valid(data) {
54 return nil, errors.New("it is not valid UTF-8")
55 }
56 r := reader{data: data}
57 r.space()
58 v, err := r.value(1)
59 if err != nil {
60 return nil, err
61 }
62 r.space()
63 if r.pos != len(r.data) {
64 return nil, fmt.Errorf("it holds more after the value it opens with, at byte %d", r.pos)
65 }
66 return v, nil
67}
68
69type reader struct {
70 data []byte
71 pos int
72}
73
74func (r *reader) space() {
75 for r.pos < len(r.data) {
76 switch r.data[r.pos] {
77 case ' ', '\t', '\n', '\r':
78 r.pos++
79 default:
80 return
81 }
82 }
83}
84
85func (r *reader) fail(what string) error {
86 if r.pos >= len(r.data) {
87 return fmt.Errorf("it ends where %s was expected", what)
88 }
89 return fmt.Errorf("it holds %q at byte %d, where %s was expected", r.data[r.pos], r.pos, what)
90}
91
92func (r *reader) value(depth int) (*value, error) {
93 if depth > maxDepth {
94 return nil, fmt.Errorf("it nests values more than %d deep", maxDepth)
95 }
96 if r.pos >= len(r.data) {
97 return nil, r.fail("a value")
98 }
99 switch c := r.data[r.pos]; {
100 case c == '{':
101 return r.object(depth)
102 case c == '[':
103 return r.array(depth)
104 case c == '"':
105 s, err := r.string()
106 if err != nil {
107 return nil, err
108 }
109 return &value{kind: kindString, text: s}, nil
110 case c == '-' || (c >= '0' && c <= '9'):
111 return r.number()
112 default:
113 for _, lit := range []string{"true", "false", "null"} {
114 if len(r.data)-r.pos >= len(lit) && string(r.data[r.pos:r.pos+len(lit)]) == lit {
115 r.pos += len(lit)
116 return &value{kind: kindLiteral, text: lit}, nil
117 }
118 }
119 return nil, r.fail("a value")
120 }
121}
122
123func (r *reader) object(depth int) (*value, error) {
124 v := &value{kind: kindObject, fields: map[string]*value{}}
125 r.pos++ // {
126 r.space()
127 if r.pos < len(r.data) && r.data[r.pos] == '}' {
128 r.pos++
129 return v, nil
130 }
131 for {
132 r.space()
133 if r.pos >= len(r.data) || r.data[r.pos] != '"' {
134 return nil, r.fail("a key")
135 }
136 key, err := r.string()
137 if err != nil {
138 return nil, err
139 }
140 if _, seen := v.fields[key]; seen {
141 return nil, fmt.Errorf("it names the key %q twice in one object", key)
142 }
143 r.space()
144 if r.pos >= len(r.data) || r.data[r.pos] != ':' {
145 return nil, r.fail("a colon")
146 }
147 r.pos++
148 r.space()
149 field, err := r.value(depth + 1)
150 if err != nil {
151 return nil, err
152 }
153 v.keys = append(v.keys, key)
154 v.fields[key] = field
155 r.space()
156 if r.pos >= len(r.data) {
157 return nil, r.fail("a comma or a closing brace")
158 }
159 switch r.data[r.pos] {
160 case ',':
161 r.pos++
162 case '}':
163 r.pos++
164 return v, nil
165 default:
166 return nil, r.fail("a comma or a closing brace")
167 }
168 }
169}
170
171func (r *reader) array(depth int) (*value, error) {
172 v := &value{kind: kindArray}
173 r.pos++ // [
174 r.space()
175 if r.pos < len(r.data) && r.data[r.pos] == ']' {
176 r.pos++
177 return v, nil
178 }
179 for {
180 r.space()
181 item, err := r.value(depth + 1)
182 if err != nil {
183 return nil, err
184 }
185 v.items = append(v.items, item)
186 r.space()
187 if r.pos >= len(r.data) {
188 return nil, r.fail("a comma or a closing bracket")
189 }
190 switch r.data[r.pos] {
191 case ',':
192 r.pos++
193 case ']':
194 r.pos++
195 return v, nil
196 default:
197 return nil, r.fail("a comma or a closing bracket")
198 }
199 }
200}
201
202// string reads one JSON string. An escape that names half of a UTF-16
203// surrogate pair alone names no character, so it is refused rather than
204// read as U+FFFD, the way encoding/json reads it.
205func (r *reader) string() (string, error) {
206 r.pos++ // "
207 var out []byte
208 for {
209 if r.pos >= len(r.data) {
210 return "", r.fail("the end of a string")
211 }
212 c := r.data[r.pos]
213 switch {
214 case c == '"':
215 r.pos++
216 return string(out), nil
217 case c < 0x20:
218 return "", fmt.Errorf("it holds the control character %q unescaped in a string, at byte %d", c, r.pos)
219 case c != '\\':
220 out = append(out, c)
221 r.pos++
222 continue
223 }
224 r.pos++ // the backslash
225 if r.pos >= len(r.data) {
226 return "", r.fail("an escape")
227 }
228 e := r.data[r.pos]
229 r.pos++
230 switch e {
231 case '"', '\\', '/':
232 out = append(out, e)
233 case 'b':
234 out = append(out, '\b')
235 case 'f':
236 out = append(out, '\f')
237 case 'n':
238 out = append(out, '\n')
239 case 'r':
240 out = append(out, '\r')
241 case 't':
242 out = append(out, '\t')
243 case 'u':
244 rn, err := r.hex4()
245 if err != nil {
246 return "", err
247 }
248 if utf16.IsSurrogate(rn) {
249 if rn >= 0xdc00 || len(r.data)-r.pos < 2 || r.data[r.pos] != '\\' || r.data[r.pos+1] != 'u' {
250 return "", fmt.Errorf("it escapes half of a surrogate pair alone, at byte %d", r.pos)
251 }
252 r.pos += 2
253 low, err := r.hex4()
254 if err != nil {
255 return "", err
256 }
257 rn = utf16.DecodeRune(rn, low)
258 if rn == utf8.RuneError {
259 return "", fmt.Errorf("it escapes half of a surrogate pair alone, at byte %d", r.pos)
260 }
261 }
262 out = utf8.AppendRune(out, rn)
263 default:
264 return "", fmt.Errorf("it holds the escape \\%c, which JSON does not have, at byte %d", e, r.pos-1)
265 }
266 }
267}
268
269func (r *reader) hex4() (rune, error) {
270 if len(r.data)-r.pos < 4 {
271 return 0, r.fail("four hex digits")
272 }
273 n, err := strconv.ParseUint(string(r.data[r.pos:r.pos+4]), 16, 32)
274 if err != nil {
275 return 0, r.fail("four hex digits")
276 }
277 r.pos += 4
278 return rune(n), nil
279}
280
281// number reads one JSON number, keeping its text.
282func (r *reader) number() (*value, error) {
283 start := r.pos
284 if r.data[r.pos] == '-' {
285 r.pos++
286 }
287 switch {
288 case r.pos < len(r.data) && r.data[r.pos] == '0':
289 r.pos++
290 case r.pos < len(r.data) && r.data[r.pos] >= '1' && r.data[r.pos] <= '9':
291 r.digits()
292 default:
293 return nil, r.fail("a digit")
294 }
295 if r.pos < len(r.data) && r.data[r.pos] == '.' {
296 r.pos++
297 if !r.digits() {
298 return nil, r.fail("a digit")
299 }
300 }
301 if r.pos < len(r.data) && (r.data[r.pos] == 'e' || r.data[r.pos] == 'E') {
302 r.pos++
303 if r.pos < len(r.data) && (r.data[r.pos] == '+' || r.data[r.pos] == '-') {
304 r.pos++
305 }
306 if !r.digits() {
307 return nil, r.fail("a digit")
308 }
309 }
310 return &value{kind: kindNumber, text: string(r.data[start:r.pos])}, nil
311}
312
313func (r *reader) digits() bool {
314 start := r.pos
315 for r.pos < len(r.data) && r.data[r.pos] >= '0' && r.data[r.pos] <= '9' {
316 r.pos++
317 }
318 return r.pos > start
319}