libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / encoding / json / encode.go
blob4a77ba1cd256e1f47709979c06325d64ddca8b88
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.
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 // http://golang.org/doc/articles/json_and_go.html
11 package json
13 import (
14 "bytes"
15 "encoding"
16 "encoding/base64"
17 "math"
18 "reflect"
19 "runtime"
20 "sort"
21 "strconv"
22 "strings"
23 "sync"
24 "unicode"
25 "unicode/utf8"
28 // Marshal returns the JSON encoding of v.
30 // Marshal traverses the value v recursively.
31 // If an encountered value implements the Marshaler interface
32 // and is not a nil pointer, Marshal calls its MarshalJSON method
33 // to produce JSON. The nil pointer exception is not strictly necessary
34 // but mimics a similar, necessary exception in the behavior of
35 // UnmarshalJSON.
37 // Otherwise, Marshal uses the following type-dependent default encodings:
39 // Boolean values encode as JSON booleans.
41 // Floating point, integer, and Number values encode as JSON numbers.
43 // String values encode as JSON strings. InvalidUTF8Error will be returned
44 // if an invalid UTF-8 sequence is encountered.
45 // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
46 // to keep some browsers from misinterpreting JSON output as HTML.
48 // Array and slice values encode as JSON arrays, except that
49 // []byte encodes as a base64-encoded string, and a nil slice
50 // encodes as the null JSON object.
52 // Struct values encode as JSON objects. Each exported struct field
53 // becomes a member of the object unless
54 // - the field's tag is "-", or
55 // - the field is empty and its tag specifies the "omitempty" option.
56 // The empty values are false, 0, any
57 // nil pointer or interface value, and any array, slice, map, or string of
58 // length zero. The object's default key string is the struct field name
59 // but can be specified in the struct field's tag value. The "json" key in
60 // the struct field's tag value is the key name, followed by an optional comma
61 // and options. Examples:
63 // // Field is ignored by this package.
64 // Field int `json:"-"`
66 // // Field appears in JSON as key "myName".
67 // Field int `json:"myName"`
69 // // Field appears in JSON as key "myName" and
70 // // the field is omitted from the object if its value is empty,
71 // // as defined above.
72 // Field int `json:"myName,omitempty"`
74 // // Field appears in JSON as key "Field" (the default), but
75 // // the field is skipped if empty.
76 // // Note the leading comma.
77 // Field int `json:",omitempty"`
79 // The "string" option signals that a field is stored as JSON inside a
80 // JSON-encoded string. It applies only to fields of string, floating point,
81 // or integer types. This extra level of encoding is sometimes used when
82 // communicating with JavaScript programs:
84 // Int64String int64 `json:",string"`
86 // The key name will be used if it's a non-empty string consisting of
87 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
88 // underscores and slashes.
90 // Anonymous struct fields are usually marshaled as if their inner exported fields
91 // were fields in the outer struct, subject to the usual Go visibility rules amended
92 // as described in the next paragraph.
93 // An anonymous struct field with a name given in its JSON tag is treated as
94 // having that name, rather than being anonymous.
96 // The Go visibility rules for struct fields are amended for JSON when
97 // deciding which field to marshal or unmarshal. If there are
98 // multiple fields at the same level, and that level is the least
99 // nested (and would therefore be the nesting level selected by the
100 // usual Go rules), the following extra rules apply:
102 // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
103 // even if there are multiple untagged fields that would otherwise conflict.
104 // 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
105 // 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
107 // Handling of anonymous struct fields is new in Go 1.1.
108 // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
109 // an anonymous struct field in both current and earlier versions, give the field
110 // a JSON tag of "-".
112 // Map values encode as JSON objects.
113 // The map's key type must be string; the object keys are used directly
114 // as map keys.
116 // Pointer values encode as the value pointed to.
117 // A nil pointer encodes as the null JSON object.
119 // Interface values encode as the value contained in the interface.
120 // A nil interface value encodes as the null JSON object.
122 // Channel, complex, and function values cannot be encoded in JSON.
123 // Attempting to encode such a value causes Marshal to return
124 // an UnsupportedTypeError.
126 // JSON cannot represent cyclic data structures and Marshal does not
127 // handle them. Passing cyclic structures to Marshal will result in
128 // an infinite recursion.
130 func Marshal(v interface{}) ([]byte, error) {
131 e := &encodeState{}
132 err := e.marshal(v)
133 if err != nil {
134 return nil, err
136 return e.Bytes(), nil
139 // MarshalIndent is like Marshal but applies Indent to format the output.
140 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
141 b, err := Marshal(v)
142 if err != nil {
143 return nil, err
145 var buf bytes.Buffer
146 err = Indent(&buf, b, prefix, indent)
147 if err != nil {
148 return nil, err
150 return buf.Bytes(), nil
153 // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
154 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
155 // so that the JSON will be safe to embed inside HTML <script> tags.
156 // For historical reasons, web browsers don't honor standard HTML
157 // escaping within <script> tags, so an alternative JSON encoding must
158 // be used.
159 func HTMLEscape(dst *bytes.Buffer, src []byte) {
160 // The characters can only appear in string literals,
161 // so just scan the string one byte at a time.
162 start := 0
163 for i, c := range src {
164 if c == '<' || c == '>' || c == '&' {
165 if start < i {
166 dst.Write(src[start:i])
168 dst.WriteString(`\u00`)
169 dst.WriteByte(hex[c>>4])
170 dst.WriteByte(hex[c&0xF])
171 start = i + 1
173 // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
174 if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
175 if start < i {
176 dst.Write(src[start:i])
178 dst.WriteString(`\u202`)
179 dst.WriteByte(hex[src[i+2]&0xF])
180 start = i + 3
183 if start < len(src) {
184 dst.Write(src[start:])
188 // Marshaler is the interface implemented by objects that
189 // can marshal themselves into valid JSON.
190 type Marshaler interface {
191 MarshalJSON() ([]byte, error)
194 // An UnsupportedTypeError is returned by Marshal when attempting
195 // to encode an unsupported value type.
196 type UnsupportedTypeError struct {
197 Type reflect.Type
200 func (e *UnsupportedTypeError) Error() string {
201 return "json: unsupported type: " + e.Type.String()
204 type UnsupportedValueError struct {
205 Value reflect.Value
206 Str string
209 func (e *UnsupportedValueError) Error() string {
210 return "json: unsupported value: " + e.Str
213 // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
214 // attempting to encode a string value with invalid UTF-8 sequences.
215 // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
216 // replacing invalid bytes with the Unicode replacement rune U+FFFD.
217 // This error is no longer generated but is kept for backwards compatibility
218 // with programs that might mention it.
219 type InvalidUTF8Error struct {
220 S string // the whole string value that caused the error
223 func (e *InvalidUTF8Error) Error() string {
224 return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
227 type MarshalerError struct {
228 Type reflect.Type
229 Err error
232 func (e *MarshalerError) Error() string {
233 return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
236 var hex = "0123456789abcdef"
238 // An encodeState encodes JSON into a bytes.Buffer.
239 type encodeState struct {
240 bytes.Buffer // accumulated output
241 scratch [64]byte
244 var encodeStatePool sync.Pool
246 func newEncodeState() *encodeState {
247 if v := encodeStatePool.Get(); v != nil {
248 e := v.(*encodeState)
249 e.Reset()
250 return e
252 return new(encodeState)
255 func (e *encodeState) marshal(v interface{}) (err error) {
256 defer func() {
257 if r := recover(); r != nil {
258 if _, ok := r.(runtime.Error); ok {
259 panic(r)
261 if s, ok := r.(string); ok {
262 panic(s)
264 err = r.(error)
267 e.reflectValue(reflect.ValueOf(v))
268 return nil
271 func (e *encodeState) error(err error) {
272 panic(err)
275 var byteSliceType = reflect.TypeOf([]byte(nil))
277 func isEmptyValue(v reflect.Value) bool {
278 switch v.Kind() {
279 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
280 return v.Len() == 0
281 case reflect.Bool:
282 return !v.Bool()
283 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
284 return v.Int() == 0
285 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
286 return v.Uint() == 0
287 case reflect.Float32, reflect.Float64:
288 return v.Float() == 0
289 case reflect.Interface, reflect.Ptr:
290 return v.IsNil()
292 return false
295 func (e *encodeState) reflectValue(v reflect.Value) {
296 valueEncoder(v)(e, v, false)
299 type encoderFunc func(e *encodeState, v reflect.Value, quoted bool)
301 var encoderCache struct {
302 sync.RWMutex
303 m map[reflect.Type]encoderFunc
306 func valueEncoder(v reflect.Value) encoderFunc {
307 if !v.IsValid() {
308 return invalidValueEncoder
310 return typeEncoder(v.Type())
313 func typeEncoder(t reflect.Type) encoderFunc {
314 encoderCache.RLock()
315 f := encoderCache.m[t]
316 encoderCache.RUnlock()
317 if f != nil {
318 return f
321 // To deal with recursive types, populate the map with an
322 // indirect func before we build it. This type waits on the
323 // real func (f) to be ready and then calls it. This indirect
324 // func is only used for recursive types.
325 encoderCache.Lock()
326 if encoderCache.m == nil {
327 encoderCache.m = make(map[reflect.Type]encoderFunc)
329 var wg sync.WaitGroup
330 wg.Add(1)
331 encoderCache.m[t] = func(e *encodeState, v reflect.Value, quoted bool) {
332 wg.Wait()
333 f(e, v, quoted)
335 encoderCache.Unlock()
337 // Compute fields without lock.
338 // Might duplicate effort but won't hold other computations back.
339 f = newTypeEncoder(t, true)
340 wg.Done()
341 encoderCache.Lock()
342 encoderCache.m[t] = f
343 encoderCache.Unlock()
344 return f
347 var (
348 marshalerType = reflect.TypeOf(new(Marshaler)).Elem()
349 textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
352 // newTypeEncoder constructs an encoderFunc for a type.
353 // The returned encoder only checks CanAddr when allowAddr is true.
354 func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
355 if t.Implements(marshalerType) {
356 return marshalerEncoder
358 if t.Kind() != reflect.Ptr && allowAddr {
359 if reflect.PtrTo(t).Implements(marshalerType) {
360 return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
364 if t.Implements(textMarshalerType) {
365 return textMarshalerEncoder
367 if t.Kind() != reflect.Ptr && allowAddr {
368 if reflect.PtrTo(t).Implements(textMarshalerType) {
369 return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
373 switch t.Kind() {
374 case reflect.Bool:
375 return boolEncoder
376 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
377 return intEncoder
378 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
379 return uintEncoder
380 case reflect.Float32:
381 return float32Encoder
382 case reflect.Float64:
383 return float64Encoder
384 case reflect.String:
385 return stringEncoder
386 case reflect.Interface:
387 return interfaceEncoder
388 case reflect.Struct:
389 return newStructEncoder(t)
390 case reflect.Map:
391 return newMapEncoder(t)
392 case reflect.Slice:
393 return newSliceEncoder(t)
394 case reflect.Array:
395 return newArrayEncoder(t)
396 case reflect.Ptr:
397 return newPtrEncoder(t)
398 default:
399 return unsupportedTypeEncoder
403 func invalidValueEncoder(e *encodeState, v reflect.Value, quoted bool) {
404 e.WriteString("null")
407 func marshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
408 if v.Kind() == reflect.Ptr && v.IsNil() {
409 e.WriteString("null")
410 return
412 m := v.Interface().(Marshaler)
413 b, err := m.MarshalJSON()
414 if err == nil {
415 // copy JSON into buffer, checking validity.
416 err = compact(&e.Buffer, b, true)
418 if err != nil {
419 e.error(&MarshalerError{v.Type(), err})
423 func addrMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
424 va := v.Addr()
425 if va.IsNil() {
426 e.WriteString("null")
427 return
429 m := va.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)
435 if err != nil {
436 e.error(&MarshalerError{v.Type(), err})
440 func textMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
441 if v.Kind() == reflect.Ptr && v.IsNil() {
442 e.WriteString("null")
443 return
445 m := v.Interface().(encoding.TextMarshaler)
446 b, err := m.MarshalText()
447 if err == nil {
448 _, err = e.stringBytes(b)
450 if err != nil {
451 e.error(&MarshalerError{v.Type(), err})
455 func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
456 va := v.Addr()
457 if va.IsNil() {
458 e.WriteString("null")
459 return
461 m := va.Interface().(encoding.TextMarshaler)
462 b, err := m.MarshalText()
463 if err == nil {
464 _, err = e.stringBytes(b)
466 if err != nil {
467 e.error(&MarshalerError{v.Type(), err})
471 func boolEncoder(e *encodeState, v reflect.Value, quoted bool) {
472 if quoted {
473 e.WriteByte('"')
475 if v.Bool() {
476 e.WriteString("true")
477 } else {
478 e.WriteString("false")
480 if quoted {
481 e.WriteByte('"')
485 func intEncoder(e *encodeState, v reflect.Value, quoted bool) {
486 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
487 if quoted {
488 e.WriteByte('"')
490 e.Write(b)
491 if quoted {
492 e.WriteByte('"')
496 func uintEncoder(e *encodeState, v reflect.Value, quoted bool) {
497 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
498 if quoted {
499 e.WriteByte('"')
501 e.Write(b)
502 if quoted {
503 e.WriteByte('"')
507 type floatEncoder int // number of bits
509 func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
510 f := v.Float()
511 if math.IsInf(f, 0) || math.IsNaN(f) {
512 e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
514 b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
515 if quoted {
516 e.WriteByte('"')
518 e.Write(b)
519 if quoted {
520 e.WriteByte('"')
524 var (
525 float32Encoder = (floatEncoder(32)).encode
526 float64Encoder = (floatEncoder(64)).encode
529 func stringEncoder(e *encodeState, v reflect.Value, quoted bool) {
530 if v.Type() == numberType {
531 numStr := v.String()
532 if numStr == "" {
533 numStr = "0" // Number's zero-val
535 e.WriteString(numStr)
536 return
538 if quoted {
539 sb, err := Marshal(v.String())
540 if err != nil {
541 e.error(err)
543 e.string(string(sb))
544 } else {
545 e.string(v.String())
549 func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) {
550 if v.IsNil() {
551 e.WriteString("null")
552 return
554 e.reflectValue(v.Elem())
557 func unsupportedTypeEncoder(e *encodeState, v reflect.Value, quoted bool) {
558 e.error(&UnsupportedTypeError{v.Type()})
561 type structEncoder struct {
562 fields []field
563 fieldEncs []encoderFunc
566 func (se *structEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
567 e.WriteByte('{')
568 first := true
569 for i, f := range se.fields {
570 fv := fieldByIndex(v, f.index)
571 if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) {
572 continue
574 if first {
575 first = false
576 } else {
577 e.WriteByte(',')
579 e.string(f.name)
580 e.WriteByte(':')
581 se.fieldEncs[i](e, fv, f.quoted)
583 e.WriteByte('}')
586 func newStructEncoder(t reflect.Type) encoderFunc {
587 fields := cachedTypeFields(t)
588 se := &structEncoder{
589 fields: fields,
590 fieldEncs: make([]encoderFunc, len(fields)),
592 for i, f := range fields {
593 se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index))
595 return se.encode
598 type mapEncoder struct {
599 elemEnc encoderFunc
602 func (me *mapEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
603 if v.IsNil() {
604 e.WriteString("null")
605 return
607 e.WriteByte('{')
608 var sv stringValues = v.MapKeys()
609 sort.Sort(sv)
610 for i, k := range sv {
611 if i > 0 {
612 e.WriteByte(',')
614 e.string(k.String())
615 e.WriteByte(':')
616 me.elemEnc(e, v.MapIndex(k), false)
618 e.WriteByte('}')
621 func newMapEncoder(t reflect.Type) encoderFunc {
622 if t.Key().Kind() != reflect.String {
623 return unsupportedTypeEncoder
625 me := &mapEncoder{typeEncoder(t.Elem())}
626 return me.encode
629 func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) {
630 if v.IsNil() {
631 e.WriteString("null")
632 return
634 s := v.Bytes()
635 e.WriteByte('"')
636 if len(s) < 1024 {
637 // for small buffers, using Encode directly is much faster.
638 dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
639 base64.StdEncoding.Encode(dst, s)
640 e.Write(dst)
641 } else {
642 // for large buffers, avoid unnecessary extra temporary
643 // buffer space.
644 enc := base64.NewEncoder(base64.StdEncoding, e)
645 enc.Write(s)
646 enc.Close()
648 e.WriteByte('"')
651 // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
652 type sliceEncoder struct {
653 arrayEnc encoderFunc
656 func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
657 if v.IsNil() {
658 e.WriteString("null")
659 return
661 se.arrayEnc(e, v, false)
664 func newSliceEncoder(t reflect.Type) encoderFunc {
665 // Byte slices get special treatment; arrays don't.
666 if t.Elem().Kind() == reflect.Uint8 {
667 return encodeByteSlice
669 enc := &sliceEncoder{newArrayEncoder(t)}
670 return enc.encode
673 type arrayEncoder struct {
674 elemEnc encoderFunc
677 func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
678 e.WriteByte('[')
679 n := v.Len()
680 for i := 0; i < n; i++ {
681 if i > 0 {
682 e.WriteByte(',')
684 ae.elemEnc(e, v.Index(i), false)
686 e.WriteByte(']')
689 func newArrayEncoder(t reflect.Type) encoderFunc {
690 enc := &arrayEncoder{typeEncoder(t.Elem())}
691 return enc.encode
694 type ptrEncoder struct {
695 elemEnc encoderFunc
698 func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
699 if v.IsNil() {
700 e.WriteString("null")
701 return
703 pe.elemEnc(e, v.Elem(), false)
706 func newPtrEncoder(t reflect.Type) encoderFunc {
707 enc := &ptrEncoder{typeEncoder(t.Elem())}
708 return enc.encode
711 type condAddrEncoder struct {
712 canAddrEnc, elseEnc encoderFunc
715 func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
716 if v.CanAddr() {
717 ce.canAddrEnc(e, v, quoted)
718 } else {
719 ce.elseEnc(e, v, quoted)
723 // newCondAddrEncoder returns an encoder that checks whether its value
724 // CanAddr and delegates to canAddrEnc if so, else to elseEnc.
725 func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
726 enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
727 return enc.encode
730 func isValidTag(s string) bool {
731 if s == "" {
732 return false
734 for _, c := range s {
735 switch {
736 case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
737 // Backslash and quote chars are reserved, but
738 // otherwise any punctuation chars are allowed
739 // in a tag name.
740 default:
741 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
742 return false
746 return true
749 func fieldByIndex(v reflect.Value, index []int) reflect.Value {
750 for _, i := range index {
751 if v.Kind() == reflect.Ptr {
752 if v.IsNil() {
753 return reflect.Value{}
755 v = v.Elem()
757 v = v.Field(i)
759 return v
762 func typeByIndex(t reflect.Type, index []int) reflect.Type {
763 for _, i := range index {
764 if t.Kind() == reflect.Ptr {
765 t = t.Elem()
767 t = t.Field(i).Type
769 return t
772 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
773 // It implements the methods to sort by string.
774 type stringValues []reflect.Value
776 func (sv stringValues) Len() int { return len(sv) }
777 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
778 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
779 func (sv stringValues) get(i int) string { return sv[i].String() }
781 // NOTE: keep in sync with stringBytes below.
782 func (e *encodeState) string(s string) (int, error) {
783 len0 := e.Len()
784 e.WriteByte('"')
785 start := 0
786 for i := 0; i < len(s); {
787 if b := s[i]; b < utf8.RuneSelf {
788 if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
790 continue
792 if start < i {
793 e.WriteString(s[start:i])
795 switch b {
796 case '\\', '"':
797 e.WriteByte('\\')
798 e.WriteByte(b)
799 case '\n':
800 e.WriteByte('\\')
801 e.WriteByte('n')
802 case '\r':
803 e.WriteByte('\\')
804 e.WriteByte('r')
805 default:
806 // This encodes bytes < 0x20 except for \n and \r,
807 // as well as < and >. The latter are escaped because they
808 // can lead to security holes when user-controlled strings
809 // are rendered into JSON and served to some browsers.
810 e.WriteString(`\u00`)
811 e.WriteByte(hex[b>>4])
812 e.WriteByte(hex[b&0xF])
815 start = i
816 continue
818 c, size := utf8.DecodeRuneInString(s[i:])
819 if c == utf8.RuneError && size == 1 {
820 if start < i {
821 e.WriteString(s[start:i])
823 e.WriteString(`\ufffd`)
824 i += size
825 start = i
826 continue
828 // U+2028 is LINE SEPARATOR.
829 // U+2029 is PARAGRAPH SEPARATOR.
830 // They are both technically valid characters in JSON strings,
831 // but don't work in JSONP, which has to be evaluated as JavaScript,
832 // and can lead to security holes there. It is valid JSON to
833 // escape them, so we do so unconditionally.
834 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
835 if c == '\u2028' || c == '\u2029' {
836 if start < i {
837 e.WriteString(s[start:i])
839 e.WriteString(`\u202`)
840 e.WriteByte(hex[c&0xF])
841 i += size
842 start = i
843 continue
845 i += size
847 if start < len(s) {
848 e.WriteString(s[start:])
850 e.WriteByte('"')
851 return e.Len() - len0, nil
854 // NOTE: keep in sync with string above.
855 func (e *encodeState) stringBytes(s []byte) (int, error) {
856 len0 := e.Len()
857 e.WriteByte('"')
858 start := 0
859 for i := 0; i < len(s); {
860 if b := s[i]; b < utf8.RuneSelf {
861 if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
863 continue
865 if start < i {
866 e.Write(s[start:i])
868 switch b {
869 case '\\', '"':
870 e.WriteByte('\\')
871 e.WriteByte(b)
872 case '\n':
873 e.WriteByte('\\')
874 e.WriteByte('n')
875 case '\r':
876 e.WriteByte('\\')
877 e.WriteByte('r')
878 default:
879 // This encodes bytes < 0x20 except for \n and \r,
880 // as well as < and >. The latter are escaped because they
881 // can lead to security holes when user-controlled strings
882 // are rendered into JSON and served to some browsers.
883 e.WriteString(`\u00`)
884 e.WriteByte(hex[b>>4])
885 e.WriteByte(hex[b&0xF])
888 start = i
889 continue
891 c, size := utf8.DecodeRune(s[i:])
892 if c == utf8.RuneError && size == 1 {
893 if start < i {
894 e.Write(s[start:i])
896 e.WriteString(`\ufffd`)
897 i += size
898 start = i
899 continue
901 // U+2028 is LINE SEPARATOR.
902 // U+2029 is PARAGRAPH SEPARATOR.
903 // They are both technically valid characters in JSON strings,
904 // but don't work in JSONP, which has to be evaluated as JavaScript,
905 // and can lead to security holes there. It is valid JSON to
906 // escape them, so we do so unconditionally.
907 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
908 if c == '\u2028' || c == '\u2029' {
909 if start < i {
910 e.Write(s[start:i])
912 e.WriteString(`\u202`)
913 e.WriteByte(hex[c&0xF])
914 i += size
915 start = i
916 continue
918 i += size
920 if start < len(s) {
921 e.Write(s[start:])
923 e.WriteByte('"')
924 return e.Len() - len0, nil
927 // A field represents a single field found in a struct.
928 type field struct {
929 name string
930 nameBytes []byte // []byte(name)
931 equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
933 tag bool
934 index []int
935 typ reflect.Type
936 omitEmpty bool
937 quoted bool
940 func fillField(f field) field {
941 f.nameBytes = []byte(f.name)
942 f.equalFold = foldFunc(f.nameBytes)
943 return f
946 // byName sorts field by name, breaking ties with depth,
947 // then breaking ties with "name came from json tag", then
948 // breaking ties with index sequence.
949 type byName []field
951 func (x byName) Len() int { return len(x) }
953 func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
955 func (x byName) Less(i, j int) bool {
956 if x[i].name != x[j].name {
957 return x[i].name < x[j].name
959 if len(x[i].index) != len(x[j].index) {
960 return len(x[i].index) < len(x[j].index)
962 if x[i].tag != x[j].tag {
963 return x[i].tag
965 return byIndex(x).Less(i, j)
968 // byIndex sorts field by index sequence.
969 type byIndex []field
971 func (x byIndex) Len() int { return len(x) }
973 func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
975 func (x byIndex) Less(i, j int) bool {
976 for k, xik := range x[i].index {
977 if k >= len(x[j].index) {
978 return false
980 if xik != x[j].index[k] {
981 return xik < x[j].index[k]
984 return len(x[i].index) < len(x[j].index)
987 // typeFields returns a list of fields that JSON should recognize for the given type.
988 // The algorithm is breadth-first search over the set of structs to include - the top struct
989 // and then any reachable anonymous structs.
990 func typeFields(t reflect.Type) []field {
991 // Anonymous fields to explore at the current level and the next.
992 current := []field{}
993 next := []field{{typ: t}}
995 // Count of queued names for current level and the next.
996 count := map[reflect.Type]int{}
997 nextCount := map[reflect.Type]int{}
999 // Types already visited at an earlier level.
1000 visited := map[reflect.Type]bool{}
1002 // Fields found.
1003 var fields []field
1005 for len(next) > 0 {
1006 current, next = next, current[:0]
1007 count, nextCount = nextCount, map[reflect.Type]int{}
1009 for _, f := range current {
1010 if visited[f.typ] {
1011 continue
1013 visited[f.typ] = true
1015 // Scan f.typ for fields to include.
1016 for i := 0; i < f.typ.NumField(); i++ {
1017 sf := f.typ.Field(i)
1018 if sf.PkgPath != "" { // unexported
1019 continue
1021 tag := sf.Tag.Get("json")
1022 if tag == "-" {
1023 continue
1025 name, opts := parseTag(tag)
1026 if !isValidTag(name) {
1027 name = ""
1029 index := make([]int, len(f.index)+1)
1030 copy(index, f.index)
1031 index[len(f.index)] = i
1033 ft := sf.Type
1034 if ft.Name() == "" && ft.Kind() == reflect.Ptr {
1035 // Follow pointer.
1036 ft = ft.Elem()
1039 // Record found field and index sequence.
1040 if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
1041 tagged := name != ""
1042 if name == "" {
1043 name = sf.Name
1045 fields = append(fields, fillField(field{
1046 name: name,
1047 tag: tagged,
1048 index: index,
1049 typ: ft,
1050 omitEmpty: opts.Contains("omitempty"),
1051 quoted: opts.Contains("string"),
1053 if count[f.typ] > 1 {
1054 // If there were multiple instances, add a second,
1055 // so that the annihilation code will see a duplicate.
1056 // It only cares about the distinction between 1 or 2,
1057 // so don't bother generating any more copies.
1058 fields = append(fields, fields[len(fields)-1])
1060 continue
1063 // Record new anonymous struct to explore in next round.
1064 nextCount[ft]++
1065 if nextCount[ft] == 1 {
1066 next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
1072 sort.Sort(byName(fields))
1074 // Delete all fields that are hidden by the Go rules for embedded fields,
1075 // except that fields with JSON tags are promoted.
1077 // The fields are sorted in primary order of name, secondary order
1078 // of field index length. Loop over names; for each name, delete
1079 // hidden fields by choosing the one dominant field that survives.
1080 out := fields[:0]
1081 for advance, i := 0, 0; i < len(fields); i += advance {
1082 // One iteration per name.
1083 // Find the sequence of fields with the name of this first field.
1084 fi := fields[i]
1085 name := fi.name
1086 for advance = 1; i+advance < len(fields); advance++ {
1087 fj := fields[i+advance]
1088 if fj.name != name {
1089 break
1092 if advance == 1 { // Only one field with this name
1093 out = append(out, fi)
1094 continue
1096 dominant, ok := dominantField(fields[i : i+advance])
1097 if ok {
1098 out = append(out, dominant)
1102 fields = out
1103 sort.Sort(byIndex(fields))
1105 return fields
1108 // dominantField looks through the fields, all of which are known to
1109 // have the same name, to find the single field that dominates the
1110 // others using Go's embedding rules, modified by the presence of
1111 // JSON tags. If there are multiple top-level fields, the boolean
1112 // will be false: This condition is an error in Go and we skip all
1113 // the fields.
1114 func dominantField(fields []field) (field, bool) {
1115 // The fields are sorted in increasing index-length order. The winner
1116 // must therefore be one with the shortest index length. Drop all
1117 // longer entries, which is easy: just truncate the slice.
1118 length := len(fields[0].index)
1119 tagged := -1 // Index of first tagged field.
1120 for i, f := range fields {
1121 if len(f.index) > length {
1122 fields = fields[:i]
1123 break
1125 if f.tag {
1126 if tagged >= 0 {
1127 // Multiple tagged fields at the same level: conflict.
1128 // Return no field.
1129 return field{}, false
1131 tagged = i
1134 if tagged >= 0 {
1135 return fields[tagged], true
1137 // All remaining fields have the same length. If there's more than one,
1138 // we have a conflict (two fields named "X" at the same level) and we
1139 // return no field.
1140 if len(fields) > 1 {
1141 return field{}, false
1143 return fields[0], true
1146 var fieldCache struct {
1147 sync.RWMutex
1148 m map[reflect.Type][]field
1151 // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
1152 func cachedTypeFields(t reflect.Type) []field {
1153 fieldCache.RLock()
1154 f := fieldCache.m[t]
1155 fieldCache.RUnlock()
1156 if f != nil {
1157 return f
1160 // Compute fields without lock.
1161 // Might duplicate effort but won't hold other computations back.
1162 f = typeFields(t)
1163 if f == nil {
1164 f = []field{}
1167 fieldCache.Lock()
1168 if fieldCache.m == nil {
1169 fieldCache.m = map[reflect.Type][]field{}
1171 fieldCache.m[t] = f
1172 fieldCache.Unlock()
1173 return f