Debian Codegraph @

encode.go

raw symbols SCIP
1 // Copyright 2016 Richard Gibson. All rights reserved.
2 // Copyright 2010 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // Package canonicaljson implements canonical serialization of Go
7 // objects to canonical-form JSON as specified at
8 // https://gibson042.github.io/canonicaljson-spec/ .
9 // The provided interface should match that of standard package
10 // "encoding/json" (from which it is derived) wherever they overlap (and
11 // in fact, this package is essentially a 2016-03-09 fork from
12 // golang/go@9d77ad8d34ce56e182adc30cd21af50a4b00932c:src/encoding/json
13 // ). Notable differences:
14 // - Object keys are sorted lexicographically by code point
15 // - Non-integer JSON numbers are represented in capital-E exponential
16 // notation with significand in (-10, 10) and no insignificant signs
17 // or zeroes beyond those required to force a decimal point.
18 // - JSON strings are represented in UTF-8 with minimal byte length,
19 // using escapes only when necessary for validity and Unicode
20 // escapes (uppercase hex) only when there is no shorter option.
21 package canonicaljson
22
23 import (
24 "bytes"
25 "encoding"
26 "encoding/base64"
27 "encoding/json"
28 "fmt"
29 "math"
30 "reflect"
31 "regexp"
32 "runtime"
33 "sort"
34 "strconv"
35 "strings"
36 "sync"
37 "unicode"
38 "unicode/utf8"
39 )
40
41 // Marshal returns the canonical UTF-8 JSON encoding of v.
42 //
43 // Marshal traverses the value v recursively.
44 // If an encountered value implements the json.Marshaler interface
45 // and is not a nil pointer, Marshal calls its MarshalJSON method
46 // to produce JSON. If no MarshalJSON method is present but the
47 // value implements encoding.TextMarshaler instead, Marshal calls
48 // its MarshalText method.
49 // The nil pointer exception is not strictly necessary
50 // but mimics a similar, necessary exception in the behavior of
51 // json.UnmarshalJSON.
52 //
53 // Otherwise, Marshal uses the following type-dependent default encodings:
54 //
55 // Boolean values encode as JSON booleans.
56 //
57 // Floating point, integer, and Number values encode as JSON numbers.
58 // Non-fractional values become sequences of digits without leading
59 // spaces; fractional values are represented in capital-E exponential
60 // notation with the shortest possible significand of magnitude less
61 // than 10 that includes at least one digit both before and after the
62 // decimal point, and the shortest possible non-empty exponent.
63 //
64 // String values encode as JSON strings, treating ill-formed UTF-8 input
65 // as an error (with the exception of "WTF-8" encodings of lone
66 // surrogates—code points U+D800 through U+DFFF [inclusive] that could
67 // not be interpreted as part of a surrogate pair).
68 // This is in contrast to encoding/json, which replaces ill-formed
69 // sequences with U+FFFD REPLACEMENT CHARACTER.
70 // Also in contrast to encoding/json, characters appear unescaped
71 // whenever possible.
72 // Control characters U+0000 through U+001F and lone surrogates U+D800
73 // through U+DFFF are replaced with their shortest escape sequence,
74 // 4 uppercase hex characters except for the following:
75 // - \b U+0008 BACKSPACE
76 // - \t U+0009 CHARACTER TABULATION ("tab")
77 // - \n U+000A LINE FEED ("newline")
78 // - \f U+000C FORM FEED
79 // - \r U+000D CARRIAGE RETURN
80 //
81 // Array and slice values encode as JSON arrays, except that
82 // []byte encodes as a base64-encoded string, and a nil slice
83 // encodes as the null JSON object.
84 //
85 // Struct values encode as JSON objects. Each exported struct field
86 // becomes a member of the object unless
87 // - the field's tag is "-", or
88 // - the field is empty and its tag specifies the "omitempty" option.
89 // The empty values are false, 0, any
90 // nil pointer or interface value, and any array, slice, map, or string of
91 // length zero. The object's default key string is the struct field name
92 // but can be specified in the struct field's tag value. The "json" key in
93 // the struct field's tag value is the key name, followed by an optional comma
94 // and options. Examples:
95 //
96 // // Field is ignored by this package.
97 // Field int `json:"-"`
98 //
99 // // Field appears in JSON as key "myName".
100 // Field int `json:"myName"`
101 //
102 // // Field appears in JSON as key "myName" and
103 // // the field is omitted from the object if its value is empty,
104 // // as defined above.
105 // Field int `json:"myName,omitempty"`
106 //
107 // // Field appears in JSON as key "Field" (the default), but
108 // // the field is skipped if empty.
109 // // Note the leading comma.
110 // Field int `json:",omitempty"`
111 //
112 // The "string" option signals that a field is stored as JSON inside a
113 // JSON-encoded string. It applies only to fields of string, floating point,
114 // integer, or boolean types. This extra level of encoding is sometimes used
115 // when communicating with JavaScript programs:
116 //
117 // Int64String int64 `json:",string"`
118 //
119 // The key name will be used if it's a non-empty string consisting of
120 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
121 // underscores and slashes.
122 //
123 // Anonymous struct fields are usually marshaled as if their inner exported fields
124 // were fields in the outer struct, subject to the usual Go visibility rules amended
125 // as described in the next paragraph.
126 // An anonymous struct field with a name given in its JSON tag is treated as
127 // having that name, rather than being anonymous.
128 // An anonymous struct field of interface type is treated the same as having
129 // that type as its name, rather than being anonymous.
130 //
131 // The Go visibility rules for struct fields are amended for JSON when
132 // deciding which field to marshal. If there are
133 // multiple fields at the same level, and that level is the least
134 // nested (and would therefore be the nesting level selected by the
135 // usual Go rules), the following extra rules apply:
136 //
137 // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
138 // even if there are multiple untagged fields that would otherwise conflict.
139 // 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
140 // 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
141 //
142 // Handling of anonymous struct fields is new in Go 1.1.
143 // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
144 // an anonymous struct field in both current and earlier versions, give the field
145 // a JSON tag of "-".
146 //
147 // Map values encode as JSON objects.
148 // The map's key type must be string; the map keys are used as JSON object
149 // keys, subject to the UTF-8 coercion described for string values above.
150 //
151 // Pointer values encode as the value pointed to.
152 // A nil pointer encodes as the null JSON object.
153 //
154 // Interface values encode as the value contained in the interface.
155 // A nil interface value encodes as the null JSON object.
156 //
157 // Channel, complex, and function values cannot be encoded in JSON.
158 // Attempting to encode such a value causes Marshal to return
159 // an UnsupportedTypeError.
160 //
161 // JSON cannot represent cyclic data structures and Marshal does not
162 // handle them. Passing cyclic structures to Marshal will result in
163 // an infinite recursion.
164 //
165 func Marshal(v interface{}) ([]byte, error) {
166 e := &encodeState{}
167 err := e.marshal(v)
168 if err != nil {
169 return nil, err
170 }
171 return e.Bytes(), nil
172 }
173
174 // MarshalIndent is like Marshal, but adds whitespace for more readable output.
175 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
176 b, err := Marshal(v)
177 if err != nil {
178 return nil, err
179 }
180 var buf bytes.Buffer
181 err = addIndentation(&buf, b, prefix, indent)
182 if err != nil {
183 return nil, err
184 }
185 return buf.Bytes(), nil
186 }
187
188 // Marshaler is the interface implemented by objects that
189 // can marshal themselves into valid JSON.
190 type Marshaler interface {
191 MarshalJSON() ([]byte, error)
192 }
193
194 // An UnsupportedTypeError is returned by Marshal when attempting
195 // to encode an unsupported value type.
196 type UnsupportedTypeError struct {
197 Type reflect.Type
198 }
199
200 func (e *UnsupportedTypeError) Error() string {
201 return "canonicaljson: unsupported type: " + e.Type.String()
202 }
203
204 type UnsupportedValueError struct {
205 Value reflect.Value
206 Str string
207 }
208
209 func (e *UnsupportedValueError) Error() string {
210 return "canonicaljson: unsupported value: " + e.Str
211 }
212
213 type MarshalerError struct {
214 Type reflect.Type
215 Err error
216 }
217
218 func (e *MarshalerError) Error() string {
219 return "canonicaljson: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
220 }
221
222 var hex = "0123456789ABCDEF"
223 var jsonNumberType = reflect.TypeOf(json.Number(""))
224
225 // An encodeState encodes JSON into a bytes.Buffer.
226 type encodeState struct {
227 bytes.Buffer // accumulated output
228 scratch [64]byte
229 }
230
231 var encodeStatePool sync.Pool
232
233 func newEncodeState() *encodeState {
234 if v := encodeStatePool.Get(); v != nil {
235 e := v.(*encodeState)
236 e.Reset()
237 return e
238 }
239 return new(encodeState)
240 }
241
242 func (e *encodeState) marshal(v interface{}) (err error) {
243 defer func() {
244 if r := recover(); r != nil {
245 if _, ok := r.(runtime.Error); ok {
246 panic(r)
247 }
248 if s, ok := r.(string); ok {
249 panic(s)
250 }
251 err = r.(error)
252 }
253 }()
254 e.reflectValue(reflect.ValueOf(v))
255 return nil
256 }
257
258 func (e *encodeState) error(err error) {
259 panic(err)
260 }
261
262 func isEmptyValue(v reflect.Value) bool {
263 switch v.Kind() {
264 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
265 return v.Len() == 0
266 case reflect.Bool:
267 return !v.Bool()
268 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
269 return v.Int() == 0
270 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
271 return v.Uint() == 0
272 case reflect.Float32, reflect.Float64:
273 return v.Float() == 0
274 case reflect.Interface, reflect.Ptr:
275 return v.IsNil()
276 }
277 return false
278 }
279
280 func (e *encodeState) reflectValue(v reflect.Value) {
281 valueEncoder(v)(e, v, false)
282 }
283
284 type encoderFunc func(e *encodeState, v reflect.Value, quoted bool)
285
286 var encoderCache struct {
287 sync.RWMutex
288 m map[reflect.Type]encoderFunc
289 }
290
291 func valueEncoder(v reflect.Value) encoderFunc {
292 if !v.IsValid() {
293 return invalidValueEncoder
294 }
295 return typeEncoder(v.Type())
296 }
297
298 func typeEncoder(t reflect.Type) encoderFunc {
299 encoderCache.RLock()
300 f := encoderCache.m[t]
301 encoderCache.RUnlock()
302 if f != nil {
303 return f
304 }
305
306 // To deal with recursive types, populate the map with an
307 // indirect func before we build it. This type waits on the
308 // real func (f) to be ready and then calls it. This indirect
309 // func is only used for recursive types.
310 encoderCache.Lock()
311 if encoderCache.m == nil {
312 encoderCache.m = make(map[reflect.Type]encoderFunc)
313 }
314 var wg sync.WaitGroup
315 wg.Add(1)
316 encoderCache.m[t] = func(e *encodeState, v reflect.Value, quoted bool) {
317 wg.Wait()
318 f(e, v, quoted)
319 }
320 encoderCache.Unlock()
321
322 // Compute fields without lock.
323 // Might duplicate effort but won't hold other computations back.
324 f = newTypeEncoder(t, true)
325 wg.Done()
326 encoderCache.Lock()
327 encoderCache.m[t] = f
328 encoderCache.Unlock()
329 return f
330 }
331
332 var (
333 marshalerType = reflect.TypeOf(new(json.Marshaler)).Elem()
334 textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
335 )
336
337 // newTypeEncoder constructs an encoderFunc for a type.
338 // The returned encoder only checks CanAddr when allowAddr is true.
339 func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
340 if t.Implements(marshalerType) {
341 return marshalerEncoder
342 }
343 if t.Kind() != reflect.Ptr && allowAddr {
344 if reflect.PtrTo(t).Implements(marshalerType) {
345 return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
346 }
347 }
348
349 if t.Implements(textMarshalerType) {
350 return textMarshalerEncoder
351 }
352 if t.Kind() != reflect.Ptr && allowAddr {
353 if reflect.PtrTo(t).Implements(textMarshalerType) {
354 return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
355 }
356 }
357
358 switch t.Kind() {
359 case reflect.Bool:
360 return boolEncoder
361 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
362 return intEncoder
363 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
364 return uintEncoder
365 case reflect.Float32:
366 return float32Encoder
367 case reflect.Float64:
368 return float64Encoder
369 case reflect.String:
370 return stringEncoder
371 case reflect.Interface:
372 return interfaceEncoder
373 case reflect.Struct:
374 return newStructEncoder(t)
375 case reflect.Map:
376 return newMapEncoder(t)
377 case reflect.Slice:
378 return newSliceEncoder(t)
379 case reflect.Array:
380 return newArrayEncoder(t)
381 case reflect.Ptr:
382 return newPtrEncoder(t)
383 default:
384 return unsupportedTypeEncoder
385 }
386 }
387
388 func invalidValueEncoder(e *encodeState, v reflect.Value, quoted bool) {
389 e.WriteString("null")
390 }
391
392 func marshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
393 if v.Kind() == reflect.Ptr && v.IsNil() {
394 e.WriteString("null")
395 return
396 }
397 m := v.Interface().(json.Marshaler)
398 b, err := m.MarshalJSON()
399
400 // Remarshal JSON, checking validity.
401 var data interface{}
402 var jsonBlob []byte
403 if err == nil {
404 err = Unmarshal(b, &data)
405 }
406 if err == nil {
407 jsonBlob, err = Marshal(data)
408 }
409 if err == nil {
410 e.Buffer.Write(jsonBlob)
411 }
412 if err != nil {
413 e.error(&MarshalerError{v.Type(), err})
414 }
415 }
416
417 func addrMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
418 va := v.Addr()
419 if va.IsNil() {
420 e.WriteString("null")
421 return
422 }
423 m := va.Interface().(json.Marshaler)
424 b, err := m.MarshalJSON()
425
426 // Remarshal JSON, checking validity.
427 var data interface{}
428 var jsonBlob []byte
429 if err == nil {
430 err = Unmarshal(b, &data)
431 }
432 if err == nil {
433 jsonBlob, err = Marshal(data)
434 }
435 if err == nil {
436 e.Buffer.Write(jsonBlob)
437 }
438 if err != nil {
439 e.error(&MarshalerError{v.Type(), err})
440 }
441 }
442
443 func textMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
444 if v.Kind() == reflect.Ptr && v.IsNil() {
445 e.WriteString("null")
446 return
447 }
448 m := v.Interface().(encoding.TextMarshaler)
449 b, err := m.MarshalText()
450 if err != nil {
451 e.error(&MarshalerError{v.Type(), err})
452 }
453 e.stringBytes(b)
454 }
455
456 func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
457 va := v.Addr()
458 if va.IsNil() {
459 e.WriteString("null")
460 return
461 }
462 m := va.Interface().(encoding.TextMarshaler)
463 b, err := m.MarshalText()
464 if err != nil {
465 e.error(&MarshalerError{v.Type(), err})
466 }
467 e.stringBytes(b)
468 }
469
470 func boolEncoder(e *encodeState, v reflect.Value, quoted bool) {
471 if quoted {
472 e.WriteByte('"')
473 }
474 if v.Bool() {
475 e.WriteString("true")
476 } else {
477 e.WriteString("false")
478 }
479 if quoted {
480 e.WriteByte('"')
481 }
482 }
483
484 func intEncoder(e *encodeState, v reflect.Value, quoted bool) {
485 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
486 if quoted {
487 e.WriteByte('"')
488 e.Write(b)
489 e.WriteByte('"')
490 } else {
491 e.Write(b)
492 }
493 }
494
495 func uintEncoder(e *encodeState, v reflect.Value, quoted bool) {
496 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
497 if quoted {
498 e.WriteByte('"')
499 e.Write(b)
500 e.WriteByte('"')
501 } else {
502 e.Write(b)
503 }
504 }
505
506 // Force capital-E exponent, remove + signs and leading zeroes
507 var expNormalizer = regexp.MustCompile("(?:E(?:[+]0*|(-|)0+)|e(?:[+]|(-|))0*)([0-9])")
508 var expNormalizerReplacement = "E$1$2$3"
509
510 // Find the significant digits in a numeric string
511 var significantDigits = regexp.MustCompile(`^(?:0(?:\.0*|)|)([0-9.]+?)(?:0*\.?0*|)(?:E|$)`)
512
513 // normalizeNumber normalizes a valid JSON numeric string and writes the result on its encoder.
514 func normalizeNumber(e *encodeState, stringBytes []byte) {
515 s := expNormalizer.ReplaceAllString(string(stringBytes), expNormalizerReplacement)
516
517 // detect negative sign
518 negative := s[0] == '-'
519 if negative {
520 s = s[1:]
521 }
522
523 // detect exponent
524 exp := 0
525 expPos := strings.LastIndexByte(s, 'E')
526 if expPos == -1 {
527 expPos = len(s)
528 } else {
529 var err error
530 exp, err = strconv.Atoi(s[expPos+1:])
531 if err != nil {
532 e.error(err)
533 }
534 }
535
536 // characterize the significant digits, finishing early on zero
537 significantRange := significantDigits.FindStringSubmatchIndex(s)
538 if significantRange == nil {
539 e.error(fmt.Errorf("canonicaljson: no significand in %q", s))
540 }
541 significantRange = significantRange[2:4]
542 if s[significantRange[0]] == '0' {
543 e.WriteByte('0')
544 return
545 }
546 pointPos := strings.IndexByte(s, '.')
547 effectivePointPos := pointPos
548 if effectivePointPos == -1 {
549 effectivePointPos = expPos
550 }
551 var significand string
552 if pointPos > significantRange[0] && pointPos < significantRange[1] {
553 significand = s[significantRange[0]:pointPos] + s[pointPos+1:significantRange[1]]
554 } else {
555 significand = s[significantRange[0]:significantRange[1]]
556 }
557
558 // detect integers (i.e., significand fits within exponent)
559 isInt := (exp <= 0 && (effectivePointPos+exp) >= significantRange[1]) ||
560 (exp > 0 && (effectivePointPos+exp+1) >= significantRange[1])
561
562 // effective exponent increases/decreases by excess/deficient significand magnitude
563 if effectivePointPos > 1 {
564 exp += effectivePointPos - 1
565 } else if significantRange[0] > 0 {
566 exp -= significantRange[0] - 1
567 }
568
569 // write result
570 if negative {
571 e.WriteByte('-')
572 }
573 if isInt {
574 // integer: render without exponent
575 e.WriteString(significand)
576 if len(significand) < exp+1 {
577 e.WriteString(strings.Repeat("0", exp+1-len(significand)))
578 }
579 } else {
580 // non-integer: render minimal significand with decimal point and non-empty exponent
581 if len(significand) == 1 {
582 significand += "0"
583 }
584 e.WriteString(significand[:1] + "." + significand[1:] + "E" + strconv.Itoa(exp))
585 }
586 }
587
588 type floatEncoder int // number of bits
589
590 func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
591 // Get a float value *not* equal to negative zero.
592 f := v.Float() + 0
593 if math.IsInf(f, 0) || math.IsNaN(f) {
594 e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
595 }
596 b := strconv.AppendFloat(e.scratch[:0], f, 'E', -1, int(bits))
597 if quoted {
598 e.WriteByte('"')
599 e.Write(b)
600 e.WriteByte('"')
601 } else {
602 normalizeNumber(e, b)
603 }
604 }
605
606 var (
607 float32Encoder = (floatEncoder(32)).encode
608 float64Encoder = (floatEncoder(64)).encode
609 )
610
611 func stringEncoder(e *encodeState, v reflect.Value, quoted bool) {
612 if t := v.Type(); t == numberType || t == jsonNumberType {
613 numStr := v.String()
614 if !isValidNumber(numStr) {
615 e.error(fmt.Errorf("canonicaljson: invalid number literal %q", numStr))
616 }
617 normalizeNumber(e, []byte(numStr))
618 return
619 }
620 if quoted {
621 sb, err := Marshal(v.String())
622 if err != nil {
623 e.error(err)
624 }
625 e.string(string(sb))
626 } else {
627 e.string(v.String())
628 }
629 }
630
631 func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) {
632 if v.IsNil() {
633 e.WriteString("null")
634 return
635 }
636 e.reflectValue(v.Elem())
637 }
638
639 func unsupportedTypeEncoder(e *encodeState, v reflect.Value, quoted bool) {
640 e.error(&UnsupportedTypeError{v.Type()})
641 }
642
643 type structEncoder struct {
644 fields []field
645 fieldEncs []encoderFunc
646 }
647
648 func (se *structEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
649 e.WriteByte('{')
650 first := true
651 for i, f := range se.fields {
652 fv := fieldByIndex(v, f.index)
653 if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) {
654 continue
655 }
656 if first {
657 first = false
658 } else {
659 e.WriteByte(',')
660 }
661 e.string(f.name)
662 e.WriteByte(':')
663 se.fieldEncs[i](e, fv, f.quoted)
664 }
665 e.WriteByte('}')
666 }
667
668 func newStructEncoder(t reflect.Type) encoderFunc {
669 fields := cachedTypeFields(t)
670 se := &structEncoder{
671 fields: fields,
672 fieldEncs: make([]encoderFunc, len(fields)),
673 }
674 for i, f := range fields {
675 se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index))
676 }
677 return se.encode
678 }
679
680 type mapEncoder struct {
681 elemEnc encoderFunc
682 }
683
684 func (me *mapEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
685 if v.IsNil() {
686 e.WriteString("null")
687 return
688 }
689 e.WriteByte('{')
690 var sv stringValues = v.MapKeys()
691 sort.Sort(sv)
692 for i, k := range sv {
693 if i > 0 {
694 e.WriteByte(',')
695 }
696 e.string(k.String())
697 e.WriteByte(':')
698 me.elemEnc(e, v.MapIndex(k), false)
699 }
700 e.WriteByte('}')
701 }
702
703 func newMapEncoder(t reflect.Type) encoderFunc {
704 if t.Key().Kind() != reflect.String {
705 return unsupportedTypeEncoder
706 }
707 me := &mapEncoder{typeEncoder(t.Elem())}
708 return me.encode
709 }
710
711 func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) {
712 if v.IsNil() {
713 e.WriteString("null")
714 return
715 }
716 s := v.Bytes()
717 e.WriteByte('"')
718 if len(s) < 1024 {
719 // for small buffers, using Encode directly is much faster.
720 dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
721 base64.StdEncoding.Encode(dst, s)
722 e.Write(dst)
723 } else {
724 // for large buffers, avoid unnecessary extra temporary
725 // buffer space.
726 enc := base64.NewEncoder(base64.StdEncoding, e)
727 enc.Write(s)
728 enc.Close()
729 }
730 e.WriteByte('"')
731 }
732
733 // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
734 type sliceEncoder struct {
735 arrayEnc encoderFunc
736 }
737
738 func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
739 if v.IsNil() {
740 e.WriteString("null")
741 return
742 }
743 se.arrayEnc(e, v, false)
744 }
745
746 func newSliceEncoder(t reflect.Type) encoderFunc {
747 // Byte slices get special treatment; arrays don't.
748 if t.Elem().Kind() == reflect.Uint8 {
749 return encodeByteSlice
750 }
751 enc := &sliceEncoder{newArrayEncoder(t)}
752 return enc.encode
753 }
754
755 type arrayEncoder struct {
756 elemEnc encoderFunc
757 }
758
759 func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
760 e.WriteByte('[')
761 n := v.Len()
762 for i := 0; i < n; i++ {
763 if i > 0 {
764 e.WriteByte(',')
765 }
766 ae.elemEnc(e, v.Index(i), false)
767 }
768 e.WriteByte(']')
769 }
770
771 func newArrayEncoder(t reflect.Type) encoderFunc {
772 enc := &arrayEncoder{typeEncoder(t.Elem())}
773 return enc.encode
774 }
775
776 type ptrEncoder struct {
777 elemEnc encoderFunc
778 }
779
780 func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
781 if v.IsNil() {
782 e.WriteString("null")
783 return
784 }
785 pe.elemEnc(e, v.Elem(), quoted)
786 }
787
788 func newPtrEncoder(t reflect.Type) encoderFunc {
789 enc := &ptrEncoder{typeEncoder(t.Elem())}
790 return enc.encode
791 }
792
793 type condAddrEncoder struct {
794 canAddrEnc, elseEnc encoderFunc
795 }
796
797 func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
798 if v.CanAddr() {
799 ce.canAddrEnc(e, v, quoted)
800 } else {
801 ce.elseEnc(e, v, quoted)
802 }
803 }
804
805 // newCondAddrEncoder returns an encoder that checks whether its value
806 // CanAddr and delegates to canAddrEnc if so, else to elseEnc.
807 func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
808 enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
809 return enc.encode
810 }
811
812 func isValidTag(s string) bool {
813 if s == "" {
814 return false
815 }
816 for _, c := range s {
817 switch {
818 case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
819 // Backslash and quote chars are reserved, but
820 // otherwise any punctuation chars are allowed
821 // in a tag name.
822 default:
823 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
824 return false
825 }
826 }
827 }
828 return true
829 }
830
831 func fieldByIndex(v reflect.Value, index []int) reflect.Value {
832 for _, i := range index {
833 if v.Kind() == reflect.Ptr {
834 if v.IsNil() {
835 return reflect.Value{}
836 }
837 v = v.Elem()
838 }
839 v = v.Field(i)
840 }
841 return v
842 }
843
844 func typeByIndex(t reflect.Type, index []int) reflect.Type {
845 for _, i := range index {
846 if t.Kind() == reflect.Ptr {
847 t = t.Elem()
848 }
849 t = t.Field(i).Type
850 }
851 return t
852 }
853
854 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
855 // It implements the methods to sort by string.
856 type stringValues []reflect.Value
857
858 func (sv stringValues) Len() int { return len(sv) }
859 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
860 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
861 func (sv stringValues) get(i int) string { return sv[i].String() }
862
863 func (e *encodeState) string(s string) int {
864 return e.stringBytes([]byte(s))
865 }
866
867 func (e *encodeState) stringBytes(s []byte) int {
868 len0 := e.Len()
869 e.WriteByte('"')
870 start := 0
871 rejectLowSurrogateAt := -1
872 for i := 0; i < len(s); {
873 if b := s[i]; b < utf8.RuneSelf {
874 if 0x20 <= b && b != '\\' && b != '"' {
875 i++
876 continue
877 }
878 if start < i {
879 e.Write(s[start:i])
880 }
881 e.WriteByte('\\')
882 switch b {
883 case '\\', '"':
884 e.WriteByte(b)
885 case '\n':
886 e.WriteByte('n')
887 case '\r':
888 e.WriteByte('r')
889 case '\t':
890 e.WriteByte('t')
891 case '\x08': // \b
892 e.WriteByte('b')
893 case '\x0c': // \f
894 e.WriteByte('f')
895 default:
896 // This encodes other bytes < 0x20 as \u00xx.
897 e.WriteString("u00")
898 e.WriteByte(hex[b>>4])
899 e.WriteByte(hex[b&0xF])
900 }
901 i++
902 start = i
903 continue
904 }
905 c, size := utf8.DecodeRune(s[i:])
906 if c == utf8.RuneError && size == 1 {
907 if start < i {
908 e.Write(s[start:i])
909 }
910
911 // Check for a "WTF-8" lone surrogate (and escape it).
912 // High surrogate (U+D800 through U+DBFF): 1110 1101 10 10bbbb 10 bbbbbb
913 // Low surrogate (U+DC00 through U+DFFF): 1110 1101 10 11bbbb 10 bbbbbb
914 if s[i] == 0xED && i+2 < len(s) {
915 c2 := s[i+1]
916 c3 := s[i+2]
917 if c2 >= 0xA0 && c2 <= 0xBF && (c3&0xC0) == 0x80 {
918 // Don't let this special-case logic sneak through a valid surrogate pair.
919 if isHigh := (c2 & 0x10) == 0; isHigh || i != rejectLowSurrogateAt {
920 if isHigh {
921 rejectLowSurrogateAt = i + 3
922 }
923 e.WriteString(`\u`)
924 e.WriteByte(hex[0xD])
925 e.WriteByte(hex[(c2>>2)&0x0F])
926 e.WriteByte(hex[((c2<<2)&0x0C)|((c3>>4)&0x03)])
927 e.WriteByte(hex[c3&0x0F])
928 i += 3
929 start = i
930 continue
931 }
932 }
933 }
934
935 e.error(&UnsupportedValueError{reflect.ValueOf(s), fmt.Sprintf("%q", string(s))})
936 }
937 i += size
938 }
939 if start < len(s) {
940 e.Write(s[start:])
941 }
942 e.WriteByte('"')
943 return e.Len() - len0
944 }
945
946 // A field represents a single field found in a struct.
947 type field struct {
948 name string
949 nameBytes []byte // []byte(name)
950 equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
951
952 tag bool
953 index []int
954 typ reflect.Type
955 omitEmpty bool
956 quoted bool
957 }
958
959 func fillField(f field) field {
960 f.nameBytes = []byte(f.name)
961 f.equalFold = foldFunc(f.nameBytes)
962 return f
963 }
964
965 // byName sorts field by name, breaking ties with depth,
966 // then breaking ties with "name came from json tag", then
967 // breaking ties with index sequence.
968 type byName []field
969
970 func (x byName) Len() int { return len(x) }
971
972 func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
973
974 func (x byName) Less(i, j int) bool {
975 if x[i].name != x[j].name {
976 return x[i].name < x[j].name
977 }
978 if len(x[i].index) != len(x[j].index) {
979 return len(x[i].index) < len(x[j].index)
980 }
981 if x[i].tag != x[j].tag {
982 return x[i].tag
983 }
984 return byIndex(x).Less(i, j)
985 }
986
987 // byIndex sorts field by index sequence.
988 type byIndex []field
989
990 func (x byIndex) Len() int { return len(x) }
991
992 func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
993
994 func (x byIndex) Less(i, j int) bool {
995 for k, xik := range x[i].index {
996 if k >= len(x[j].index) {
997 return false
998 }
999 if xik != x[j].index[k] {
1000 return xik < x[j].index[k]
1001 }
1002 }
1003 return len(x[i].index) < len(x[j].index)
1004 }
1005
1006 // typeFields returns a list of fields that JSON should recognize for the given type.
1007 // The algorithm is breadth-first search over the set of structs to include - the top struct
1008 // and then any reachable anonymous structs.
1009 func typeFields(t reflect.Type) []field {
1010 // Anonymous fields to explore at the current level and the next.
1011 current := []field{}
1012 next := []field{{typ: t}}
1013
1014 // Count of queued names for current level and the next.
1015 count := map[reflect.Type]int{}
1016 nextCount := map[reflect.Type]int{}
1017
1018 // Types already visited at an earlier level.
1019 visited := map[reflect.Type]bool{}
1020
1021 // Fields found.
1022 var fields []field
1023
1024 for len(next) > 0 {
1025 current, next = next, current[:0]
1026 count, nextCount = nextCount, map[reflect.Type]int{}
1027
1028 for _, f := range current {
1029 if visited[f.typ] {
1030 continue
1031 }
1032 visited[f.typ] = true
1033
1034 // Scan f.typ for fields to include.
1035 for i := 0; i < f.typ.NumField(); i++ {
1036 sf := f.typ.Field(i)
1037 if sf.PkgPath != "" && !sf.Anonymous { // unexported
1038 continue
1039 }
1040 tag := sf.Tag.Get("json")
1041 if tag == "-" {
1042 continue
1043 }
1044 name, opts := parseTag(tag)
1045 if !isValidTag(name) {
1046 name = ""
1047 }
1048 index := make([]int, len(f.index)+1)
1049 copy(index, f.index)
1050 index[len(f.index)] = i
1051
1052 ft := sf.Type
1053 if ft.Name() == "" && ft.Kind() == reflect.Ptr {
1054 // Follow pointer.
1055 ft = ft.Elem()
1056 }
1057
1058 // Only strings, floats, integers, and booleans can be quoted.
1059 quoted := false
1060 if opts.Contains("string") {
1061 switch ft.Kind() {
1062 case reflect.Bool,
1063 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
1064 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
1065 reflect.Float32, reflect.Float64,
1066 reflect.String:
1067 quoted = true
1068 }
1069 }
1070
1071 // Record found field and index sequence.
1072 if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
1073 tagged := name != ""
1074 if name == "" {
1075 name = sf.Name
1076 }
1077 fields = append(fields, fillField(field{
1078 name: name,
1079 tag: tagged,
1080 index: index,
1081 typ: ft,
1082 omitEmpty: opts.Contains("omitempty"),
1083 quoted: quoted,
1084 }))
1085 if count[f.typ] > 1 {
1086 // If there were multiple instances, add a second,
1087 // so that the annihilation code will see a duplicate.
1088 // It only cares about the distinction between 1 or 2,
1089 // so don't bother generating any more copies.
1090 fields = append(fields, fields[len(fields)-1])
1091 }
1092 continue
1093 }
1094
1095 // Record new anonymous struct to explore in next round.
1096 nextCount[ft]++
1097 if nextCount[ft] == 1 {
1098 next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
1099 }
1100 }
1101 }
1102 }
1103
1104 sort.Sort(byName(fields))
1105
1106 // Delete all fields that are hidden by the Go rules for embedded fields,
1107 // except that fields with JSON tags are promoted.
1108
1109 // The fields are sorted in primary order of name, secondary order
1110 // of field index length. Loop over names; for each name, delete
1111 // hidden fields by choosing the one dominant field that survives.
1112 out := fields[:0]
1113 for advance, i := 0, 0; i < len(fields); i += advance {
1114 // One iteration per name.
1115 // Find the sequence of fields with the name of this first field.
1116 fi := fields[i]
1117 name := fi.name
1118 for advance = 1; i+advance < len(fields); advance++ {
1119 fj := fields[i+advance]
1120 if fj.name != name {
1121 break
1122 }
1123 }
1124 if advance == 1 { // Only one field with this name
1125 out = append(out, fi)
1126 continue
1127 }
1128 dominant, ok := dominantField(fields[i : i+advance])
1129 if ok {
1130 out = append(out, dominant)
1131 }
1132 }
1133
1134 return out
1135 }
1136
1137 // dominantField looks through the fields, all of which are known to
1138 // have the same name, to find the single field that dominates the
1139 // others using Go's embedding rules, modified by the presence of
1140 // JSON tags. If there are multiple top-level fields, the boolean
1141 // will be false: This condition is an error in Go and we skip all
1142 // the fields.
1143 func dominantField(fields []field) (field, bool) {
1144 // The fields are sorted in increasing index-length order. The winner
1145 // must therefore be one with the shortest index length. Drop all
1146 // longer entries, which is easy: just truncate the slice.
1147 length := len(fields[0].index)
1148 tagged := -1 // Index of first tagged field.
1149 for i, f := range fields {
1150 if len(f.index) > length {
1151 fields = fields[:i]
1152 break
1153 }
1154 if f.tag {
1155 if tagged >= 0 {
1156 // Multiple tagged fields at the same level: conflict.
1157 // Return no field.
1158 return field{}, false
1159 }
1160 tagged = i
1161 }
1162 }
1163 if tagged >= 0 {
1164 return fields[tagged], true
1165 }
1166 // All remaining fields have the same length. If there's more than one,
1167 // we have a conflict (two fields named "X" at the same level) and we
1168 // return no field.
1169 if len(fields) > 1 {
1170 return field{}, false
1171 }
1172 return fields[0], true
1173 }
1174
1175 var fieldCache struct {
1176 sync.RWMutex
1177 m map[reflect.Type][]field
1178 }
1179
1180 // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
1181 func cachedTypeFields(t reflect.Type) []field {
1182 fieldCache.RLock()
1183 f := fieldCache.m[t]
1184 fieldCache.RUnlock()
1185 if f != nil {
1186 return f
1187 }
1188
1189 // Compute fields without lock.
1190 // Might duplicate effort but won't hold other computations back.
1191 f = typeFields(t)
1192 if f == nil {
1193 f = []field{}
1194 }
1195
1196 fieldCache.Lock()
1197 if fieldCache.m == nil {
1198 fieldCache.m = map[reflect.Type][]field{}
1199 }
1200 fieldCache.m[t] = f
1201 fieldCache.Unlock()
1202 return f
1203 }