open-vault/vendor/github.com/ugorji/go/codec/encode.go

1455 lines
37 KiB
Go
Raw Normal View History

2015-06-29 21:50:55 +00:00
// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
2015-08-19 01:12:51 +00:00
// Use of this source code is governed by a MIT license found in the LICENSE file.
2015-06-29 21:50:55 +00:00
package codec
import (
"encoding"
"fmt"
"io"
"reflect"
"sort"
"sync"
)
const (
defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024
)
// 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 abstracts writing to a byte array or to an io.Writer.
type encWriter interface {
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)
EncodeRawExt(re *RawExt, e *Encoder)
EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder)
EncodeArrayStart(length int)
EncodeMapStart(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)
2015-10-30 22:07:00 +00:00
reset()
2015-06-29 21:50:55 +00:00
}
2015-09-22 15:44:21 +00:00
type encDriverAsis interface {
EncodeAsis(v []byte)
}
2015-06-29 21:50:55 +00:00
type encNoSeparator struct{}
2015-09-22 15:44:21 +00:00
func (_ encNoSeparator) EncodeEnd() {}
2015-06-29 21:50:55 +00:00
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
// Canonical representation means that encoding a value will always result in the same
// sequence of bytes.
//
2015-09-22 15:44:21 +00:00
// This only affects maps, as the iteration order for maps is random.
//
// The implementation MAY use the natural sort order for the map keys if possible:
//
// - If there is a natural sort order (ie for number, bool, string or []byte keys),
// then the map keys are first sorted in natural order and then written
// with corresponding map values to the strema.
// - If there is no natural sort order, then the map keys will first be
// encoded into []byte, and then sorted,
// before writing the sorted keys and the corresponding map values to the stream.
//
2015-06-29 21:50:55 +00:00
Canonical bool
2016-04-26 00:18:04 +00:00
// CheckCircularRef controls whether we check for circular references
// and error fast during an encode.
//
// If enabled, an error is received if a pointer to a struct
// references itself either directly or through one of its fields (iteratively).
//
// This is opt-in, as there may be a performance hit to checking circular references.
CheckCircularRef bool
2016-09-02 22:05:09 +00:00
// RecursiveEmptyCheck controls whether we descend into interfaces, structs and pointers
// when checking if a value is empty.
//
// Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls.
RecursiveEmptyCheck bool
2016-09-12 19:16:55 +00:00
// Raw controls whether we encode Raw values.
// This is a "dangerous" option and must be explicitly set.
// If set, we blindly encode Raw values as-is, without checking
// if they are a correct representation of a value in that format.
// If unset, we error out.
Raw bool
2015-06-29 21:50:55 +00:00
// 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
2016-04-26 00:18:04 +00:00
bs [1]byte
2015-06-29 21:50:55 +00:00
}
func (o *simpleIoEncWriterWriter) WriteByte(c byte) (err error) {
if o.bw != nil {
return o.bw.WriteByte(c)
}
2016-04-26 00:18:04 +00:00
// _, err = o.w.Write([]byte{c})
o.bs[0] = c
_, err = o.w.Write(o.bs[:])
2015-06-29 21:50:55 +00:00
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))
return o.w.Write(bytesView(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
2015-10-30 22:07:00 +00:00
s simpleIoEncWriterWriter
2015-06-29 21:50:55 +00:00
// x [8]byte // temp byte array re-used internally for efficiency
}
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) {
panic(fmt.Errorf("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) {
panic(fmt.Errorf("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) writeb(s []byte) {
if len(s) > 0 {
c := z.grow(len(s))
copy(z.b[c:], s)
}
}
func (z *bytesEncWriter) writestr(s string) {
if len(s) > 0 {
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+1] = b2
2016-06-01 14:24:48 +00:00
z.b[c] = b1
2015-06-29 21:50:55 +00:00
}
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 > len(z.b) {
if z.c > cap(z.b) {
2015-10-07 20:10:00 +00:00
// appendslice logic (if cap < 1024, *2, else *1.25): more expensive. many copy calls.
// bytes.Buffer model (2*cap + n): much better
// bs := make([]byte, 2*cap(z.b)+n)
bs := make([]byte, growCap(cap(z.b), 1, n))
2015-06-29 21:50:55 +00:00
copy(bs, z.b[:oldcursor])
z.b = bs
} else {
z.b = z.b[:cap(z.b)]
}
}
return
}
// ---------------------------------------------
2015-10-07 20:10:00 +00:00
type encFnInfo struct {
2015-06-29 21:50:55 +00:00
e *Encoder
ti *typeInfo
xfFn Ext
xfTag uint64
seq seqType
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) builtin(rv reflect.Value) {
f.e.e.EncodeBuiltin(f.ti.rtid, rv.Interface())
2015-06-29 21:50:55 +00:00
}
2016-09-12 19:16:55 +00:00
func (f *encFnInfo) raw(rv reflect.Value) {
f.e.raw(rv.Interface().(Raw))
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) rawExt(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
// rev := rv.Interface().(RawExt)
2015-10-07 20:10:00 +00:00
// f.e.e.EncodeRawExt(&rev, f.e)
2015-06-29 21:50:55 +00:00
var re *RawExt
if rv.CanAddr() {
re = rv.Addr().Interface().(*RawExt)
} else {
rev := rv.Interface().(RawExt)
re = &rev
}
2015-10-07 20:10:00 +00:00
f.e.e.EncodeRawExt(re, f.e)
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) ext(rv reflect.Value) {
2015-09-22 15:44:21 +00:00
// if this is a struct|array and it was addressable, then pass the address directly (not the value)
if k := rv.Kind(); (k == reflect.Struct || k == reflect.Array) && rv.CanAddr() {
2015-06-29 21:50:55 +00:00
rv = rv.Addr()
}
2015-10-07 20:10:00 +00:00
f.e.e.EncodeExt(rv.Interface(), f.xfTag, f.xfFn, f.e)
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) getValueForMarshalInterface(rv reflect.Value, indir int8) (v interface{}, proceed bool) {
2015-06-29 21:50:55 +00:00
if indir == 0 {
v = rv.Interface()
} else if indir == -1 {
2015-09-22 15:44:21 +00:00
// If a non-pointer was passed to Encode(), then that value is not addressable.
2016-07-23 00:11:47 +00:00
// Take addr if addressable, else copy value to an addressable value.
2015-09-22 15:44:21 +00:00
if rv.CanAddr() {
v = rv.Addr().Interface()
} else {
rv2 := reflect.New(rv.Type())
rv2.Elem().Set(rv)
v = rv2.Interface()
// fmt.Printf("rv.Type: %v, rv2.Type: %v, v: %v\n", rv.Type(), rv2.Type(), v)
}
2015-06-29 21:50:55 +00:00
} else {
for j := int8(0); j < indir; j++ {
if rv.IsNil() {
2015-10-07 20:10:00 +00:00
f.e.e.EncodeNil()
2015-06-29 21:50:55 +00:00
return
}
rv = rv.Elem()
}
v = rv.Interface()
}
return v, true
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) selferMarshal(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
if v, proceed := f.getValueForMarshalInterface(rv, f.ti.csIndir); proceed {
v.(Selfer).CodecEncodeSelf(f.e)
}
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) binaryMarshal(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
if v, proceed := f.getValueForMarshalInterface(rv, f.ti.bmIndir); proceed {
bs, fnerr := v.(encoding.BinaryMarshaler).MarshalBinary()
2015-09-22 15:44:21 +00:00
f.e.marshal(bs, fnerr, false, c_RAW)
2015-06-29 21:50:55 +00:00
}
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) textMarshal(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
if v, proceed := f.getValueForMarshalInterface(rv, f.ti.tmIndir); proceed {
// debugf(">>>> encoding.TextMarshaler: %T", rv.Interface())
bs, fnerr := v.(encoding.TextMarshaler).MarshalText()
2015-09-22 15:44:21 +00:00
f.e.marshal(bs, fnerr, false, c_UTF8)
}
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) jsonMarshal(rv reflect.Value) {
2015-09-22 15:44:21 +00:00
if v, proceed := f.getValueForMarshalInterface(rv, f.ti.jmIndir); proceed {
bs, fnerr := v.(jsonMarshaler).MarshalJSON()
f.e.marshal(bs, fnerr, true, c_UTF8)
2015-06-29 21:50:55 +00:00
}
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kBool(rv reflect.Value) {
f.e.e.EncodeBool(rv.Bool())
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kString(rv reflect.Value) {
f.e.e.EncodeString(c_UTF8, rv.String())
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kFloat64(rv reflect.Value) {
f.e.e.EncodeFloat64(rv.Float())
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kFloat32(rv reflect.Value) {
f.e.e.EncodeFloat32(float32(rv.Float()))
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kInt(rv reflect.Value) {
f.e.e.EncodeInt(rv.Int())
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kUint(rv reflect.Value) {
f.e.e.EncodeUint(rv.Uint())
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kInvalid(rv reflect.Value) {
f.e.e.EncodeNil()
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kErr(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
f.e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv)
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kSlice(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
ti := f.ti
// array may be non-addressable, so we have to manage with care
// (don't call rv.Bytes, rv.Slice, etc).
// E.g. type struct S{B [2]byte};
// Encode(S{}) will bomb on "panic: slice of unaddressable array".
2015-10-30 22:07:00 +00:00
e := f.e
2015-06-29 21:50:55 +00:00
if f.seq != seqTypeArray {
if rv.IsNil() {
2015-10-30 22:07:00 +00:00
e.e.EncodeNil()
2015-06-29 21:50:55 +00:00
return
}
// If in this method, then there was no extension function defined.
// So it's okay to treat as []byte.
if ti.rtid == uint8SliceTypId {
2015-10-30 22:07:00 +00:00
e.e.EncodeStringBytes(c_RAW, rv.Bytes())
2015-06-29 21:50:55 +00:00
return
}
}
2015-10-30 22:07:00 +00:00
cr := e.cr
2015-06-29 21:50:55 +00:00
rtelem := ti.rt.Elem()
l := rv.Len()
2015-10-30 22:07:00 +00:00
if ti.rtid == uint8SliceTypId || rtelem.Kind() == reflect.Uint8 {
2015-06-29 21:50:55 +00:00
switch f.seq {
case seqTypeArray:
2015-10-30 22:07:00 +00:00
// if l == 0 { e.e.encodeStringBytes(c_RAW, nil) } else
2015-06-29 21:50:55 +00:00
if rv.CanAddr() {
2015-10-30 22:07:00 +00:00
e.e.EncodeStringBytes(c_RAW, rv.Slice(0, l).Bytes())
2015-06-29 21:50:55 +00:00
} else {
var bs []byte
2015-10-30 22:07:00 +00:00
if l <= cap(e.b) {
bs = e.b[:l]
2015-06-29 21:50:55 +00:00
} else {
bs = make([]byte, l)
}
reflect.Copy(reflect.ValueOf(bs), rv)
// TODO: Test that reflect.Copy works instead of manual one-by-one
// for i := 0; i < l; i++ {
// bs[i] = byte(rv.Index(i).Uint())
// }
2015-10-30 22:07:00 +00:00
e.e.EncodeStringBytes(c_RAW, bs)
2015-06-29 21:50:55 +00:00
}
case seqTypeSlice:
2015-10-30 22:07:00 +00:00
e.e.EncodeStringBytes(c_RAW, rv.Bytes())
2015-06-29 21:50:55 +00:00
case seqTypeChan:
2015-10-30 22:07:00 +00:00
bs := e.b[:0]
2015-06-29 21:50:55 +00:00
// do not use range, so that the number of elements encoded
// does not change, and encoding does not hang waiting on someone to close chan.
// for b := range rv.Interface().(<-chan byte) {
// bs = append(bs, b)
// }
ch := rv.Interface().(<-chan byte)
for i := 0; i < l; i++ {
bs = append(bs, <-ch)
}
2015-10-30 22:07:00 +00:00
e.e.EncodeStringBytes(c_RAW, bs)
2015-06-29 21:50:55 +00:00
}
return
}
if ti.mbs {
if l%2 == 1 {
2015-10-30 22:07:00 +00:00
e.errorf("mapBySlice requires even slice length, but got %v", l)
2015-06-29 21:50:55 +00:00
return
}
2015-10-30 22:07:00 +00:00
e.e.EncodeMapStart(l / 2)
2015-06-29 21:50:55 +00:00
} else {
2015-10-30 22:07:00 +00:00
e.e.EncodeArrayStart(l)
2015-06-29 21:50:55 +00:00
}
if l > 0 {
for rtelem.Kind() == reflect.Ptr {
rtelem = rtelem.Elem()
}
// if kind is reflect.Interface, do not pre-determine the
// encoding type, because preEncodeValue may break it down to
// a concrete type and kInterface will bomb.
2015-10-07 20:10:00 +00:00
var fn *encFn
2015-06-29 21:50:55 +00:00
if rtelem.Kind() != reflect.Interface {
rtelemid := reflect.ValueOf(rtelem).Pointer()
fn = e.getEncFn(rtelemid, rtelem, true, true)
}
// TODO: Consider perf implication of encoding odd index values as symbols if type is string
2015-09-22 15:44:21 +00:00
for j := 0; j < l; j++ {
2015-10-30 22:07:00 +00:00
if cr != nil {
if ti.mbs {
2016-04-26 00:18:04 +00:00
if j%2 == 0 {
2015-10-30 22:07:00 +00:00
cr.sendContainerState(containerMapKey)
} else {
cr.sendContainerState(containerMapValue)
}
} else {
cr.sendContainerState(containerArrayElem)
}
}
2015-09-22 15:44:21 +00:00
if f.seq == seqTypeChan {
if rv2, ok2 := rv.Recv(); ok2 {
e.encodeValue(rv2, fn)
2015-10-30 22:07:00 +00:00
} else {
e.encode(nil) // WE HAVE TO DO SOMETHING, so nil if nothing received.
2015-06-29 21:50:55 +00:00
}
2015-09-22 15:44:21 +00:00
} else {
e.encodeValue(rv.Index(j), fn)
2015-06-29 21:50:55 +00:00
}
}
}
2015-09-22 15:44:21 +00:00
2015-10-30 22:07:00 +00:00
if cr != nil {
if ti.mbs {
cr.sendContainerState(containerMapEnd)
} else {
cr.sendContainerState(containerArrayEnd)
}
}
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kStruct(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
fti := f.ti
e := f.e
2015-10-30 22:07:00 +00:00
cr := e.cr
2015-06-29 21:50:55 +00:00
tisfi := fti.sfip
toMap := !(fti.toArray || e.h.StructToArray)
newlen := len(fti.sfi)
2015-10-07 20:10:00 +00:00
2015-06-29 21:50:55 +00:00
// Use sync.Pool to reduce allocating slices unnecessarily.
2016-04-26 00:18:04 +00:00
// The cost of sync.Pool is less than the cost of new allocation.
2015-10-07 20:10:00 +00:00
pool, poolv, fkvs := encStructPoolGet(newlen)
2015-06-29 21:50:55 +00:00
// if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
if toMap {
tisfi = fti.sfi
}
newlen = 0
var kv stringRv
2016-09-02 22:05:09 +00:00
recur := e.h.RecursiveEmptyCheck
2015-06-29 21:50:55 +00:00
for _, si := range tisfi {
kv.r = si.field(rv, false)
2015-06-29 21:50:55 +00:00
if toMap {
2016-09-02 22:05:09 +00:00
if si.omitEmpty && isEmptyValue(kv.r, recur, recur) {
2015-06-29 21:50:55 +00:00
continue
}
kv.v = si.encName
2015-06-29 21:50:55 +00:00
} else {
// use the zero value.
// if a reference or struct, set to nil (so you do not output too much)
2016-09-02 22:05:09 +00:00
if si.omitEmpty && isEmptyValue(kv.r, recur, recur) {
switch kv.r.Kind() {
2016-09-02 22:05:09 +00:00
case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
kv.r = reflect.Value{} //encode as nil
2015-06-29 21:50:55 +00:00
}
}
}
fkvs[newlen] = kv
newlen++
}
// debugf(">>>> kStruct: newlen: %v", newlen)
2015-09-22 15:44:21 +00:00
// sep := !e.be
2016-07-23 00:11:47 +00:00
ee := e.e //don't dereference every time
2015-09-22 15:44:21 +00:00
if toMap {
ee.EncodeMapStart(newlen)
// asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
for j := 0; j < newlen; j++ {
kv = fkvs[j]
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
2015-09-22 15:44:21 +00:00
if asSymbols {
ee.EncodeSymbol(kv.v)
2015-09-22 15:44:21 +00:00
} else {
ee.EncodeString(c_UTF8, kv.v)
2015-06-29 21:50:55 +00:00
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(kv.r, nil)
2015-06-29 21:50:55 +00:00
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapEnd)
}
2015-06-29 21:50:55 +00:00
} else {
2015-09-22 15:44:21 +00:00
ee.EncodeArrayStart(newlen)
for j := 0; j < newlen; j++ {
kv = fkvs[j]
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerArrayElem)
}
e.encodeValue(kv.r, nil)
2015-06-29 21:50:55 +00:00
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerArrayEnd)
}
2015-06-29 21:50:55 +00:00
}
// do not use defer. Instead, use explicit pool return at end of function.
// defer has a cost we are trying to avoid.
// If there is a panic and these slices are not returned, it is ok.
if pool != nil {
pool.Put(poolv)
}
}
2015-10-07 20:10:00 +00:00
// func (f *encFnInfo) kPtr(rv reflect.Value) {
2015-06-29 21:50:55 +00:00
// debugf(">>>>>>> ??? encode kPtr called - shouldn't get called")
// if rv.IsNil() {
2015-10-07 20:10:00 +00:00
// f.e.e.encodeNil()
2015-06-29 21:50:55 +00:00
// return
// }
// f.e.encodeValue(rv.Elem())
// }
2016-04-26 00:18:04 +00:00
// func (f *encFnInfo) kInterface(rv reflect.Value) {
// println("kInterface called")
// debug.PrintStack()
// if rv.IsNil() {
// f.e.e.EncodeNil()
// return
// }
// f.e.encodeValue(rv.Elem(), nil)
// }
2015-06-29 21:50:55 +00:00
2015-10-07 20:10:00 +00:00
func (f *encFnInfo) kMap(rv reflect.Value) {
ee := f.e.e
2015-06-29 21:50:55 +00:00
if rv.IsNil() {
2015-10-07 20:10:00 +00:00
ee.EncodeNil()
2015-06-29 21:50:55 +00:00
return
}
l := rv.Len()
2015-10-07 20:10:00 +00:00
ee.EncodeMapStart(l)
2015-06-29 21:50:55 +00:00
e := f.e
2015-10-30 22:07:00 +00:00
cr := e.cr
2015-06-29 21:50:55 +00:00
if l == 0 {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapEnd)
}
2015-06-29 21:50:55 +00:00
return
}
var asSymbols bool
// determine the underlying key and val encFn's for the map.
// This eliminates some work which is done for each loop iteration i.e.
// rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
//
// However, if kind is reflect.Interface, do not pre-determine the
// encoding type, because preEncodeValue may break it down to
// a concrete type and kInterface will bomb.
2015-10-07 20:10:00 +00:00
var keyFn, valFn *encFn
2015-06-29 21:50:55 +00:00
ti := f.ti
rtkey := ti.rt.Key()
rtval := ti.rt.Elem()
rtkeyid := reflect.ValueOf(rtkey).Pointer()
// keyTypeIsString := f.ti.rt.Key().Kind() == reflect.String
var keyTypeIsString = rtkeyid == stringTypId
if keyTypeIsString {
asSymbols = e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
} else {
for rtkey.Kind() == reflect.Ptr {
rtkey = rtkey.Elem()
}
if rtkey.Kind() != reflect.Interface {
rtkeyid = reflect.ValueOf(rtkey).Pointer()
keyFn = e.getEncFn(rtkeyid, rtkey, true, true)
}
}
for rtval.Kind() == reflect.Ptr {
rtval = rtval.Elem()
}
if rtval.Kind() != reflect.Interface {
rtvalid := reflect.ValueOf(rtval).Pointer()
valFn = e.getEncFn(rtvalid, rtval, true, true)
}
mks := rv.MapKeys()
// for j, lmks := 0, len(mks); j < lmks; j++ {
2015-06-29 21:50:55 +00:00
if e.h.Canonical {
e.kMapCanonical(rtkeyid, rtkey, rv, mks, valFn, asSymbols)
2015-06-29 21:50:55 +00:00
} else {
for j := range mks {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
2015-06-29 21:50:55 +00:00
if keyTypeIsString {
if asSymbols {
ee.EncodeSymbol(mks[j].String())
} else {
ee.EncodeString(c_UTF8, mks[j].String())
}
} else {
e.encodeValue(mks[j], keyFn)
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
2015-06-29 21:50:55 +00:00
e.encodeValue(rv.MapIndex(mks[j]), valFn)
}
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapEnd)
}
2015-06-29 21:50:55 +00:00
}
func (e *Encoder) kMapCanonical(rtkeyid uintptr, rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *encFn, asSymbols bool) {
ee := e.e
2015-10-30 22:07:00 +00:00
cr := e.cr
// we previously did out-of-band if an extension was registered.
// This is not necessary, as the natural kind is sufficient for ordering.
if rtkeyid == uint8SliceTypId {
mksv := make([]bytesRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Bytes()
}
sort.Sort(bytesRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeStringBytes(c_RAW, mksv[i].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
} else {
switch rtkey.Kind() {
case reflect.Bool:
mksv := make([]boolRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Bool()
}
sort.Sort(boolRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeBool(mksv[i].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
case reflect.String:
mksv := make([]stringRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.String()
}
sort.Sort(stringRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
if asSymbols {
ee.EncodeSymbol(mksv[i].v)
} else {
ee.EncodeString(c_UTF8, mksv[i].v)
}
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
mksv := make([]uintRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Uint()
}
sort.Sort(uintRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeUint(mksv[i].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
mksv := make([]intRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Int()
}
sort.Sort(intRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeInt(mksv[i].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
case reflect.Float32:
mksv := make([]floatRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(floatRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeFloat32(float32(mksv[i].v))
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
case reflect.Float64:
mksv := make([]floatRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(floatRvSlice(mksv))
for i := range mksv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
ee.EncodeFloat64(mksv[i].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksv[i].r), valFn)
}
default:
// out-of-band
// first encode each key to a []byte first, then sort them, then record
var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding
e2 := NewEncoderBytes(&mksv, e.hh)
mksbv := make([]bytesRv, len(mks))
for i, k := range mks {
v := &mksbv[i]
l := len(mksv)
e2.MustEncode(k)
v.r = k
v.v = mksv[l:]
// fmt.Printf(">>>>> %s\n", mksv[l:])
}
sort.Sort(bytesRvSlice(mksbv))
for j := range mksbv {
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapKey)
}
e.asis(mksbv[j].v)
2015-10-30 22:07:00 +00:00
if cr != nil {
cr.sendContainerState(containerMapValue)
}
e.encodeValue(rv.MapIndex(mksbv[j].r), valFn)
}
}
}
}
2015-06-29 21:50:55 +00:00
// --------------------------------------------------
// 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
2015-10-07 20:10:00 +00:00
f func(*encFnInfo, reflect.Value)
2015-06-29 21:50:55 +00:00
}
// --------------------------------------------------
2015-10-07 20:10:00 +00:00
type encRtidFn struct {
2015-06-29 21:50:55 +00:00
rtid uintptr
fn encFn
}
// An Encoder writes an object to an output stream in the codec format.
type Encoder struct {
// hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
2015-09-22 15:44:21 +00:00
e encDriver
// NOTE: Encoder shouldn't call it's write methods,
// as the handler MAY need to do some coordination.
2015-06-29 21:50:55 +00:00
w encWriter
2015-10-07 20:10:00 +00:00
s []encRtidFn
2016-04-26 00:18:04 +00:00
ci set
2015-06-29 21:50:55 +00:00
be bool // is binary encoding
2015-09-22 15:44:21 +00:00
js bool // is json handle
2015-06-29 21:50:55 +00:00
wi ioEncWriter
wb bytesEncWriter
2015-10-30 22:07:00 +00:00
2015-06-29 21:50:55 +00:00
h *BasicHandle
2015-10-30 22:07:00 +00:00
hh Handle
2015-06-29 21:50:55 +00:00
2015-10-30 22:07:00 +00:00
cr containerStateRecv
2015-09-22 15:44:21 +00:00
as encDriverAsis
2015-10-30 22:07:00 +00:00
f map[uintptr]*encFn
b [scratchByteArrayLen]byte
2015-06-29 21:50:55 +00:00
}
// 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 {
2015-10-30 22:07:00 +00:00
e := newEncoder(h)
e.Reset(w)
2015-06-29 21:50:55 +00:00
return e
}
// 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 {
2015-10-30 22:07:00 +00:00
e := newEncoder(h)
e.ResetBytes(out)
return e
}
func newEncoder(h Handle) *Encoder {
2015-06-29 21:50:55 +00:00
e := &Encoder{hh: h, h: h.getBasicHandle(), be: h.isBinary()}
2015-10-30 22:07:00 +00:00
_, e.js = h.(*JsonHandle)
e.e = h.newEncDriver(e)
e.as, _ = e.e.(encDriverAsis)
e.cr, _ = e.e.(containerStateRecv)
return e
}
// Reset the Encoder with a new output stream.
//
2016-07-23 00:11:47 +00:00
// This accommodates using the state of the Encoder,
2015-10-30 22:07:00 +00:00
// where it has "cached" information about sub-engines.
func (e *Encoder) Reset(w io.Writer) {
ww, ok := w.(ioEncWriterWriter)
if ok {
e.wi.w = ww
} else {
sww := &e.wi.s
sww.w = w
sww.bw, _ = w.(io.ByteWriter)
sww.sw, _ = w.(ioEncStringWriter)
e.wi.w = sww
//ww = bufio.NewWriterSize(w, defEncByteBufSize)
}
e.w = &e.wi
e.e.reset()
}
func (e *Encoder) ResetBytes(out *[]byte) {
2015-06-29 21:50:55 +00:00
in := *out
if in == nil {
in = make([]byte, defEncByteBufSize)
}
2015-10-30 22:07:00 +00:00
e.wb.b, e.wb.out, e.wb.c = in, out, 0
2015-06-29 21:50:55 +00:00
e.w = &e.wb
2015-10-30 22:07:00 +00:00
e.e.reset()
2015-06-29 21:50:55 +00:00
}
2015-10-30 22:07:00 +00:00
// func (e *Encoder) sendContainerState(c containerState) {
// if e.cr != nil {
// e.cr.sendContainerState(c)
// }
// }
2015-06-29 21:50:55 +00:00
// Encode writes an object into a stream.
//
// Encoding can be configured via the 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.
// Note that the "json" key is used in the absence of the "codec" key.
//
// 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 tag is "-", OR
// - the field is empty (empty or the zero value) and its 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 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.
//
2015-09-22 15:44:21 +00:00
// Anonymous fields are encoded inline except:
// - the struct tag specifies a replacement name (first value)
// - the field is of an interface type
2015-06-29 21:50:55 +00:00
//
// Examples:
//
// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
// 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.
2015-09-22 15:44:21 +00:00
// io.Reader //use key "Reader".
// MyStruct `codec:"my1" //use key "my1".
// MyStruct //inline it
2015-06-29 21:50:55 +00:00
// ...
// }
//
// 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:
2015-09-22 15:44:21 +00:00
// - If a Selfer, call its CodecEncodeSelf method
2015-06-29 21:50:55 +00:00
// - If an extension is registered for it, call that extension function
2015-09-22 15:44:21 +00:00
// - If it implements encoding.(Binary|Text|JSON)Marshaler, call its Marshal(Binary|Text|JSON) method
2015-06-29 21:50:55 +00:00
// - 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
}
// MustEncode is like Encode, but panics if unable to Encode.
// This provides insight to the code location that triggered the error.
func (e *Encoder) MustEncode(v interface{}) {
e.encode(v)
e.w.atEndOfEncode()
}
// comment out these (Must)Write methods. They were only put there to support cbor.
// However, users already have access to the streams, and can write directly.
//
// // Write allows users write to the Encoder stream directly.
// func (e *Encoder) Write(bs []byte) (err error) {
// defer panicToErr(&err)
// e.w.writeb(bs)
// return
// }
// // MustWrite is like write, but panics if unable to Write.
// func (e *Encoder) MustWrite(bs []byte) {
// e.w.writeb(bs)
// }
func (e *Encoder) encode(iv interface{}) {
// if ics, ok := iv.(Selfer); ok {
// ics.CodecEncodeSelf(e)
// return
// }
switch v := iv.(type) {
case nil:
e.e.EncodeNil()
case Selfer:
v.CodecEncodeSelf(e)
2016-09-12 19:16:55 +00:00
case Raw:
e.raw(v)
2015-06-29 21:50:55 +00:00
case reflect.Value:
2015-10-07 20:10:00 +00:00
e.encodeValue(v, nil)
2015-06-29 21:50:55 +00:00
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 []uint8:
e.e.EncodeStringBytes(c_RAW, 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 *[]uint8:
e.e.EncodeStringBytes(c_RAW, *v)
default:
2015-09-22 15:44:21 +00:00
const checkCodecSelfer1 = true // in case T is passed, where *T is a Selfer, still checkCodecSelfer
if !fastpathEncodeTypeSwitch(iv, e) {
e.encodeI(iv, false, checkCodecSelfer1)
2015-06-29 21:50:55 +00:00
}
}
}
2016-04-26 00:18:04 +00:00
func (e *Encoder) preEncodeValue(rv reflect.Value) (rv2 reflect.Value, sptr uintptr, proceed bool) {
2015-10-30 22:07:00 +00:00
// use a goto statement instead of a recursive function for ptr/interface.
TOP:
switch rv.Kind() {
2016-04-26 00:18:04 +00:00
case reflect.Ptr:
if rv.IsNil() {
e.e.EncodeNil()
return
}
rv = rv.Elem()
if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
// TODO: Movable pointers will be an issue here. Future problem.
sptr = rv.UnsafeAddr()
break TOP
}
goto TOP
case reflect.Interface:
2015-10-30 22:07:00 +00:00
if rv.IsNil() {
2015-06-29 21:50:55 +00:00
e.e.EncodeNil()
return
}
2015-10-30 22:07:00 +00:00
rv = rv.Elem()
goto TOP
case reflect.Slice, reflect.Map:
if rv.IsNil() {
e.e.EncodeNil()
return
}
case reflect.Invalid, reflect.Func:
e.e.EncodeNil()
return
2015-06-29 21:50:55 +00:00
}
2016-04-26 00:18:04 +00:00
proceed = true
rv2 = rv
return
}
func (e *Encoder) doEncodeValue(rv reflect.Value, fn *encFn, sptr uintptr,
checkFastpath, checkCodecSelfer bool) {
if sptr != 0 {
if (&e.ci).add(sptr) {
e.errorf("circular reference found: # %d", sptr)
}
}
if fn == nil {
rt := rv.Type()
rtid := reflect.ValueOf(rt).Pointer()
// fn = e.getEncFn(rtid, rt, true, true)
fn = e.getEncFn(rtid, rt, checkFastpath, checkCodecSelfer)
}
fn.f(&fn.i, rv)
if sptr != 0 {
(&e.ci).remove(sptr)
}
}
func (e *Encoder) encodeI(iv interface{}, checkFastpath, checkCodecSelfer bool) {
if rv, sptr, proceed := e.preEncodeValue(reflect.ValueOf(iv)); proceed {
e.doEncodeValue(rv, nil, sptr, checkFastpath, checkCodecSelfer)
}
2015-06-29 21:50:55 +00:00
}
2015-10-07 20:10:00 +00:00
func (e *Encoder) encodeValue(rv reflect.Value, fn *encFn) {
2015-06-29 21:50:55 +00:00
// if a valid fn is passed, it MUST BE for the dereferenced type of rv
2016-04-26 00:18:04 +00:00
if rv, sptr, proceed := e.preEncodeValue(rv); proceed {
e.doEncodeValue(rv, fn, sptr, true, true)
2015-06-29 21:50:55 +00:00
}
}
2015-10-07 20:10:00 +00:00
func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *encFn) {
2015-06-29 21:50:55 +00:00
// rtid := reflect.ValueOf(rt).Pointer()
var ok bool
if useMapForCodecCache {
fn, ok = e.f[rtid]
} else {
2015-10-07 20:10:00 +00:00
for i := range e.s {
v := &(e.s[i])
2015-06-29 21:50:55 +00:00
if v.rtid == rtid {
2015-10-07 20:10:00 +00:00
fn, ok = &(v.fn), true
2015-06-29 21:50:55 +00:00
break
}
}
}
if ok {
return
}
2015-10-07 20:10:00 +00:00
if useMapForCodecCache {
if e.f == nil {
e.f = make(map[uintptr]*encFn, initCollectionCap)
}
fn = new(encFn)
e.f[rtid] = fn
} else {
if e.s == nil {
e.s = make([]encRtidFn, 0, initCollectionCap)
}
e.s = append(e.s, encRtidFn{rtid: rtid})
fn = &(e.s[len(e.s)-1]).fn
}
2015-10-12 18:07:12 +00:00
ti := e.h.getTypeInfo(rtid, rt)
2015-10-07 20:10:00 +00:00
fi := &(fn.i)
fi.e = e
fi.ti = ti
2015-06-29 21:50:55 +00:00
if checkCodecSelfer && ti.cs {
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).selferMarshal
2016-09-12 19:16:55 +00:00
} else if rtid == rawTypId {
fn.f = (*encFnInfo).raw
2015-06-29 21:50:55 +00:00
} else if rtid == rawExtTypId {
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).rawExt
2015-06-29 21:50:55 +00:00
} else if e.e.IsBuiltinType(rtid) {
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).builtin
2015-06-29 21:50:55 +00:00
} else if xfFn := e.h.getExt(rtid); xfFn != nil {
fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).ext
2015-06-29 21:50:55 +00:00
} else if supportMarshalInterfaces && e.be && ti.bm {
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).binaryMarshal
2015-09-22 15:44:21 +00:00
} else if supportMarshalInterfaces && !e.be && e.js && ti.jm {
//If JSON, we should check JSONMarshal before textMarshal
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).jsonMarshal
2015-06-29 21:50:55 +00:00
} else if supportMarshalInterfaces && !e.be && ti.tm {
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).textMarshal
2015-06-29 21:50:55 +00:00
} else {
rk := rt.Kind()
if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
2016-04-26 00:18:04 +00:00
if rt.PkgPath() == "" { // un-named slice or map
2015-06-29 21:50:55 +00:00
if idx := fastpathAV.index(rtid); idx != -1 {
fn.f = fastpathAV[idx].encfn
}
} else {
ok = false
// use mapping for underlying type if there
var rtu reflect.Type
if rk == reflect.Map {
rtu = reflect.MapOf(rt.Key(), rt.Elem())
} else {
rtu = reflect.SliceOf(rt.Elem())
}
rtuid := reflect.ValueOf(rtu).Pointer()
if idx := fastpathAV.index(rtuid); idx != -1 {
xfnf := fastpathAV[idx].encfn
xrt := fastpathAV[idx].rt
2015-10-07 20:10:00 +00:00
fn.f = func(xf *encFnInfo, xrv reflect.Value) {
2015-06-29 21:50:55 +00:00
xfnf(xf, xrv.Convert(xrt))
}
}
}
}
if fn.f == nil {
switch rk {
case reflect.Bool:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kBool
2015-06-29 21:50:55 +00:00
case reflect.String:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kString
2015-06-29 21:50:55 +00:00
case reflect.Float64:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kFloat64
2015-06-29 21:50:55 +00:00
case reflect.Float32:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kFloat32
2015-06-29 21:50:55 +00:00
case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kInt
2015-09-22 15:44:21 +00:00
case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uintptr:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kUint
2015-06-29 21:50:55 +00:00
case reflect.Invalid:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kInvalid
2015-06-29 21:50:55 +00:00
case reflect.Chan:
2015-10-07 20:10:00 +00:00
fi.seq = seqTypeChan
fn.f = (*encFnInfo).kSlice
2015-06-29 21:50:55 +00:00
case reflect.Slice:
2015-10-07 20:10:00 +00:00
fi.seq = seqTypeSlice
fn.f = (*encFnInfo).kSlice
2015-06-29 21:50:55 +00:00
case reflect.Array:
2015-10-07 20:10:00 +00:00
fi.seq = seqTypeArray
fn.f = (*encFnInfo).kSlice
2015-06-29 21:50:55 +00:00
case reflect.Struct:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kStruct
2016-04-26 00:18:04 +00:00
// reflect.Ptr and reflect.Interface are handled already by preEncodeValue
2015-06-29 21:50:55 +00:00
// case reflect.Ptr:
2015-10-07 20:10:00 +00:00
// fn.f = (*encFnInfo).kPtr
2016-04-26 00:18:04 +00:00
// case reflect.Interface:
// fn.f = (*encFnInfo).kInterface
2015-06-29 21:50:55 +00:00
case reflect.Map:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kMap
2015-06-29 21:50:55 +00:00
default:
2015-10-07 20:10:00 +00:00
fn.f = (*encFnInfo).kErr
2015-06-29 21:50:55 +00:00
}
}
}
return
}
2015-09-22 15:44:21 +00:00
func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) {
if fnerr != nil {
panic(fnerr)
}
if bs == nil {
e.e.EncodeNil()
} else if asis {
e.asis(bs)
} else {
e.e.EncodeStringBytes(c, bs)
}
}
func (e *Encoder) asis(v []byte) {
if e.as == nil {
e.w.writeb(v)
} else {
e.as.EncodeAsis(v)
}
}
2016-09-12 19:16:55 +00:00
func (e *Encoder) raw(vv Raw) {
v := []byte(vv)
if !e.h.Raw {
e.errorf("Raw values cannot be encoded: %v", v)
}
if e.as == nil {
e.w.writeb(v)
} else {
e.as.EncodeAsis(v)
}
}
2015-06-29 21:50:55 +00:00
func (e *Encoder) errorf(format string, params ...interface{}) {
err := fmt.Errorf(format, params...)
panic(err)
}
// ----------------------------------------
2015-10-07 20:10:00 +00:00
const encStructPoolLen = 5
2015-06-29 21:50:55 +00:00
// encStructPool is an array of sync.Pool.
// Each element of the array pools one of encStructPool(8|16|32|64).
// It allows the re-use of slices up to 64 in length.
// A performance cost of encoding structs was collecting
// which values were empty and should be omitted.
// We needed slices of reflect.Value and string to collect them.
// This shared pool reduces the amount of unnecessary creation we do.
// The cost is that of locking sometimes, but sync.Pool is efficient
// enough to reduce thread contention.
var encStructPool [encStructPoolLen]sync.Pool
func init() {
encStructPool[0].New = func() interface{} { return new([8]stringRv) }
encStructPool[1].New = func() interface{} { return new([16]stringRv) }
encStructPool[2].New = func() interface{} { return new([32]stringRv) }
encStructPool[3].New = func() interface{} { return new([64]stringRv) }
encStructPool[4].New = func() interface{} { return new([128]stringRv) }
2015-10-07 20:10:00 +00:00
}
func encStructPoolGet(newlen int) (p *sync.Pool, v interface{}, s []stringRv) {
2015-10-07 20:10:00 +00:00
// if encStructPoolLen != 5 { // constant chec, so removed at build time.
// panic(errors.New("encStructPoolLen must be equal to 4")) // defensive, in case it is changed
// }
// idxpool := newlen / 8
if newlen <= 8 {
p = &encStructPool[0]
v = p.Get()
s = v.(*[8]stringRv)[:newlen]
2015-10-07 20:10:00 +00:00
} else if newlen <= 16 {
p = &encStructPool[1]
v = p.Get()
s = v.(*[16]stringRv)[:newlen]
2015-10-07 20:10:00 +00:00
} else if newlen <= 32 {
p = &encStructPool[2]
v = p.Get()
s = v.(*[32]stringRv)[:newlen]
2015-10-07 20:10:00 +00:00
} else if newlen <= 64 {
p = &encStructPool[3]
v = p.Get()
s = v.(*[64]stringRv)[:newlen]
2015-10-07 20:10:00 +00:00
} else if newlen <= 128 {
p = &encStructPool[4]
v = p.Get()
s = v.(*[128]stringRv)[:newlen]
2015-10-07 20:10:00 +00:00
} else {
s = make([]stringRv, newlen)
2015-10-07 20:10:00 +00:00
}
return
2015-06-29 21:50:55 +00:00
}
// ----------------------------------------
// func encErr(format string, params ...interface{}) {
// doPanic(msgTagEnc, format, params...)
// }