summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/hashicorp/go-msgpack/codec/encode.go
blob: 4914be0c748bf90137d052f9eca89db2b79e8b3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a BSD-style license found in the LICENSE file.

package codec

import (
	"io"
	"reflect"
)

const (
	// Some tagging information for error messages.
	msgTagEnc         = "codec.encoder"
	defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024
	// maxTimeSecs32 = math.MaxInt32 / 60 / 24 / 366
)

// AsSymbolFlag defines what should be encoded as symbols.
type AsSymbolFlag uint8

const (
	// AsSymbolDefault is default.
	// Currently, this means only encode struct field names as symbols.
	// The default is subject to change.
	AsSymbolDefault AsSymbolFlag = iota

	// AsSymbolAll means encode anything which could be a symbol as a symbol.
	AsSymbolAll = 0xfe

	// AsSymbolNone means do not encode anything as a symbol.
	AsSymbolNone = 1 << iota

	// AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols.
	AsSymbolMapStringKeysFlag

	// AsSymbolStructFieldName means encode struct field names as symbols.
	AsSymbolStructFieldNameFlag
)

// encWriter abstracting writing to a byte array or to an io.Writer.
type encWriter interface {
	writeUint16(uint16)
	writeUint32(uint32)
	writeUint64(uint64)
	writeb([]byte)
	writestr(string)
	writen1(byte)
	writen2(byte, byte)
	atEndOfEncode()
}

// encDriver abstracts the actual codec (binc vs msgpack, etc)
type encDriver interface {
	isBuiltinType(rt uintptr) bool
	encodeBuiltin(rt uintptr, v interface{})
	encodeNil()
	encodeInt(i int64)
	encodeUint(i uint64)
	encodeBool(b bool)
	encodeFloat32(f float32)
	encodeFloat64(f float64)
	encodeExtPreamble(xtag byte, length int)
	encodeArrayPreamble(length int)
	encodeMapPreamble(length int)
	encodeString(c charEncoding, v string)
	encodeSymbol(v string)
	encodeStringBytes(c charEncoding, v []byte)
	//TODO
	//encBignum(f *big.Int)
	//encStringRunes(c charEncoding, v []rune)
}

type ioEncWriterWriter interface {
	WriteByte(c byte) error
	WriteString(s string) (n int, err error)
	Write(p []byte) (n int, err error)
}

type ioEncStringWriter interface {
	WriteString(s string) (n int, err error)
}

type EncodeOptions struct {
	// Encode a struct as an array, and not as a map.
	StructToArray bool

	// AsSymbols defines what should be encoded as symbols.
	//
	// Encoding as symbols can reduce the encoded size significantly.
	//
	// However, during decoding, each string to be encoded as a symbol must
	// be checked to see if it has been seen before. Consequently, encoding time
	// will increase if using symbols, because string comparisons has a clear cost.
	//
	// Sample values:
	//   AsSymbolNone
	//   AsSymbolAll
	//   AsSymbolMapStringKeys
	//   AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag
	AsSymbols AsSymbolFlag
}

// ---------------------------------------------

type simpleIoEncWriterWriter struct {
	w  io.Writer
	bw io.ByteWriter
	sw ioEncStringWriter
}

func (o *simpleIoEncWriterWriter) WriteByte(c byte) (err error) {
	if o.bw != nil {
		return o.bw.WriteByte(c)
	}
	_, err = o.w.Write([]byte{c})
	return
}

func (o *simpleIoEncWriterWriter) WriteString(s string) (n int, err error) {
	if o.sw != nil {
		return o.sw.WriteString(s)
	}
	return o.w.Write([]byte(s))
}

func (o *simpleIoEncWriterWriter) Write(p []byte) (n int, err error) {
	return o.w.Write(p)
}

// ----------------------------------------

// ioEncWriter implements encWriter and can write to an io.Writer implementation
type ioEncWriter struct {
	w ioEncWriterWriter
	x [8]byte // temp byte array re-used internally for efficiency
}

func (z *ioEncWriter) writeUint16(v uint16) {
	bigen.PutUint16(z.x[:2], v)
	z.writeb(z.x[:2])
}

func (z *ioEncWriter) writeUint32(v uint32) {
	bigen.PutUint32(z.x[:4], v)
	z.writeb(z.x[:4])
}

func (z *ioEncWriter) writeUint64(v uint64) {
	bigen.PutUint64(z.x[:8], v)
	z.writeb(z.x[:8])
}

func (z *ioEncWriter) writeb(bs []byte) {
	if len(bs) == 0 {
		return
	}
	n, err := z.w.Write(bs)
	if err != nil {
		panic(err)
	}
	if n != len(bs) {
		encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(bs), n)
	}
}

func (z *ioEncWriter) writestr(s string) {
	n, err := z.w.WriteString(s)
	if err != nil {
		panic(err)
	}
	if n != len(s) {
		encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(s), n)
	}
}

func (z *ioEncWriter) writen1(b byte) {
	if err := z.w.WriteByte(b); err != nil {
		panic(err)
	}
}

func (z *ioEncWriter) writen2(b1 byte, b2 byte) {
	z.writen1(b1)
	z.writen1(b2)
}

func (z *ioEncWriter) atEndOfEncode() {}

// ----------------------------------------

// bytesEncWriter implements encWriter and can write to an byte slice.
// It is used by Marshal function.
type bytesEncWriter struct {
	b   []byte
	c   int     // cursor
	out *[]byte // write out on atEndOfEncode
}

func (z *bytesEncWriter) writeUint16(v uint16) {
	c := z.grow(2)
	z.b[c] = byte(v >> 8)
	z.b[c+1] = byte(v)
}

func (z *bytesEncWriter) writeUint32(v uint32) {
	c := z.grow(4)
	z.b[c] = byte(v >> 24)
	z.b[c+1] = byte(v >> 16)
	z.b[c+2] = byte(v >> 8)
	z.b[c+3] = byte(v)
}

func (z *bytesEncWriter) writeUint64(v uint64) {
	c := z.grow(8)
	z.b[c] = byte(v >> 56)
	z.b[c+1] = byte(v >> 48)
	z.b[c+2] = byte(v >> 40)
	z.b[c+3] = byte(v >> 32)
	z.b[c+4] = byte(v >> 24)
	z.b[c+5] = byte(v >> 16)
	z.b[c+6] = byte(v >> 8)
	z.b[c+7] = byte(v)
}

func (z *bytesEncWriter) writeb(s []byte) {
	if len(s) == 0 {
		return
	}
	c := z.grow(len(s))
	copy(z.b[c:], s)
}

func (z *bytesEncWriter) writestr(s string) {
	c := z.grow(len(s))
	copy(z.b[c:], s)
}

func (z *bytesEncWriter) writen1(b1 byte) {
	c := z.grow(1)
	z.b[c] = b1
}

func (z *bytesEncWriter) writen2(b1 byte, b2 byte) {
	c := z.grow(2)
	z.b[c] = b1
	z.b[c+1] = b2
}

func (z *bytesEncWriter) atEndOfEncode() {
	*(z.out) = z.b[:z.c]
}

func (z *bytesEncWriter) grow(n int) (oldcursor int) {
	oldcursor = z.c
	z.c = oldcursor + n
	if z.c > cap(z.b) {
		// Tried using appendslice logic: (if cap < 1024, *2, else *1.25).
		// However, it was too expensive, causing too many iterations of copy.
		// Using bytes.Buffer model was much better (2*cap + n)
		bs := make([]byte, 2*cap(z.b)+n)
		copy(bs, z.b[:oldcursor])
		z.b = bs
	} else if z.c > len(z.b) {
		z.b = z.b[:cap(z.b)]
	}
	return
}

// ---------------------------------------------

type encFnInfo struct {
	ti    *typeInfo
	e     *Encoder
	ee    encDriver
	xfFn  func(reflect.Value) ([]byte, error)
	xfTag byte
}

func (f *encFnInfo) builtin(rv reflect.Value) {
	f.ee.encodeBuiltin(f.ti.rtid, rv.Interface())
}

func (f *encFnInfo) rawExt(rv reflect.Value) {
	f.e.encRawExt(rv.Interface().(RawExt))
}

func (f *encFnInfo) ext(rv reflect.Value) {
	bs, fnerr := f.xfFn(rv)
	if fnerr != nil {
		panic(fnerr)
	}
	if bs == nil {
		f.ee.encodeNil()
		return
	}
	if f.e.hh.writeExt() {
		f.ee.encodeExtPreamble(f.xfTag, len(bs))
		f.e.w.writeb(bs)
	} else {
		f.ee.encodeStringBytes(c_RAW, bs)
	}

}

func (f *encFnInfo) binaryMarshal(rv reflect.Value) {
	var bm binaryMarshaler
	if f.ti.mIndir == 0 {
		bm = rv.Interface().(binaryMarshaler)
	} else if f.ti.mIndir == -1 {
		bm = rv.Addr().Interface().(binaryMarshaler)
	} else {
		for j, k := int8(0), f.ti.mIndir; j < k; j++ {
			if rv.IsNil() {
				f.ee.encodeNil()
				return
			}
			rv = rv.Elem()
		}
		bm = rv.Interface().(binaryMarshaler)
	}
	// debugf(">>>> binaryMarshaler: %T", rv.Interface())
	bs, fnerr := bm.MarshalBinary()
	if fnerr != nil {
		panic(fnerr)
	}
	if bs == nil {
		f.ee.encodeNil()
	} else {
		f.ee.encodeStringBytes(c_RAW, bs)
	}
}

func (f *encFnInfo) kBool(rv reflect.Value) {
	f.ee.encodeBool(rv.Bool())
}

func (f *encFnInfo) kString(rv reflect.Value) {
	f.ee.encodeString(c_UTF8, rv.String())
}

func (f *encFnInfo) kFloat64(rv reflect.Value) {
	f.ee.encodeFloat64(rv.Float())
}

func (f *encFnInfo) kFloat32(rv reflect.Value) {
	f.ee.encodeFloat32(float32(rv.Float()))
}

func (f *encFnInfo) kInt(rv reflect.Value) {
	f.ee.encodeInt(rv.Int())
}

func (f *encFnInfo) kUint(rv reflect.Value) {
	f.ee.encodeUint(rv.Uint())
}

func (f *encFnInfo) kInvalid(rv reflect.Value) {
	f.ee.encodeNil()
}

func (f *encFnInfo) kErr(rv reflect.Value) {
	encErr("Unsupported kind: %s, for: %#v", rv.Kind(), rv)
}

func (f *encFnInfo) kSlice(rv reflect.Value) {
	if rv.IsNil() {
		f.ee.encodeNil()
		return
	}

	if shortCircuitReflectToFastPath {
		switch f.ti.rtid {
		case intfSliceTypId:
			f.e.encSliceIntf(rv.Interface().([]interface{}))
			return
		case strSliceTypId:
			f.e.encSliceStr(rv.Interface().([]string))
			return
		case uint64SliceTypId:
			f.e.encSliceUint64(rv.Interface().([]uint64))
			return
		case int64SliceTypId:
			f.e.encSliceInt64(rv.Interface().([]int64))
			return
		}
	}

	// If in this method, then there was no extension function defined.
	// So it's okay to treat as []byte.
	if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
		f.ee.encodeStringBytes(c_RAW, rv.Bytes())
		return
	}

	l := rv.Len()
	if f.ti.mbs {
		if l%2 == 1 {
			encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
		}
		f.ee.encodeMapPreamble(l / 2)
	} else {
		f.ee.encodeArrayPreamble(l)
	}
	if l == 0 {
		return
	}
	for j := 0; j < l; j++ {
		// TODO: Consider perf implication of encoding odd index values as symbols if type is string
		f.e.encodeValue(rv.Index(j))
	}
}

func (f *encFnInfo) kArray(rv reflect.Value) {
	// We cannot share kSlice method, because the array may be non-addressable.
	// E.g. type struct S{B [2]byte}; Encode(S{}) will bomb on "panic: slice of unaddressable array".
	// So we have to duplicate the functionality here.
	// f.e.encodeValue(rv.Slice(0, rv.Len()))
	// f.kSlice(rv.Slice(0, rv.Len()))

	l := rv.Len()
	// Handle an array of bytes specially (in line with what is done for slices)
	if f.ti.rt.Elem().Kind() == reflect.Uint8 {
		if l == 0 {
			f.ee.encodeStringBytes(c_RAW, nil)
			return
		}
		var bs []byte
		if rv.CanAddr() {
			bs = rv.Slice(0, l).Bytes()
		} else {
			bs = make([]byte, l)
			for i := 0; i < l; i++ {
				bs[i] = byte(rv.Index(i).Uint())
			}
		}
		f.ee.encodeStringBytes(c_RAW, bs)
		return
	}

	if f.ti.mbs {
		if l%2 == 1 {
			encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
		}
		f.ee.encodeMapPreamble(l / 2)
	} else {
		f.ee.encodeArrayPreamble(l)
	}
	if l == 0 {
		return
	}
	for j := 0; j < l; j++ {
		// TODO: Consider perf implication of encoding odd index values as symbols if type is string
		f.e.encodeValue(rv.Index(j))
	}
}

func (f *encFnInfo) kStruct(rv reflect.Value) {
	fti := f.ti
	newlen := len(fti.sfi)
	rvals := make([]reflect.Value, newlen)
	var encnames []string
	e := f.e
	tisfi := fti.sfip
	toMap := !(fti.toArray || e.h.StructToArray)
	// if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
	if toMap {
		tisfi = fti.sfi
		encnames = make([]string, newlen)
	}
	newlen = 0
	for _, si := range tisfi {
		if si.i != -1 {
			rvals[newlen] = rv.Field(int(si.i))
		} else {
			rvals[newlen] = rv.FieldByIndex(si.is)
		}
		if toMap {
			if si.omitEmpty && isEmptyValue(rvals[newlen]) {
				continue
			}
			encnames[newlen] = si.encName
		} else {
			if si.omitEmpty && isEmptyValue(rvals[newlen]) {
				rvals[newlen] = reflect.Value{} //encode as nil
			}
		}
		newlen++
	}

	// debugf(">>>> kStruct: newlen: %v", newlen)
	if toMap {
		ee := f.ee //don't dereference everytime
		ee.encodeMapPreamble(newlen)
		// asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
		asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
		for j := 0; j < newlen; j++ {
			if asSymbols {
				ee.encodeSymbol(encnames[j])
			} else {
				ee.encodeString(c_UTF8, encnames[j])
			}
			e.encodeValue(rvals[j])
		}
	} else {
		f.ee.encodeArrayPreamble(newlen)
		for j := 0; j < newlen; j++ {
			e.encodeValue(rvals[j])
		}
	}
}

// func (f *encFnInfo) kPtr(rv reflect.Value) {
// 	debugf(">>>>>>> ??? encode kPtr called - shouldn't get called")
// 	if rv.IsNil() {
// 		f.ee.encodeNil()
// 		return
// 	}
// 	f.e.encodeValue(rv.Elem())
// }

func (f *encFnInfo) kInterface(rv reflect.Value) {
	if rv.IsNil() {
		f.ee.encodeNil()
		return
	}
	f.e.encodeValue(rv.Elem())
}

func (f *encFnInfo) kMap(rv reflect.Value) {
	if rv.IsNil() {
		f.ee.encodeNil()
		return
	}

	if shortCircuitReflectToFastPath {
		switch f.ti.rtid {
		case mapIntfIntfTypId:
			f.e.encMapIntfIntf(rv.Interface().(map[interface{}]interface{}))
			return
		case mapStrIntfTypId:
			f.e.encMapStrIntf(rv.Interface().(map[string]interface{}))
			return
		case mapStrStrTypId:
			f.e.encMapStrStr(rv.Interface().(map[string]string))
			return
		case mapInt64IntfTypId:
			f.e.encMapInt64Intf(rv.Interface().(map[int64]interface{}))
			return
		case mapUint64IntfTypId:
			f.e.encMapUint64Intf(rv.Interface().(map[uint64]interface{}))
			return
		}
	}

	l := rv.Len()
	f.ee.encodeMapPreamble(l)
	if l == 0 {
		return
	}
	// keyTypeIsString := f.ti.rt.Key().Kind() == reflect.String
	keyTypeIsString := f.ti.rt.Key() == stringTyp
	var asSymbols bool
	if keyTypeIsString {
		asSymbols = f.e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
	}
	mks := rv.MapKeys()
	// for j, lmks := 0, len(mks); j < lmks; j++ {
	for j := range mks {
		if keyTypeIsString {
			if asSymbols {
				f.ee.encodeSymbol(mks[j].String())
			} else {
				f.ee.encodeString(c_UTF8, mks[j].String())
			}
		} else {
			f.e.encodeValue(mks[j])
		}
		f.e.encodeValue(rv.MapIndex(mks[j]))
	}

}

// --------------------------------------------------

// encFn encapsulates the captured variables and the encode function.
// This way, we only do some calculations one times, and pass to the
// code block that should be called (encapsulated in a function)
// instead of executing the checks every time.
type encFn struct {
	i *encFnInfo
	f func(*encFnInfo, reflect.Value)
}

// --------------------------------------------------

// An Encoder writes an object to an output stream in the codec format.
type Encoder struct {
	w  encWriter
	e  encDriver
	h  *BasicHandle
	hh Handle
	f  map[uintptr]encFn
	x  []uintptr
	s  []encFn
}

// NewEncoder returns an Encoder for encoding into an io.Writer.
//
// For efficiency, Users are encouraged to pass in a memory buffered writer
// (eg bufio.Writer, bytes.Buffer).
func NewEncoder(w io.Writer, h Handle) *Encoder {
	ww, ok := w.(ioEncWriterWriter)
	if !ok {
		sww := simpleIoEncWriterWriter{w: w}
		sww.bw, _ = w.(io.ByteWriter)
		sww.sw, _ = w.(ioEncStringWriter)
		ww = &sww
		//ww = bufio.NewWriterSize(w, defEncByteBufSize)
	}
	z := ioEncWriter{
		w: ww,
	}
	return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
}

// NewEncoderBytes returns an encoder for encoding directly and efficiently
// into a byte slice, using zero-copying to temporary slices.
//
// It will potentially replace the output byte slice pointed to.
// After encoding, the out parameter contains the encoded contents.
func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
	in := *out
	if in == nil {
		in = make([]byte, defEncByteBufSize)
	}
	z := bytesEncWriter{
		b:   in,
		out: out,
	}
	return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
}

// Encode writes an object into a stream in the codec format.
//
// Encoding can be configured via the "codec" struct tag for the fields.
//
// The "codec" key in struct field's tag value is the key name,
// followed by an optional comma and options.
//
// To set an option on all fields (e.g. omitempty on all fields), you
// can create a field called _struct, and set flags on it.
//
// Struct values "usually" encode as maps. Each exported struct field is encoded unless:
//    - the field's codec tag is "-", OR
//    - the field is empty and its codec tag specifies the "omitempty" option.
//
// When encoding as a map, the first string in the tag (before the comma)
// is the map key string to use when encoding.
//
// However, struct values may encode as arrays. This happens when:
//    - StructToArray Encode option is set, OR
//    - the codec tag on the _struct field sets the "toarray" option
//
// Values with types that implement MapBySlice are encoded as stream maps.
//
// The empty values (for omitempty option) are false, 0, any nil pointer
// or interface value, and any array, slice, map, or string of length zero.
//
// Anonymous fields are encoded inline if no struct tag is present.
// Else they are encoded as regular fields.
//
// Examples:
//
//      type MyStruct struct {
//          _struct bool    `codec:",omitempty"`   //set omitempty for every field
//          Field1 string   `codec:"-"`            //skip this field
//          Field2 int      `codec:"myName"`       //Use key "myName" in encode stream
//          Field3 int32    `codec:",omitempty"`   //use key "Field3". Omit if empty.
//          Field4 bool     `codec:"f4,omitempty"` //use key "f4". Omit if empty.
//          ...
//      }
//
//      type MyStruct struct {
//          _struct bool    `codec:",omitempty,toarray"`   //set omitempty for every field
//                                                         //and encode struct as an array
//      }
//
// The mode of encoding is based on the type of the value. When a value is seen:
//   - If an extension is registered for it, call that extension function
//   - If it implements BinaryMarshaler, call its MarshalBinary() (data []byte, err error)
//   - Else encode it based on its reflect.Kind
//
// Note that struct field names and keys in map[string]XXX will be treated as symbols.
// Some formats support symbols (e.g. binc) and will properly encode the string
// only once in the stream, and use a tag to refer to it thereafter.
func (e *Encoder) Encode(v interface{}) (err error) {
	defer panicToErr(&err)
	e.encode(v)
	e.w.atEndOfEncode()
	return
}

func (e *Encoder) encode(iv interface{}) {
	switch v := iv.(type) {
	case nil:
		e.e.encodeNil()

	case reflect.Value:
		e.encodeValue(v)

	case string:
		e.e.encodeString(c_UTF8, v)
	case bool:
		e.e.encodeBool(v)
	case int:
		e.e.encodeInt(int64(v))
	case int8:
		e.e.encodeInt(int64(v))
	case int16:
		e.e.encodeInt(int64(v))
	case int32:
		e.e.encodeInt(int64(v))
	case int64:
		e.e.encodeInt(v)
	case uint:
		e.e.encodeUint(uint64(v))
	case uint8:
		e.e.encodeUint(uint64(v))
	case uint16:
		e.e.encodeUint(uint64(v))
	case uint32:
		e.e.encodeUint(uint64(v))
	case uint64:
		e.e.encodeUint(v)
	case float32:
		e.e.encodeFloat32(v)
	case float64:
		e.e.encodeFloat64(v)

	case []interface{}:
		e.encSliceIntf(v)
	case []string:
		e.encSliceStr(v)
	case []int64:
		e.encSliceInt64(v)
	case []uint64:
		e.encSliceUint64(v)
	case []uint8:
		e.e.encodeStringBytes(c_RAW, v)

	case map[interface{}]interface{}:
		e.encMapIntfIntf(v)
	case map[string]interface{}:
		e.encMapStrIntf(v)
	case map[string]string:
		e.encMapStrStr(v)
	case map[int64]interface{}:
		e.encMapInt64Intf(v)
	case map[uint64]interface{}:
		e.encMapUint64Intf(v)

	case *string:
		e.e.encodeString(c_UTF8, *v)
	case *bool:
		e.e.encodeBool(*v)
	case *int:
		e.e.encodeInt(int64(*v))
	case *int8:
		e.e.encodeInt(int64(*v))
	case *int16:
		e.e.encodeInt(int64(*v))
	case *int32:
		e.e.encodeInt(int64(*v))
	case *int64:
		e.e.encodeInt(*v)
	case *uint:
		e.e.encodeUint(uint64(*v))
	case *uint8:
		e.e.encodeUint(uint64(*v))
	case *uint16:
		e.e.encodeUint(uint64(*v))
	case *uint32:
		e.e.encodeUint(uint64(*v))
	case *uint64:
		e.e.encodeUint(*v)
	case *float32:
		e.e.encodeFloat32(*v)
	case *float64:
		e.e.encodeFloat64(*v)

	case *[]interface{}:
		e.encSliceIntf(*v)
	case *[]string:
		e.encSliceStr(*v)
	case *[]int64:
		e.encSliceInt64(*v)
	case *[]uint64:
		e.encSliceUint64(*v)
	case *[]uint8:
		e.e.encodeStringBytes(c_RAW, *v)

	case *map[interface{}]interface{}:
		e.encMapIntfIntf(*v)
	case *map[string]interface{}:
		e.encMapStrIntf(*v)
	case *map[string]string:
		e.encMapStrStr(*v)
	case *map[int64]interface{}:
		e.encMapInt64Intf(*v)
	case *map[uint64]interface{}:
		e.encMapUint64Intf(*v)

	default:
		e.encodeValue(reflect.ValueOf(iv))
	}
}

func (e *Encoder) encodeValue(rv reflect.Value) {
	for rv.Kind() == reflect.Ptr {
		if rv.IsNil() {
			e.e.encodeNil()
			return
		}
		rv = rv.Elem()
	}

	rt := rv.Type()
	rtid := reflect.ValueOf(rt).Pointer()

	// if e.f == nil && e.s == nil { debugf("---->Creating new enc f map for type: %v\n", rt) }
	var fn encFn
	var ok bool
	if useMapForCodecCache {
		fn, ok = e.f[rtid]
	} else {
		for i, v := range e.x {
			if v == rtid {
				fn, ok = e.s[i], true
				break
			}
		}
	}
	if !ok {
		// debugf("\tCreating new enc fn for type: %v\n", rt)
		fi := encFnInfo{ti: getTypeInfo(rtid, rt), e: e, ee: e.e}
		fn.i = &fi
		if rtid == rawExtTypId {
			fn.f = (*encFnInfo).rawExt
		} else if e.e.isBuiltinType(rtid) {
			fn.f = (*encFnInfo).builtin
		} else if xfTag, xfFn := e.h.getEncodeExt(rtid); xfFn != nil {
			fi.xfTag, fi.xfFn = xfTag, xfFn
			fn.f = (*encFnInfo).ext
		} else if supportBinaryMarshal && fi.ti.m {
			fn.f = (*encFnInfo).binaryMarshal
		} else {
			switch rk := rt.Kind(); rk {
			case reflect.Bool:
				fn.f = (*encFnInfo).kBool
			case reflect.String:
				fn.f = (*encFnInfo).kString
			case reflect.Float64:
				fn.f = (*encFnInfo).kFloat64
			case reflect.Float32:
				fn.f = (*encFnInfo).kFloat32
			case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16:
				fn.f = (*encFnInfo).kInt
			case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16:
				fn.f = (*encFnInfo).kUint
			case reflect.Invalid:
				fn.f = (*encFnInfo).kInvalid
			case reflect.Slice:
				fn.f = (*encFnInfo).kSlice
			case reflect.Array:
				fn.f = (*encFnInfo).kArray
			case reflect.Struct:
				fn.f = (*encFnInfo).kStruct
			// case reflect.Ptr:
			// 	fn.f = (*encFnInfo).kPtr
			case reflect.Interface:
				fn.f = (*encFnInfo).kInterface
			case reflect.Map:
				fn.f = (*encFnInfo).kMap
			default:
				fn.f = (*encFnInfo).kErr
			}
		}
		if useMapForCodecCache {
			if e.f == nil {
				e.f = make(map[uintptr]encFn, 16)
			}
			e.f[rtid] = fn
		} else {
			e.s = append(e.s, fn)
			e.x = append(e.x, rtid)
		}
	}

	fn.f(fn.i, rv)

}

func (e *Encoder) encRawExt(re RawExt) {
	if re.Data == nil {
		e.e.encodeNil()
		return
	}
	if e.hh.writeExt() {
		e.e.encodeExtPreamble(re.Tag, len(re.Data))
		e.w.writeb(re.Data)
	} else {
		e.e.encodeStringBytes(c_RAW, re.Data)
	}
}

// ---------------------------------------------
// short circuit functions for common maps and slices

func (e *Encoder) encSliceIntf(v []interface{}) {
	e.e.encodeArrayPreamble(len(v))
	for _, v2 := range v {
		e.encode(v2)
	}
}

func (e *Encoder) encSliceStr(v []string) {
	e.e.encodeArrayPreamble(len(v))
	for _, v2 := range v {
		e.e.encodeString(c_UTF8, v2)
	}
}

func (e *Encoder) encSliceInt64(v []int64) {
	e.e.encodeArrayPreamble(len(v))
	for _, v2 := range v {
		e.e.encodeInt(v2)
	}
}

func (e *Encoder) encSliceUint64(v []uint64) {
	e.e.encodeArrayPreamble(len(v))
	for _, v2 := range v {
		e.e.encodeUint(v2)
	}
}

func (e *Encoder) encMapStrStr(v map[string]string) {
	e.e.encodeMapPreamble(len(v))
	asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
	for k2, v2 := range v {
		if asSymbols {
			e.e.encodeSymbol(k2)
		} else {
			e.e.encodeString(c_UTF8, k2)
		}
		e.e.encodeString(c_UTF8, v2)
	}
}

func (e *Encoder) encMapStrIntf(v map[string]interface{}) {
	e.e.encodeMapPreamble(len(v))
	asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
	for k2, v2 := range v {
		if asSymbols {
			e.e.encodeSymbol(k2)
		} else {
			e.e.encodeString(c_UTF8, k2)
		}
		e.encode(v2)
	}
}

func (e *Encoder) encMapInt64Intf(v map[int64]interface{}) {
	e.e.encodeMapPreamble(len(v))
	for k2, v2 := range v {
		e.e.encodeInt(k2)
		e.encode(v2)
	}
}

func (e *Encoder) encMapUint64Intf(v map[uint64]interface{}) {
	e.e.encodeMapPreamble(len(v))
	for k2, v2 := range v {
		e.e.encodeUint(uint64(k2))
		e.encode(v2)
	}
}

func (e *Encoder) encMapIntfIntf(v map[interface{}]interface{}) {
	e.e.encodeMapPreamble(len(v))
	for k2, v2 := range v {
		e.encode(k2)
		e.encode(v2)
	}
}

// ----------------------------------------

func encErr(format string, params ...interface{}) {
	doPanic(msgTagEnc, format, params...)
}