Debian Codegraph @

canonical/json/encode.go

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