Debian Codegraph @

encode.go

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