summaryrefslogtreecommitdiff
path: root/encode.go
blob: 684cc75c477da3f9e0680bc21241f423eebdf677 (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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package lowmemjson

import (
	"bytes"
	"encoding"
	"encoding/base64"
	"fmt"
	"io"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"unsafe"

	"git.lukeshu.com/go/lowmemjson/internal/jsonstring"
	"git.lukeshu.com/go/lowmemjson/internal/jsonstruct"
)

// Encodable is the interface implemented by types that can encode
// themselves to JSON.  Encodable is a low-memory-overhead replacement
// for the json.Marshaler interface.
//
// The io.Writer passed to EncodeJSON returns an error if invalid JSON
// is written to it.
type Encodable interface {
	EncodeJSON(w io.Writer) error
}

// An Encoder encodes and writes values to a stream of JSON elements.
//
// Encoder is analogous to, and has a similar API to the standar
// library's encoding/json.Encoder.  Differences are that rather than
// having .SetEscapeHTML and .SetIndent methods, the io.Writer passed
// to it may be a *ReEncoder that has these settings (and more).  If
// something more similar to a json.Encoder is desired,
// lowmemjson/compat/json.Encoder offers those .SetEscapeHTML and
// .SetIndent methods.
type Encoder struct {
	w      *ReEncoder
	isRoot bool
}

// NewEncoder returns a new Encoder that writes 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.
//
// An Encoder tends to make many small writes; if w.Write calls are
// syscalls, then you may want to wrap w in a bufio.Writer.
func NewEncoder(w io.Writer) *Encoder {
	re, ok := w.(*ReEncoder)
	if !ok {
		re = NewReEncoder(w, ReEncoderConfig{
			AllowMultipleValues: true,
		})
	}
	return &Encoder{
		w:      re,
		isRoot: re.par.StackIsEmpty(),
	}
}

// Encode encodes obj to JSON and writes that JSON to the Encoder's
// output stream.
//
// See the [documentation for encoding/json.Marshal] for details about
// the conversion Go values to JSON; Encode behaves identically to
// that, with the exception that in addition to the json.Marshaler
// interface it also checks for the Encodable interface.
//
// Unlike encoding/json.Encoder.Encode, lowmemjson.Encoder.Encode does
// not buffer its output; if a encode-error is encountered, lowmemjson
// may write partial output, whereas encodin/json would not have
// written anything.
//
// [documentation for encoding/json.Marshal]: https://pkg.go.dev/encoding/json@go1.20#Marshal
func (enc *Encoder) Encode(obj any) (err error) {
	if enc.isRoot {
		enc.w.par.Reset()
	}
	escaper := enc.w.esc
	if escaper == nil {
		escaper = EscapeDefault
	}
	if err := encode(enc.w, reflect.ValueOf(obj), escaper, enc.w.utf, false, 0, map[any]struct{}{}); err != nil {
		if rwe, ok := err.(*ReEncodeWriteError); ok {
			err = &EncodeWriteError{
				Err:    rwe.Err,
				Offset: rwe.Offset,
			}
		}
		return err
	}
	if enc.isRoot {
		return enc.w.Close()
	}
	return nil
}

func discardInt(_ int, err error) error {
	return err
}

const startDetectingCyclesAfter = 1000

func encode(w *ReEncoder, val reflect.Value, escaper BackslashEscaper, utf InvalidUTF8Mode, quote bool, cycleDepth uint, cycleSeen map[any]struct{}) error {
	if !val.IsValid() {
		return discardInt(w.WriteString("null"))
	}
	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() {
			return discardInt(w.WriteString("null"))
		}
		obj, ok := val.Interface().(Encodable)
		if !ok {
			return discardInt(w.WriteString("null"))
		}
		w.pushWriteBarrier()
		if err := obj.EncodeJSON(w); err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "EncodeJSON",
				Err:        err,
			}
		}
		if err := w.Close(); err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "EncodeJSON",
				Err:        err,
			}
		}
		w.popWriteBarrier()

	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() {
			return discardInt(w.WriteString("null"))
		}
		obj, ok := val.Interface().(jsonMarshaler)
		if !ok {
			return discardInt(w.WriteString("null"))
		}
		dat, err := obj.MarshalJSON()
		if err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "MarshalJSON",
				Err:        err,
			}
		}
		w.pushWriteBarrier()
		if _, err := w.Write(dat); err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "MarshalJSON",
				Err:        err,
			}
		}
		if err := w.Close(); err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "MarshalJSON",
				Err:        err,
			}
		}
		w.popWriteBarrier()

	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() {
			return discardInt(w.WriteString("null"))
		}
		obj, ok := val.Interface().(encoding.TextMarshaler)
		if !ok {
			return discardInt(w.WriteString("null"))
		}
		text, err := obj.MarshalText()
		if err != nil {
			return &EncodeMethodError{
				Type:       val.Type(),
				SourceFunc: "MarshalText",
				Err:        err,
			}
		}
		if err := jsonstring.EncodeStringFromBytes(w, escaper, utf, val, text); err != nil {
			return err
		}
	default:
		switch val.Kind() {
		case reflect.Bool:
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
			if val.Bool() {
				if _, err := w.WriteString("true"); err != nil {
					return err
				}
			} else {
				if _, err := w.WriteString("false"); err != nil {
					return err
				}
			}
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
			// MaxInt64  =  9223372036854775807
			// MinInt64  =  -9223372036854775808
			//              0        1         2
			//              12345678901234567890
			var buf [20]byte
			if _, err := w.Write(strconv.AppendInt(buf[:0], val.Int(), 10)); err != nil {
				return err
			}
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
			// MaxUint64 = 18446744073709551615
			//             0        1         2
			//             12345678901234567890
			var buf [20]byte
			if _, err := w.Write(strconv.AppendUint(buf[:0], val.Uint(), 10)); err != nil {
				return err
			}
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
		case reflect.Float32:
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
			if err := encodeFloat(w, 32, val); err != nil {
				return err
			}
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
		case reflect.Float64:
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
			if err := encodeFloat(w, 64, val); err != nil {
				return err
			}
			if quote {
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			}
		case reflect.String:
			if val.Type() == numberType {
				numStr := val.String()
				if numStr == "" {
					numStr = "0"
				}
				if quote {
					if err := w.WriteByte('"'); err != nil {
						return err
					}
				}
				if _, err := w.WriteString(numStr); err != nil {
					return err
				}
				if quote {
					if err := w.WriteByte('"'); err != nil {
						return err
					}
				}
			} else {
				if quote {
					var buf bytes.Buffer
					if err := jsonstring.EncodeStringFromString(&buf, escaper, utf, val, val.String()); err != nil {
						return err
					}
					if err := jsonstring.EncodeStringFromBytes(w, escaper, utf, val, buf.Bytes()); err != nil {
						return err
					}
				} else {
					if err := jsonstring.EncodeStringFromString(w, escaper, utf, val, val.String()); err != nil {
						return err
					}
				}
			}
		case reflect.Interface:
			if val.IsNil() {
				if _, err := w.WriteString("null"); err != nil {
					return err
				}
			} else {
				if err := encode(w, val.Elem(), escaper, utf, quote, cycleDepth, cycleSeen); err != nil {
					return err
				}
			}
		case reflect.Struct:
			if err := w.WriteByte('{'); err != nil {
				return err
			}
			empty := true
			for _, field := range jsonstruct.IndexStruct(val.Type()).ByPos {
				fVal, err := val.FieldByIndexErr(field.Path)
				if err != nil {
					continue
				}
				if field.OmitEmpty && isEmptyValue(fVal) {
					continue
				}
				if !empty {
					if err := w.WriteByte(','); err != nil {
						return err
					}
				}
				empty = false
				if err := jsonstring.EncodeStringFromString(w, escaper, utf, val, field.Name); err != nil {
					return err
				}
				if err := w.WriteByte(':'); err != nil {
					return err
				}
				if err := encode(w, fVal, escaper, utf, field.Quote, cycleDepth, cycleSeen); err != nil {
					return err
				}
			}
			if err := w.WriteByte('}'); err != nil {
				return err
			}
		case reflect.Map:
			if val.IsNil() {
				return discardInt(w.WriteString("null"))
			}
			if val.Len() == 0 {
				return discardInt(w.WriteString("{}"))
			}
			if cycleDepth++; cycleDepth > startDetectingCyclesAfter {
				ptr := val.UnsafePointer()
				if _, seen := cycleSeen[ptr]; seen {
					return &EncodeValueError{
						Value: val,
						Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
					}
				}
				cycleSeen[ptr] = struct{}{}
				defer delete(cycleSeen, ptr)
			}
			if err := w.WriteByte('{'); err != nil {
				return err
			}

			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
				if err := encode(NewReEncoder(&k, ReEncoderConfig{BackslashEscape: escaper, InvalidUTF8: utf}), iter.Key(), escaper, utf, false, cycleDepth, cycleSeen); err != nil {
					return err
				}
				kStr := k.String()
				if kStr == "null" {
					kStr = `""`
				}
				if !strings.HasPrefix(kStr, `"`) {
					k.Reset()
					if err := jsonstring.EncodeStringFromString(&k, escaper, utf, iter.Key(), kStr); err != nil {
						return err
					}
					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 {
					if err := w.WriteByte(','); err != nil {
						return err
					}
				}
				if _, err := w.WriteString(kv.K); err != nil {
					return err
				}
				if err := w.WriteByte(':'); err != nil {
					return err
				}
				if err := encode(w, kv.V, escaper, utf, false, cycleDepth, cycleSeen); err != nil {
					return err
				}
			}
			if err := w.WriteByte('}'); err != nil {
				return err
			}
		case reflect.Slice:
			switch {
			case val.IsNil():
				if _, err := w.WriteString("null"); err != nil {
					return err
				}
			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)):
				if err := w.WriteByte('"'); err != nil {
					return err
				}
				enc := base64.NewEncoder(base64.StdEncoding, w)
				if val.CanConvert(byteSliceType) {
					if _, err := enc.Write(val.Convert(byteSliceType).Interface().([]byte)); err != nil {
						return 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 {
							return err
						}
					}
				}
				if err := enc.Close(); err != nil {
					return err
				}
				if err := w.WriteByte('"'); err != nil {
					return err
				}
			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 {
						return &EncodeValueError{
							Value: val,
							Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
						}
					}
					cycleSeen[ptr] = struct{}{}
					defer delete(cycleSeen, ptr)
				}
				if err := encodeArray(w, val, escaper, utf, cycleDepth, cycleSeen); err != nil {
					return err
				}
			}
		case reflect.Array:
			if err := encodeArray(w, val, escaper, utf, cycleDepth, cycleSeen); err != nil {
				return err
			}
		case reflect.Pointer:
			if val.IsNil() {
				if _, err := w.WriteString("null"); err != nil {
					return err
				}
			} else {
				if cycleDepth++; cycleDepth > startDetectingCyclesAfter {
					ptr := val.UnsafePointer()
					if _, seen := cycleSeen[ptr]; seen {
						return &EncodeValueError{
							Value: val,
							Str:   fmt.Sprintf("encountered a cycle via %s", val.Type()),
						}
					}
					cycleSeen[ptr] = struct{}{}
					defer delete(cycleSeen, ptr)
				}
				if err := encode(w, val.Elem(), escaper, utf, quote, cycleDepth, cycleSeen); err != nil {
					return err
				}
			}
		default:
			return &EncodeTypeError{
				Type: val.Type(),
			}
		}
	}
	return nil
}

func encodeArray(w *ReEncoder, val reflect.Value, escaper BackslashEscaper, utf InvalidUTF8Mode, cycleDepth uint, cycleSeen map[any]struct{}) error {
	if err := w.WriteByte('['); err != nil {
		return err
	}
	n := val.Len()
	for i := 0; i < n; i++ {
		if i > 0 {
			if err := w.WriteByte(','); err != nil {
				return err
			}
		}
		if err := encode(w, val.Index(i), escaper, utf, false, cycleDepth, cycleSeen); err != nil {
			return err
		}
	}
	if err := w.WriteByte(']'); err != nil {
		return err
	}
	return nil
}