summaryrefslogtreecommitdiff
path: root/encode.go
blob: acef2140500a08895f165ed29bf7f522790dc936 (plain)
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package lowmemjson

import (
	"bytes"
	"encoding"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	iofs "io/fs"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"unicode/utf8"
	"unsafe"
)

type Encodable interface {
	EncodeJSON(w io.Writer) error
}

type encodeError struct {
	Err error
}

func encodeWriteByte(w io.Writer, b byte) {
	if err := writeByte(w, b); err != nil {
		panic(encodeError{err})
	}
}

func encodeWriteString(w io.Writer, str string) {
	if _, err := io.WriteString(w, str); err != nil {
		panic(encodeError{err})
	}
}

type Encoder struct {
	w                *ReEncoder
	closeAfterEncode bool
}

// NewEncoder returns a new encoder.
//
// If w is an *ReEncoder, then the inner backslash-escaping of
// double-encoded ",string" tagged string values obeys the
// *ReEncoder's BackslashEscape policy.
func NewEncoder(w io.Writer) *Encoder {
	re, ok := w.(*ReEncoder)
	if !ok {
		re = &ReEncoder{
			Out:                 w,
			AllowMultipleValues: true,
		}
	}
	return &Encoder{
		w:                re,
		closeAfterEncode: len(re.par.stack) == 0 || (len(re.par.stack) == 1 && re.par.stack[0] == RuneTypeError),
	}
}

func (enc *Encoder) Encode(obj any) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if e, ok := r.(encodeError); ok {
				err = e.Err
			} else {
				panic(r)
			}
		}
	}()
	encode(enc.w, reflect.ValueOf(obj), enc.w.BackslashEscape, false, 0, map[any]struct{}{})
	if enc.closeAfterEncode {
		return enc.w.Close()
	}
	return nil
}

// Encode encodes a value to w.
//
// If w is an *ReEncoder, then the inner backslash-escaping of
// double-encoded ",string" tagged string values obeys the
// *ReEncoder's BackslashEscape policy.
//
// Does not write a trailing newline or other whitespace; if you will
// be encoding multiple values to w, then you should instead use an
// *Encoder object, as some JSON values need whitespace between them.
func Encode(w io.Writer, obj any) (err error) {
	return NewEncoder(w).Encode(obj)
}

var (
	encodableType     = reflect.TypeOf((*Encodable)(nil)).Elem()
	jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
)

const startDetectingCyclesAfter = 1000

func encode(w io.Writer, val reflect.Value, escaper BackslashEscaper, quote bool, cycleDepth uint, cycleSeen map[any]struct{}) {
	if !val.IsValid() {
		encodeWriteString(w, "null")
		return
	}
	switch {

	case val.Kind() != reflect.Pointer && val.CanAddr() && reflect.PointerTo(val.Type()).Implements(encodableType):
		val = val.Addr()
		fallthrough
	case val.Type().Implements(encodableType):
		if val.Kind() == reflect.Pointer && val.IsNil() {
			encodeWriteString(w, "null")
			return
		}
		obj, ok := val.Interface().(Encodable)
		if !ok {
			encodeWriteString(w, "null")
			return
		}
		// Use a sub-ReEncoder to check that it's a full element.
		validator := &ReEncoder{Out: w, BackslashEscape: escaper}
		if err := obj.EncodeJSON(validator); err != nil {
			panic(encodeError{&EncodeMethodError{
				Type:       val.Type(),
				Err:        err,
				SourceFunc: "EncodeJSON",
			}})
		}
		if err := validator.Close(); err != nil && !errors.Is(err, iofs.ErrClosed) {
			panic(encodeError{err})
		}

	case val.Kind() != reflect.Pointer && val.CanAddr() && reflect.PointerTo(val.Type()).Implements(jsonMarshalerType):
		val = val.Addr()
		fallthrough
	case val.Type().Implements(jsonMarshalerType):
		if val.Kind() == reflect.Pointer && val.IsNil() {
			encodeWriteString(w, "null")
			return
		}
		obj, ok := val.Interface().(json.Marshaler)
		if !ok {
			encodeWriteString(w, "null")
			return
		}
		dat, err := obj.MarshalJSON()
		if err != nil {
			panic(encodeError{&EncodeMethodError{
				Type:       val.Type(),
				Err:        err,
				SourceFunc: "MarshalJSON",
			}})
		}
		// Use a sub-ReEncoder to check that it's a full element.
		validator := &ReEncoder{Out: w, BackslashEscape: escaper}
		if _, err := validator.Write(dat); err != nil {
			panic(encodeError{err})
		}
		if err := validator.Close(); err != nil {
			panic(encodeError{err})
		}

	case val.Kind() != reflect.Pointer && val.CanAddr() && reflect.PointerTo(val.Type()).Implements(textMarshalerType):
		val = val.Addr()
		fallthrough
	case val.Type().Implements(textMarshalerType):
		if val.Kind() == reflect.Pointer && val.IsNil() {
			encodeWriteString(w, "null")
			return
		}
		obj, ok := val.Interface().(encoding.TextMarshaler)
		if !ok {
			encodeWriteString(w, "null")
			return
		}
		text, err := obj.MarshalText()
		if err != nil {
			panic(encodeError{&EncodeMethodError{
				Type:       val.Type(),
				Err:        err,
				SourceFunc: "MarshalText",
			}})
		}
		encodeStringFromBytes(w, escaper, text)

	default:
		switch val.Kind() {
		case reflect.Bool:
			if quote {
				encodeWriteByte(w, '"')
			}
			if val.Bool() {
				encodeWriteString(w, "true")
			} else {
				encodeWriteString(w, "false")
			}
			if quote {
				encodeWriteByte(w, '"')
			}
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			if quote {
				encodeWriteByte(w, '"')
			}
			encodeWriteString(w, strconv.FormatInt(val.Int(), 10))
			if quote {
				encodeWriteByte(w, '"')
			}
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			if quote {
				encodeWriteByte(w, '"')
			}
			encodeWriteString(w, strconv.FormatUint(val.Uint(), 10))
			if quote {
				encodeWriteByte(w, '"')
			}
		case reflect.Float32, reflect.Float64:
			if quote {
				encodeWriteByte(w, '"')
			}
			encodeTODO(w, val)
			if quote {
				encodeWriteByte(w, '"')
			}
		case reflect.String:
			if val.Type() == numberType {
				numStr := val.String()
				if numStr == "" {
					numStr = "0"
				}
				if quote {
					encodeWriteByte(w, '"')
				}
				encodeWriteString(w, numStr)
				if quote {
					encodeWriteByte(w, '"')
				}
			} else {
				if quote {
					var buf bytes.Buffer
					encodeStringFromString(&buf, escaper, val.String())
					encodeStringFromBytes(w, escaper, buf.Bytes())
				} else {
					encodeStringFromString(w, escaper, val.String())
				}
			}
		case reflect.Interface:
			if val.IsNil() {
				encodeWriteString(w, "null")
			} else {
				encode(w, val.Elem(), escaper, quote, cycleDepth, cycleSeen)
			}
		case reflect.Struct:
			encodeWriteByte(w, '{')
			empty := true
			for _, field := range indexStruct(val.Type()).byPos {
				fVal, err := val.FieldByIndexErr(field.Path)
				if err != nil {
					continue
				}
				if field.OmitEmpty && isEmptyValue(fVal) {
					continue
				}
				if !empty {
					encodeWriteByte(w, ',')
				}
				empty = false
				encodeStringFromString(w, escaper, field.Name)
				encodeWriteByte(w, ':')
				encode(w, fVal, escaper, field.Quote, cycleDepth, cycleSeen)
			}
			encodeWriteByte(w, '}')
		case reflect.Map:
			if val.IsNil() {
				encodeWriteString(w, "null")
				return
			}
			if val.Len() == 0 {
				encodeWriteString(w, "{}")
				return
			}
			if cycleDepth++; cycleDepth > startDetectingCyclesAfter {
				ptr := val.UnsafePointer()
				if _, seen := cycleSeen[ptr]; seen {
					panic(encodeError{&EncodeValueError{
						Value: val,
						Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
					}})
				}
				cycleSeen[ptr] = struct{}{}
				defer delete(cycleSeen, ptr)
			}
			encodeWriteByte(w, '{')

			type kv struct {
				K string
				V reflect.Value
			}
			kvs := make([]kv, val.Len())
			iter := val.MapRange()
			for i := 0; iter.Next(); i++ {
				// TODO: Avoid buffering the map key
				var k strings.Builder
				encode(&k, iter.Key(), escaper, false, cycleDepth, cycleSeen)
				kStr := k.String()
				if kStr == "null" {
					kStr = `""`
				}
				if !strings.HasPrefix(kStr, `"`) {
					k.Reset()
					encodeStringFromString(&k, escaper, kStr)
					kStr = k.String()
				}
				kvs[i].K = kStr
				kvs[i].V = iter.Value()
			}
			sort.Slice(kvs, func(i, j int) bool {
				return kvs[i].K < kvs[j].K
			})

			for i, kv := range kvs {
				if i > 0 {
					encodeWriteByte(w, ',')
				}
				encodeWriteString(w, kv.K)
				encodeWriteByte(w, ':')
				encode(w, kv.V, escaper, false, cycleDepth, cycleSeen)
			}
			encodeWriteByte(w, '}')
		case reflect.Slice:
			switch {
			case val.IsNil():
				encodeWriteString(w, "null")
			case val.Type().Elem().Kind() == reflect.Uint8 && !(false ||
				val.Type().Elem().Implements(encodableType) ||
				reflect.PointerTo(val.Type().Elem()).Implements(encodableType) ||
				val.Type().Elem().Implements(jsonMarshalerType) ||
				reflect.PointerTo(val.Type().Elem()).Implements(jsonMarshalerType) ||
				val.Type().Elem().Implements(textMarshalerType) ||
				reflect.PointerTo(val.Type().Elem()).Implements(textMarshalerType)):
				encodeWriteByte(w, '"')
				enc := base64.NewEncoder(base64.StdEncoding, w)
				if val.CanConvert(byteSliceType) {
					if _, err := enc.Write(val.Convert(byteSliceType).Interface().([]byte)); err != nil {
						panic(encodeError{err})
					}
				} else {
					// TODO: Surely there's a better way.
					for i, n := 0, val.Len(); i < n; i++ {
						var buf [1]byte
						buf[0] = val.Index(i).Convert(byteType).Interface().(byte)
						if _, err := enc.Write(buf[:]); err != nil {
							panic(encodeError{err})
						}
					}
				}
				if err := enc.Close(); err != nil {
					panic(encodeError{err})
				}
				encodeWriteByte(w, '"')
			default:
				if cycleDepth++; cycleDepth > startDetectingCyclesAfter {
					// For slices, val.UnsafePointer() doesn't return a pointer to the slice header
					// or anything like that, it returns a pointer *to the first element in the
					// slice*.  That means that the pointer isn't enough to uniquely identify the
					// slice!  So we pair the pointer with the length of the slice, which is
					// sufficient.
					ptr := struct {
						ptr unsafe.Pointer
						len int
					}{val.UnsafePointer(), val.Len()}
					if _, seen := cycleSeen[ptr]; seen {
						panic(encodeError{&EncodeValueError{
							Value: val,
							Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
						}})
					}
					cycleSeen[ptr] = struct{}{}
					defer delete(cycleSeen, ptr)
				}
				encodeArray(w, val, escaper, cycleDepth, cycleSeen)
			}
		case reflect.Array:
			encodeArray(w, val, escaper, cycleDepth, cycleSeen)
		case reflect.Pointer:
			if val.IsNil() {
				encodeWriteString(w, "null")
			} else {
				if cycleDepth++; cycleDepth > startDetectingCyclesAfter {
					ptr := val.UnsafePointer()
					if _, seen := cycleSeen[ptr]; seen {
						panic(encodeError{&EncodeValueError{
							Value: val,
							Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
						}})
					}
					cycleSeen[ptr] = struct{}{}
					defer delete(cycleSeen, ptr)
				}
				encode(w, val.Elem(), escaper, quote, cycleDepth, cycleSeen)
			}
		default:
			panic(encodeError{&EncodeTypeError{
				Type: val.Type(),
			}})
		}
	}
}

func encodeStringFromString(w io.Writer, escaper BackslashEscaper, str string) {
	encodeWriteByte(w, '"')
	for _, c := range str {
		if _, err := writeStringChar(w, c, BackslashEscapeNone, escaper); err != nil {
			panic(encodeError{err})
		}
	}
	encodeWriteByte(w, '"')
}

func encodeStringFromBytes(w io.Writer, escaper BackslashEscaper, str []byte) {
	encodeWriteByte(w, '"')
	for i := 0; i < len(str); {
		c, size := utf8.DecodeRune(str[i:])
		if _, err := writeStringChar(w, c, BackslashEscapeNone, escaper); err != nil {
			panic(encodeError{err})
		}
		i += size
	}
	encodeWriteByte(w, '"')
}

func encodeArray(w io.Writer, val reflect.Value, escaper BackslashEscaper, cycleDepth uint, cycleSeen map[any]struct{}) {
	encodeWriteByte(w, '[')
	n := val.Len()
	for i := 0; i < n; i++ {
		if i > 0 {
			encodeWriteByte(w, ',')
		}
		encode(w, val.Index(i), escaper, false, cycleDepth, cycleSeen)
	}
	encodeWriteByte(w, ']')
}

func encodeTODO(w io.Writer, val reflect.Value) {
	bs, err := json.Marshal(val.Interface())
	if err != nil {
		panic(encodeError{err})
	}
	if _, err := w.Write(bs); err != nil {
		panic(encodeError{err})
	}
}