| 1 |
// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. |
| 2 |
// Use of this source code is governed by a MIT license found in the LICENSE file. |
| 3 |
|
| 4 |
package codec |
| 5 |
|
| 6 |
import ( |
| 7 |
"bufio" |
| 8 |
"encoding" |
| 9 |
"fmt" |
| 10 |
"io" |
| 11 |
"reflect" |
| 12 |
"sort" |
| 13 |
"sync" |
| 14 |
) |
| 15 |
|
| 16 |
const defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024 |
| 17 |
|
| 18 |
// AsSymbolFlag defines what should be encoded as symbols. |
| 19 |
type AsSymbolFlag uint8 |
| 20 |
|
| 21 |
const ( |
| 22 |
// AsSymbolDefault is default. |
| 23 |
// Currently, this means only encode struct field names as symbols. |
| 24 |
// The default is subject to change. |
| 25 |
AsSymbolDefault AsSymbolFlag = iota |
| 26 |
|
| 27 |
// AsSymbolAll means encode anything which could be a symbol as a symbol. |
| 28 |
AsSymbolAll = 0xfe |
| 29 |
|
| 30 |
// AsSymbolNone means do not encode anything as a symbol. |
| 31 |
AsSymbolNone = 1 << iota |
| 32 |
|
| 33 |
// AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols. |
| 34 |
AsSymbolMapStringKeysFlag |
| 35 |
|
| 36 |
// AsSymbolStructFieldName means encode struct field names as symbols. |
| 37 |
AsSymbolStructFieldNameFlag |
| 38 |
) |
| 39 |
|
| 40 |
// encWriter abstracts writing to a byte array or to an io.Writer. |
| 41 |
type encWriter interface { |
| 42 |
writeb([]byte) |
| 43 |
writestr(string) |
| 44 |
writen1(byte) |
| 45 |
writen2(byte, byte) |
| 46 |
writen4(byte, byte, byte, byte) |
| 47 |
writen5(byte, byte, byte, byte, byte) |
| 48 |
atEndOfEncode() |
| 49 |
} |
| 50 |
|
| 51 |
// encDriver abstracts the actual codec (binc vs msgpack, etc) |
| 52 |
type encDriver interface { |
| 53 |
// IsBuiltinType(rt uintptr) bool |
| 54 |
EncodeBuiltin(rt uintptr, v interface{}) |
| 55 |
EncodeNil() |
| 56 |
EncodeInt(i int64) |
| 57 |
EncodeUint(i uint64) |
| 58 |
EncodeBool(b bool) |
| 59 |
EncodeFloat32(f float32) |
| 60 |
EncodeFloat64(f float64) |
| 61 |
// encodeExtPreamble(xtag byte, length int) |
| 62 |
EncodeRawExt(re *RawExt, e *Encoder) |
| 63 |
EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder) |
| 64 |
WriteArrayStart(length int) |
| 65 |
WriteArrayElem() |
| 66 |
WriteArrayEnd() |
| 67 |
WriteMapStart(length int) |
| 68 |
WriteMapElemKey() |
| 69 |
WriteMapElemValue() |
| 70 |
WriteMapEnd() |
| 71 |
EncodeString(c charEncoding, v string) |
| 72 |
EncodeSymbol(v string) |
| 73 |
EncodeStringBytes(c charEncoding, v []byte) |
| 74 |
//TODO |
| 75 |
//encBignum(f *big.Int) |
| 76 |
//encStringRunes(c charEncoding, v []rune) |
| 77 |
|
| 78 |
reset() |
| 79 |
atEndOfEncode() |
| 80 |
} |
| 81 |
|
| 82 |
type ioEncStringWriter interface { |
| 83 |
WriteString(s string) (n int, err error) |
| 84 |
} |
| 85 |
|
| 86 |
type ioEncFlusher interface { |
| 87 |
Flush() error |
| 88 |
} |
| 89 |
|
| 90 |
type encDriverAsis interface { |
| 91 |
EncodeAsis(v []byte) |
| 92 |
} |
| 93 |
|
| 94 |
// type encNoSeparator struct{} |
| 95 |
// func (_ encNoSeparator) EncodeEnd() {} |
| 96 |
|
| 97 |
type encDriverNoopContainerWriter struct{} |
| 98 |
|
| 99 |
func (_ encDriverNoopContainerWriter) WriteArrayStart(length int) {} |
| 100 |
func (_ encDriverNoopContainerWriter) WriteArrayElem() {} |
| 101 |
func (_ encDriverNoopContainerWriter) WriteArrayEnd() {} |
| 102 |
func (_ encDriverNoopContainerWriter) WriteMapStart(length int) {} |
| 103 |
func (_ encDriverNoopContainerWriter) WriteMapElemKey() {} |
| 104 |
func (_ encDriverNoopContainerWriter) WriteMapElemValue() {} |
| 105 |
func (_ encDriverNoopContainerWriter) WriteMapEnd() {} |
| 106 |
func (_ encDriverNoopContainerWriter) atEndOfEncode() {} |
| 107 |
|
| 108 |
// type ioEncWriterWriter interface { |
| 109 |
// WriteByte(c byte) error |
| 110 |
// WriteString(s string) (n int, err error) |
| 111 |
// Write(p []byte) (n int, err error) |
| 112 |
// } |
| 113 |
|
| 114 |
type EncodeOptions struct { |
| 115 |
// Encode a struct as an array, and not as a map |
| 116 |
StructToArray bool |
| 117 |
|
| 118 |
// Canonical representation means that encoding a value will always result in the same |
| 119 |
// sequence of bytes. |
| 120 |
// |
| 121 |
// This only affects maps, as the iteration order for maps is random. |
| 122 |
// |
| 123 |
// The implementation MAY use the natural sort order for the map keys if possible: |
| 124 |
// |
| 125 |
// - If there is a natural sort order (ie for number, bool, string or []byte keys), |
| 126 |
// then the map keys are first sorted in natural order and then written |
| 127 |
// with corresponding map values to the strema. |
| 128 |
// - If there is no natural sort order, then the map keys will first be |
| 129 |
// encoded into []byte, and then sorted, |
| 130 |
// before writing the sorted keys and the corresponding map values to the stream. |
| 131 |
// |
| 132 |
Canonical bool |
| 133 |
|
| 134 |
// CheckCircularRef controls whether we check for circular references |
| 135 |
// and error fast during an encode. |
| 136 |
// |
| 137 |
// If enabled, an error is received if a pointer to a struct |
| 138 |
// references itself either directly or through one of its fields (iteratively). |
| 139 |
// |
| 140 |
// This is opt-in, as there may be a performance hit to checking circular references. |
| 141 |
CheckCircularRef bool |
| 142 |
|
| 143 |
// RecursiveEmptyCheck controls whether we descend into interfaces, structs and pointers |
| 144 |
// when checking if a value is empty. |
| 145 |
// |
| 146 |
// Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls. |
| 147 |
RecursiveEmptyCheck bool |
| 148 |
|
| 149 |
// Raw controls whether we encode Raw values. |
| 150 |
// This is a "dangerous" option and must be explicitly set. |
| 151 |
// If set, we blindly encode Raw values as-is, without checking |
| 152 |
// if they are a correct representation of a value in that format. |
| 153 |
// If unset, we error out. |
| 154 |
Raw bool |
| 155 |
|
| 156 |
// AsSymbols defines what should be encoded as symbols. |
| 157 |
// |
| 158 |
// Encoding as symbols can reduce the encoded size significantly. |
| 159 |
// |
| 160 |
// However, during decoding, each string to be encoded as a symbol must |
| 161 |
// be checked to see if it has been seen before. Consequently, encoding time |
| 162 |
// will increase if using symbols, because string comparisons has a clear cost. |
| 163 |
// |
| 164 |
// Sample values: |
| 165 |
// AsSymbolNone |
| 166 |
// AsSymbolAll |
| 167 |
// AsSymbolMapStringKeys |
| 168 |
// AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag |
| 169 |
AsSymbols AsSymbolFlag |
| 170 |
|
| 171 |
// WriterBufferSize is the size of the buffer used when writing. |
| 172 |
// |
| 173 |
// if > 0, we use a smart buffer internally for performance purposes. |
| 174 |
WriterBufferSize int |
| 175 |
} |
| 176 |
|
| 177 |
// --------------------------------------------- |
| 178 |
|
| 179 |
type simpleIoEncWriter struct { |
| 180 |
io.Writer |
| 181 |
} |
| 182 |
|
| 183 |
// type bufIoEncWriter struct { |
| 184 |
// w io.Writer |
| 185 |
// buf []byte |
| 186 |
// err error |
| 187 |
// } |
| 188 |
|
| 189 |
// func (x *bufIoEncWriter) Write(b []byte) (n int, err error) { |
| 190 |
// if x.err != nil { |
| 191 |
// return 0, x.err |
| 192 |
// } |
| 193 |
// if cap(x.buf)-len(x.buf) >= len(b) { |
| 194 |
// x.buf = append(x.buf, b) |
| 195 |
// return len(b), nil |
| 196 |
// } |
| 197 |
// n, err = x.w.Write(x.buf) |
| 198 |
// if err != nil { |
| 199 |
// x.err = err |
| 200 |
// return 0, x.err |
| 201 |
// } |
| 202 |
// n, err = x.w.Write(b) |
| 203 |
// x.err = err |
| 204 |
// return |
| 205 |
// } |
| 206 |
|
| 207 |
// ioEncWriter implements encWriter and can write to an io.Writer implementation |
| 208 |
type ioEncWriter struct { |
| 209 |
w io.Writer |
| 210 |
ww io.Writer |
| 211 |
bw io.ByteWriter |
| 212 |
sw ioEncStringWriter |
| 213 |
fw ioEncFlusher |
| 214 |
b [8]byte |
| 215 |
} |
| 216 |
|
| 217 |
func (z *ioEncWriter) WriteByte(b byte) (err error) { |
| 218 |
// x.bs[0] = b |
| 219 |
// _, err = x.ww.Write(x.bs[:]) |
| 220 |
z.b[0] = b |
| 221 |
_, err = z.w.Write(z.b[:1]) |
| 222 |
return |
| 223 |
} |
| 224 |
|
| 225 |
func (z *ioEncWriter) WriteString(s string) (n int, err error) { |
| 226 |
return z.w.Write(bytesView(s)) |
| 227 |
} |
| 228 |
|
| 229 |
func (z *ioEncWriter) writeb(bs []byte) { |
| 230 |
// if len(bs) == 0 { |
| 231 |
// return |
| 232 |
// } |
| 233 |
if _, err := z.ww.Write(bs); err != nil { |
| 234 |
panic(err) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
func (z *ioEncWriter) writestr(s string) { |
| 239 |
// if len(s) == 0 { |
| 240 |
// return |
| 241 |
// } |
| 242 |
if _, err := z.sw.WriteString(s); err != nil { |
| 243 |
panic(err) |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
func (z *ioEncWriter) writen1(b byte) { |
| 248 |
if err := z.bw.WriteByte(b); err != nil { |
| 249 |
panic(err) |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
func (z *ioEncWriter) writen2(b1, b2 byte) { |
| 254 |
var err error |
| 255 |
if err = z.bw.WriteByte(b1); err == nil { |
| 256 |
if err = z.bw.WriteByte(b2); err == nil { |
| 257 |
return |
| 258 |
} |
| 259 |
} |
| 260 |
panic(err) |
| 261 |
} |
| 262 |
|
| 263 |
func (z *ioEncWriter) writen4(b1, b2, b3, b4 byte) { |
| 264 |
z.b[0], z.b[1], z.b[2], z.b[3] = b1, b2, b3, b4 |
| 265 |
if _, err := z.ww.Write(z.b[:4]); err != nil { |
| 266 |
panic(err) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
func (z *ioEncWriter) writen5(b1, b2, b3, b4, b5 byte) { |
| 271 |
z.b[0], z.b[1], z.b[2], z.b[3], z.b[4] = b1, b2, b3, b4, b5 |
| 272 |
if _, err := z.ww.Write(z.b[:5]); err != nil { |
| 273 |
panic(err) |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
func (z *ioEncWriter) atEndOfEncode() { |
| 278 |
if z.fw != nil { |
| 279 |
z.fw.Flush() |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
// ---------------------------------------- |
| 284 |
|
| 285 |
// bytesEncWriter implements encWriter and can write to an byte slice. |
| 286 |
// It is used by Marshal function. |
| 287 |
type bytesEncWriter struct { |
| 288 |
b []byte |
| 289 |
c int // cursor |
| 290 |
out *[]byte // write out on atEndOfEncode |
| 291 |
} |
| 292 |
|
| 293 |
func (z *bytesEncWriter) writeb(s []byte) { |
| 294 |
oc, a := z.growNoAlloc(len(s)) |
| 295 |
if a { |
| 296 |
z.growAlloc(len(s), oc) |
| 297 |
} |
| 298 |
copy(z.b[oc:], s) |
| 299 |
} |
| 300 |
|
| 301 |
func (z *bytesEncWriter) writestr(s string) { |
| 302 |
oc, a := z.growNoAlloc(len(s)) |
| 303 |
if a { |
| 304 |
z.growAlloc(len(s), oc) |
| 305 |
} |
| 306 |
copy(z.b[oc:], s) |
| 307 |
} |
| 308 |
|
| 309 |
func (z *bytesEncWriter) writen1(b1 byte) { |
| 310 |
oc, a := z.growNoAlloc(1) |
| 311 |
if a { |
| 312 |
z.growAlloc(1, oc) |
| 313 |
} |
| 314 |
z.b[oc] = b1 |
| 315 |
} |
| 316 |
|
| 317 |
func (z *bytesEncWriter) writen2(b1, b2 byte) { |
| 318 |
oc, a := z.growNoAlloc(2) |
| 319 |
if a { |
| 320 |
z.growAlloc(2, oc) |
| 321 |
} |
| 322 |
z.b[oc+1] = b2 |
| 323 |
z.b[oc] = b1 |
| 324 |
} |
| 325 |
|
| 326 |
func (z *bytesEncWriter) writen4(b1, b2, b3, b4 byte) { |
| 327 |
oc, a := z.growNoAlloc(4) |
| 328 |
if a { |
| 329 |
z.growAlloc(4, oc) |
| 330 |
} |
| 331 |
z.b[oc+3] = b4 |
| 332 |
z.b[oc+2] = b3 |
| 333 |
z.b[oc+1] = b2 |
| 334 |
z.b[oc] = b1 |
| 335 |
} |
| 336 |
|
| 337 |
func (z *bytesEncWriter) writen5(b1, b2, b3, b4, b5 byte) { |
| 338 |
oc, a := z.growNoAlloc(5) |
| 339 |
if a { |
| 340 |
z.growAlloc(5, oc) |
| 341 |
} |
| 342 |
z.b[oc+4] = b5 |
| 343 |
z.b[oc+3] = b4 |
| 344 |
z.b[oc+2] = b3 |
| 345 |
z.b[oc+1] = b2 |
| 346 |
z.b[oc] = b1 |
| 347 |
} |
| 348 |
|
| 349 |
func (z *bytesEncWriter) atEndOfEncode() { |
| 350 |
*(z.out) = z.b[:z.c] |
| 351 |
} |
| 352 |
|
| 353 |
// have a growNoalloc(n int), which can be inlined. |
| 354 |
// if allocation is needed, then call growAlloc(n int) |
| 355 |
|
| 356 |
func (z *bytesEncWriter) growNoAlloc(n int) (oldcursor int, allocNeeded bool) { |
| 357 |
oldcursor = z.c |
| 358 |
z.c = z.c + n |
| 359 |
if z.c > len(z.b) { |
| 360 |
if z.c > cap(z.b) { |
| 361 |
allocNeeded = true |
| 362 |
} else { |
| 363 |
z.b = z.b[:cap(z.b)] |
| 364 |
} |
| 365 |
} |
| 366 |
return |
| 367 |
} |
| 368 |
|
| 369 |
func (z *bytesEncWriter) growAlloc(n int, oldcursor int) { |
| 370 |
// appendslice logic (if cap < 1024, *2, else *1.25): more expensive. many copy calls. |
| 371 |
// bytes.Buffer model (2*cap + n): much better |
| 372 |
// bs := make([]byte, 2*cap(z.b)+n) |
| 373 |
bs := make([]byte, growCap(cap(z.b), 1, n)) |
| 374 |
copy(bs, z.b[:oldcursor]) |
| 375 |
z.b = bs |
| 376 |
} |
| 377 |
|
| 378 |
// --------------------------------------------- |
| 379 |
|
| 380 |
func (e *Encoder) builtin(f *codecFnInfo, rv reflect.Value) { |
| 381 |
e.e.EncodeBuiltin(f.ti.rtid, rv2i(rv)) |
| 382 |
} |
| 383 |
|
| 384 |
func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) { |
| 385 |
e.rawBytes(rv2i(rv).(Raw)) |
| 386 |
} |
| 387 |
|
| 388 |
func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) { |
| 389 |
// rev := rv2i(rv).(RawExt) |
| 390 |
// e.e.EncodeRawExt(&rev, e) |
| 391 |
var re *RawExt |
| 392 |
if rv.CanAddr() { |
| 393 |
re = rv2i(rv.Addr()).(*RawExt) |
| 394 |
} else { |
| 395 |
rev := rv2i(rv).(RawExt) |
| 396 |
re = &rev |
| 397 |
} |
| 398 |
e.e.EncodeRawExt(re, e) |
| 399 |
} |
| 400 |
|
| 401 |
func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) { |
| 402 |
// if this is a struct|array and it was addressable, then pass the address directly (not the value) |
| 403 |
if k := rv.Kind(); (k == reflect.Struct || k == reflect.Array) && rv.CanAddr() { |
| 404 |
rv = rv.Addr() |
| 405 |
} |
| 406 |
e.e.EncodeExt(rv2i(rv), f.xfTag, f.xfFn, e) |
| 407 |
} |
| 408 |
|
| 409 |
func (e *Encoder) getValueForMarshalInterface(rv reflect.Value, indir int8) (v interface{}, proceed bool) { |
| 410 |
if indir == 0 { |
| 411 |
v = rv2i(rv) |
| 412 |
} else if indir == -1 { |
| 413 |
// If a non-pointer was passed to Encode(), then that value is not addressable. |
| 414 |
// Take addr if addressable, else copy value to an addressable value. |
| 415 |
if rv.CanAddr() { |
| 416 |
v = rv2i(rv.Addr()) |
| 417 |
} else { |
| 418 |
rv2 := reflect.New(rv.Type()) |
| 419 |
rv2.Elem().Set(rv) |
| 420 |
v = rv2i(rv2) |
| 421 |
} |
| 422 |
} else { |
| 423 |
for j := int8(0); j < indir; j++ { |
| 424 |
if rv.IsNil() { |
| 425 |
e.e.EncodeNil() |
| 426 |
return |
| 427 |
} |
| 428 |
rv = rv.Elem() |
| 429 |
} |
| 430 |
v = rv2i(rv) |
| 431 |
} |
| 432 |
return v, true |
| 433 |
} |
| 434 |
|
| 435 |
func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) { |
| 436 |
if v, proceed := e.getValueForMarshalInterface(rv, f.ti.csIndir); proceed { |
| 437 |
v.(Selfer).CodecEncodeSelf(e) |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) { |
| 442 |
if v, proceed := e.getValueForMarshalInterface(rv, f.ti.bmIndir); proceed { |
| 443 |
bs, fnerr := v.(encoding.BinaryMarshaler).MarshalBinary() |
| 444 |
e.marshal(bs, fnerr, false, c_RAW) |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) { |
| 449 |
if v, proceed := e.getValueForMarshalInterface(rv, f.ti.tmIndir); proceed { |
| 450 |
bs, fnerr := v.(encoding.TextMarshaler).MarshalText() |
| 451 |
e.marshal(bs, fnerr, false, c_UTF8) |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) { |
| 456 |
if v, proceed := e.getValueForMarshalInterface(rv, f.ti.jmIndir); proceed { |
| 457 |
bs, fnerr := v.(jsonMarshaler).MarshalJSON() |
| 458 |
e.marshal(bs, fnerr, true, c_UTF8) |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { |
| 463 |
e.e.EncodeBool(rv.Bool()) |
| 464 |
} |
| 465 |
|
| 466 |
func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { |
| 467 |
e.e.EncodeString(c_UTF8, rv.String()) |
| 468 |
} |
| 469 |
|
| 470 |
func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { |
| 471 |
e.e.EncodeFloat64(rv.Float()) |
| 472 |
} |
| 473 |
|
| 474 |
func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { |
| 475 |
e.e.EncodeFloat32(float32(rv.Float())) |
| 476 |
} |
| 477 |
|
| 478 |
func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { |
| 479 |
e.e.EncodeInt(rv.Int()) |
| 480 |
} |
| 481 |
|
| 482 |
func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { |
| 483 |
e.e.EncodeUint(rv.Uint()) |
| 484 |
} |
| 485 |
|
| 486 |
func (e *Encoder) kInvalid(f *codecFnInfo, rv reflect.Value) { |
| 487 |
e.e.EncodeNil() |
| 488 |
} |
| 489 |
|
| 490 |
func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) { |
| 491 |
e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv) |
| 492 |
} |
| 493 |
|
| 494 |
func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) { |
| 495 |
ti := f.ti |
| 496 |
ee := e.e |
| 497 |
// array may be non-addressable, so we have to manage with care |
| 498 |
// (don't call rv.Bytes, rv.Slice, etc). |
| 499 |
// E.g. type struct S{B [2]byte}; |
| 500 |
// Encode(S{}) will bomb on "panic: slice of unaddressable array". |
| 501 |
if f.seq != seqTypeArray { |
| 502 |
if rv.IsNil() { |
| 503 |
ee.EncodeNil() |
| 504 |
return |
| 505 |
} |
| 506 |
// If in this method, then there was no extension function defined. |
| 507 |
// So it's okay to treat as []byte. |
| 508 |
if ti.rtid == uint8SliceTypId { |
| 509 |
ee.EncodeStringBytes(c_RAW, rv.Bytes()) |
| 510 |
return |
| 511 |
} |
| 512 |
} |
| 513 |
elemsep := e.hh.hasElemSeparators() |
| 514 |
rtelem := ti.rt.Elem() |
| 515 |
l := rv.Len() |
| 516 |
if ti.rtid == uint8SliceTypId || rtelem.Kind() == reflect.Uint8 { |
| 517 |
switch f.seq { |
| 518 |
case seqTypeArray: |
| 519 |
if rv.CanAddr() { |
| 520 |
ee.EncodeStringBytes(c_RAW, rv.Slice(0, l).Bytes()) |
| 521 |
} else { |
| 522 |
var bs []byte |
| 523 |
if l <= cap(e.b) { |
| 524 |
bs = e.b[:l] |
| 525 |
} else { |
| 526 |
bs = make([]byte, l) |
| 527 |
} |
| 528 |
reflect.Copy(reflect.ValueOf(bs), rv) |
| 529 |
ee.EncodeStringBytes(c_RAW, bs) |
| 530 |
} |
| 531 |
return |
| 532 |
case seqTypeSlice: |
| 533 |
ee.EncodeStringBytes(c_RAW, rv.Bytes()) |
| 534 |
return |
| 535 |
} |
| 536 |
} |
| 537 |
if ti.rtid == uint8SliceTypId && f.seq == seqTypeChan { |
| 538 |
bs := e.b[:0] |
| 539 |
// do not use range, so that the number of elements encoded |
| 540 |
// does not change, and encoding does not hang waiting on someone to close chan. |
| 541 |
// for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) } |
| 542 |
ch := rv2i(rv).(<-chan byte) |
| 543 |
for i := 0; i < l; i++ { |
| 544 |
bs = append(bs, <-ch) |
| 545 |
} |
| 546 |
ee.EncodeStringBytes(c_RAW, bs) |
| 547 |
return |
| 548 |
} |
| 549 |
|
| 550 |
if ti.mbs { |
| 551 |
if l%2 == 1 { |
| 552 |
e.errorf("mapBySlice requires even slice length, but got %v", l) |
| 553 |
return |
| 554 |
} |
| 555 |
ee.WriteMapStart(l / 2) |
| 556 |
} else { |
| 557 |
ee.WriteArrayStart(l) |
| 558 |
} |
| 559 |
|
| 560 |
if l > 0 { |
| 561 |
var fn *codecFn |
| 562 |
var recognizedVtyp = useLookupRecognizedTypes && isRecognizedRtidOrPtr(rt2id(rtelem)) |
| 563 |
if !recognizedVtyp { |
| 564 |
for rtelem.Kind() == reflect.Ptr { |
| 565 |
rtelem = rtelem.Elem() |
| 566 |
} |
| 567 |
// if kind is reflect.Interface, do not pre-determine the |
| 568 |
// encoding type, because preEncodeValue may break it down to |
| 569 |
// a concrete type and kInterface will bomb. |
| 570 |
if rtelem.Kind() != reflect.Interface { |
| 571 |
fn = e.cf.get(rtelem, true, true) |
| 572 |
} |
| 573 |
} |
| 574 |
// TODO: Consider perf implication of encoding odd index values as symbols if type is string |
| 575 |
for j := 0; j < l; j++ { |
| 576 |
if elemsep { |
| 577 |
if ti.mbs { |
| 578 |
if j%2 == 0 { |
| 579 |
ee.WriteMapElemKey() |
| 580 |
} else { |
| 581 |
ee.WriteMapElemValue() |
| 582 |
} |
| 583 |
} else { |
| 584 |
ee.WriteArrayElem() |
| 585 |
} |
| 586 |
} |
| 587 |
if f.seq == seqTypeChan { |
| 588 |
if rv2, ok2 := rv.Recv(); ok2 { |
| 589 |
if useLookupRecognizedTypes && recognizedVtyp { |
| 590 |
e.encode(rv2i(rv2)) |
| 591 |
} else { |
| 592 |
e.encodeValue(rv2, fn, true) |
| 593 |
} |
| 594 |
} else { |
| 595 |
ee.EncodeNil() // WE HAVE TO DO SOMETHING, so nil if nothing received. |
| 596 |
} |
| 597 |
} else { |
| 598 |
if useLookupRecognizedTypes && recognizedVtyp { |
| 599 |
e.encode(rv2i(rv.Index(j))) |
| 600 |
} else { |
| 601 |
e.encodeValue(rv.Index(j), fn, true) |
| 602 |
} |
| 603 |
} |
| 604 |
} |
| 605 |
} |
| 606 |
|
| 607 |
if ti.mbs { |
| 608 |
ee.WriteMapEnd() |
| 609 |
} else { |
| 610 |
ee.WriteArrayEnd() |
| 611 |
} |
| 612 |
} |
| 613 |
|
| 614 |
func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) { |
| 615 |
fti := f.ti |
| 616 |
elemsep := e.hh.hasElemSeparators() |
| 617 |
tisfi := fti.sfip |
| 618 |
toMap := !(fti.toArray || e.h.StructToArray) |
| 619 |
if toMap { |
| 620 |
tisfi = fti.sfi |
| 621 |
} |
| 622 |
ee := e.e |
| 623 |
|
| 624 |
sfn := structFieldNode{v: rv, update: false} |
| 625 |
if toMap { |
| 626 |
ee.WriteMapStart(len(tisfi)) |
| 627 |
// asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 |
| 628 |
asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 |
| 629 |
if !elemsep { |
| 630 |
for _, si := range tisfi { |
| 631 |
if asSymbols { |
| 632 |
ee.EncodeSymbol(si.encName) |
| 633 |
} else { |
| 634 |
ee.EncodeString(c_UTF8, si.encName) |
| 635 |
} |
| 636 |
e.encodeValue(sfn.field(si), nil, true) |
| 637 |
} |
| 638 |
} else { |
| 639 |
for _, si := range tisfi { |
| 640 |
ee.WriteMapElemKey() |
| 641 |
if asSymbols { |
| 642 |
ee.EncodeSymbol(si.encName) |
| 643 |
} else { |
| 644 |
ee.EncodeString(c_UTF8, si.encName) |
| 645 |
} |
| 646 |
ee.WriteMapElemValue() |
| 647 |
e.encodeValue(sfn.field(si), nil, true) |
| 648 |
} |
| 649 |
} |
| 650 |
ee.WriteMapEnd() |
| 651 |
} else { |
| 652 |
ee.WriteArrayStart(len(tisfi)) |
| 653 |
if !elemsep { |
| 654 |
for _, si := range tisfi { |
| 655 |
e.encodeValue(sfn.field(si), nil, true) |
| 656 |
} |
| 657 |
} else { |
| 658 |
for _, si := range tisfi { |
| 659 |
ee.WriteArrayElem() |
| 660 |
e.encodeValue(sfn.field(si), nil, true) |
| 661 |
} |
| 662 |
} |
| 663 |
ee.WriteArrayEnd() |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { |
| 668 |
fti := f.ti |
| 669 |
elemsep := e.hh.hasElemSeparators() |
| 670 |
tisfi := fti.sfip |
| 671 |
toMap := !(fti.toArray || e.h.StructToArray) |
| 672 |
// if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct) |
| 673 |
if toMap { |
| 674 |
tisfi = fti.sfi |
| 675 |
} |
| 676 |
newlen := len(fti.sfi) |
| 677 |
ee := e.e |
| 678 |
|
| 679 |
// Use sync.Pool to reduce allocating slices unnecessarily. |
| 680 |
// The cost of sync.Pool is less than the cost of new allocation. |
| 681 |
// |
| 682 |
// Each element of the array pools one of encStructPool(8|16|32|64). |
| 683 |
// It allows the re-use of slices up to 64 in length. |
| 684 |
// A performance cost of encoding structs was collecting |
| 685 |
// which values were empty and should be omitted. |
| 686 |
// We needed slices of reflect.Value and string to collect them. |
| 687 |
// This shared pool reduces the amount of unnecessary creation we do. |
| 688 |
// The cost is that of locking sometimes, but sync.Pool is efficient |
| 689 |
// enough to reduce thread contention. |
| 690 |
|
| 691 |
var spool *sync.Pool |
| 692 |
var poolv interface{} |
| 693 |
var fkvs []stringRv |
| 694 |
if newlen <= 8 { |
| 695 |
spool, poolv = pool.stringRv8() |
| 696 |
fkvs = poolv.(*[8]stringRv)[:newlen] |
| 697 |
} else if newlen <= 16 { |
| 698 |
spool, poolv = pool.stringRv16() |
| 699 |
fkvs = poolv.(*[16]stringRv)[:newlen] |
| 700 |
} else if newlen <= 32 { |
| 701 |
spool, poolv = pool.stringRv32() |
| 702 |
fkvs = poolv.(*[32]stringRv)[:newlen] |
| 703 |
} else if newlen <= 64 { |
| 704 |
spool, poolv = pool.stringRv64() |
| 705 |
fkvs = poolv.(*[64]stringRv)[:newlen] |
| 706 |
} else if newlen <= 128 { |
| 707 |
spool, poolv = pool.stringRv128() |
| 708 |
fkvs = poolv.(*[128]stringRv)[:newlen] |
| 709 |
} else { |
| 710 |
fkvs = make([]stringRv, newlen) |
| 711 |
} |
| 712 |
|
| 713 |
newlen = 0 |
| 714 |
var kv stringRv |
| 715 |
recur := e.h.RecursiveEmptyCheck |
| 716 |
sfn := structFieldNode{v: rv, update: false} |
| 717 |
for _, si := range tisfi { |
| 718 |
// kv.r = si.field(rv, false) |
| 719 |
kv.r = sfn.field(si) |
| 720 |
if toMap { |
| 721 |
if si.omitEmpty && isEmptyValue(kv.r, recur, recur) { |
| 722 |
continue |
| 723 |
} |
| 724 |
kv.v = si.encName |
| 725 |
} else { |
| 726 |
// use the zero value. |
| 727 |
// if a reference or struct, set to nil (so you do not output too much) |
| 728 |
if si.omitEmpty && isEmptyValue(kv.r, recur, recur) { |
| 729 |
switch kv.r.Kind() { |
| 730 |
case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice: |
| 731 |
kv.r = reflect.Value{} //encode as nil |
| 732 |
} |
| 733 |
} |
| 734 |
} |
| 735 |
fkvs[newlen] = kv |
| 736 |
newlen++ |
| 737 |
} |
| 738 |
|
| 739 |
if toMap { |
| 740 |
ee.WriteMapStart(newlen) |
| 741 |
// asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 |
| 742 |
asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0 |
| 743 |
if !elemsep { |
| 744 |
for j := 0; j < newlen; j++ { |
| 745 |
kv = fkvs[j] |
| 746 |
if asSymbols { |
| 747 |
ee.EncodeSymbol(kv.v) |
| 748 |
} else { |
| 749 |
ee.EncodeString(c_UTF8, kv.v) |
| 750 |
} |
| 751 |
e.encodeValue(kv.r, nil, true) |
| 752 |
} |
| 753 |
} else { |
| 754 |
for j := 0; j < newlen; j++ { |
| 755 |
kv = fkvs[j] |
| 756 |
ee.WriteMapElemKey() |
| 757 |
if asSymbols { |
| 758 |
ee.EncodeSymbol(kv.v) |
| 759 |
} else { |
| 760 |
ee.EncodeString(c_UTF8, kv.v) |
| 761 |
} |
| 762 |
ee.WriteMapElemValue() |
| 763 |
e.encodeValue(kv.r, nil, true) |
| 764 |
} |
| 765 |
} |
| 766 |
ee.WriteMapEnd() |
| 767 |
} else { |
| 768 |
ee.WriteArrayStart(newlen) |
| 769 |
if !elemsep { |
| 770 |
for j := 0; j < newlen; j++ { |
| 771 |
e.encodeValue(fkvs[j].r, nil, true) |
| 772 |
} |
| 773 |
} else { |
| 774 |
for j := 0; j < newlen; j++ { |
| 775 |
ee.WriteArrayElem() |
| 776 |
e.encodeValue(fkvs[j].r, nil, true) |
| 777 |
} |
| 778 |
} |
| 779 |
ee.WriteArrayEnd() |
| 780 |
} |
| 781 |
|
| 782 |
// do not use defer. Instead, use explicit pool return at end of function. |
| 783 |
// defer has a cost we are trying to avoid. |
| 784 |
// If there is a panic and these slices are not returned, it is ok. |
| 785 |
if spool != nil { |
| 786 |
spool.Put(poolv) |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { |
| 791 |
ee := e.e |
| 792 |
if rv.IsNil() { |
| 793 |
ee.EncodeNil() |
| 794 |
return |
| 795 |
} |
| 796 |
|
| 797 |
l := rv.Len() |
| 798 |
ee.WriteMapStart(l) |
| 799 |
elemsep := e.hh.hasElemSeparators() |
| 800 |
if l == 0 { |
| 801 |
ee.WriteMapEnd() |
| 802 |
return |
| 803 |
} |
| 804 |
var asSymbols bool |
| 805 |
// determine the underlying key and val encFn's for the map. |
| 806 |
// This eliminates some work which is done for each loop iteration i.e. |
| 807 |
// rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn. |
| 808 |
// |
| 809 |
// However, if kind is reflect.Interface, do not pre-determine the |
| 810 |
// encoding type, because preEncodeValue may break it down to |
| 811 |
// a concrete type and kInterface will bomb. |
| 812 |
var keyFn, valFn *codecFn |
| 813 |
ti := f.ti |
| 814 |
rtkey0 := ti.rt.Key() |
| 815 |
rtkey := rtkey0 |
| 816 |
rtval0 := ti.rt.Elem() |
| 817 |
rtval := rtval0 |
| 818 |
rtkeyid := rt2id(rtkey0) |
| 819 |
rtvalid := rt2id(rtval0) |
| 820 |
for rtval.Kind() == reflect.Ptr { |
| 821 |
rtval = rtval.Elem() |
| 822 |
} |
| 823 |
if rtval.Kind() != reflect.Interface { |
| 824 |
valFn = e.cf.get(rtval, true, true) |
| 825 |
} |
| 826 |
mks := rv.MapKeys() |
| 827 |
|
| 828 |
if e.h.Canonical { |
| 829 |
e.kMapCanonical(rtkey, rv, mks, valFn, asSymbols) |
| 830 |
ee.WriteMapEnd() |
| 831 |
return |
| 832 |
} |
| 833 |
|
| 834 |
var recognizedKtyp, recognizedVtyp bool |
| 835 |
var keyTypeIsString = rtkeyid == stringTypId |
| 836 |
if keyTypeIsString { |
| 837 |
asSymbols = e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0 |
| 838 |
} else { |
| 839 |
if useLookupRecognizedTypes { |
| 840 |
if recognizedKtyp = isRecognizedRtidOrPtr(rtkeyid); recognizedKtyp { |
| 841 |
goto LABEL1 |
| 842 |
} |
| 843 |
} |
| 844 |
for rtkey.Kind() == reflect.Ptr { |
| 845 |
rtkey = rtkey.Elem() |
| 846 |
} |
| 847 |
if rtkey.Kind() != reflect.Interface { |
| 848 |
rtkeyid = rt2id(rtkey) |
| 849 |
keyFn = e.cf.get(rtkey, true, true) |
| 850 |
} |
| 851 |
} |
| 852 |
|
| 853 |
// for j, lmks := 0, len(mks); j < lmks; j++ { |
| 854 |
LABEL1: |
| 855 |
recognizedVtyp = useLookupRecognizedTypes && isRecognizedRtidOrPtr(rtvalid) |
| 856 |
for j := range mks { |
| 857 |
if elemsep { |
| 858 |
ee.WriteMapElemKey() |
| 859 |
} |
| 860 |
if keyTypeIsString { |
| 861 |
if asSymbols { |
| 862 |
ee.EncodeSymbol(mks[j].String()) |
| 863 |
} else { |
| 864 |
ee.EncodeString(c_UTF8, mks[j].String()) |
| 865 |
} |
| 866 |
} else if useLookupRecognizedTypes && recognizedKtyp { |
| 867 |
e.encode(rv2i(mks[j])) |
| 868 |
} else { |
| 869 |
e.encodeValue(mks[j], keyFn, true) |
| 870 |
} |
| 871 |
if elemsep { |
| 872 |
ee.WriteMapElemValue() |
| 873 |
} |
| 874 |
if useLookupRecognizedTypes && recognizedVtyp { |
| 875 |
e.encode(rv2i(rv.MapIndex(mks[j]))) |
| 876 |
} else { |
| 877 |
e.encodeValue(rv.MapIndex(mks[j]), valFn, true) |
| 878 |
} |
| 879 |
} |
| 880 |
ee.WriteMapEnd() |
| 881 |
} |
| 882 |
|
| 883 |
func (e *Encoder) kMapCanonical(rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *codecFn, asSymbols bool) { |
| 884 |
ee := e.e |
| 885 |
elemsep := e.hh.hasElemSeparators() |
| 886 |
// we previously did out-of-band if an extension was registered. |
| 887 |
// This is not necessary, as the natural kind is sufficient for ordering. |
| 888 |
|
| 889 |
// WHAT IS THIS? rtkeyid can never be a []uint8, per spec |
| 890 |
// if rtkeyid == uint8SliceTypId { |
| 891 |
// mksv := make([]bytesRv, len(mks)) |
| 892 |
// for i, k := range mks { |
| 893 |
// v := &mksv[i] |
| 894 |
// v.r = k |
| 895 |
// v.v = k.Bytes() |
| 896 |
// } |
| 897 |
// sort.Sort(bytesRvSlice(mksv)) |
| 898 |
// for i := range mksv { |
| 899 |
// if elemsep { |
| 900 |
// ee.WriteMapElemKey() |
| 901 |
// } |
| 902 |
// ee.EncodeStringBytes(c_RAW, mksv[i].v) |
| 903 |
// if elemsep { |
| 904 |
// ee.WriteMapElemValue() |
| 905 |
// } |
| 906 |
// e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 907 |
// } |
| 908 |
// return |
| 909 |
// } |
| 910 |
|
| 911 |
switch rtkey.Kind() { |
| 912 |
case reflect.Bool: |
| 913 |
mksv := make([]boolRv, len(mks)) |
| 914 |
for i, k := range mks { |
| 915 |
v := &mksv[i] |
| 916 |
v.r = k |
| 917 |
v.v = k.Bool() |
| 918 |
} |
| 919 |
sort.Sort(boolRvSlice(mksv)) |
| 920 |
for i := range mksv { |
| 921 |
if elemsep { |
| 922 |
ee.WriteMapElemKey() |
| 923 |
} |
| 924 |
ee.EncodeBool(mksv[i].v) |
| 925 |
if elemsep { |
| 926 |
ee.WriteMapElemValue() |
| 927 |
} |
| 928 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 929 |
} |
| 930 |
case reflect.String: |
| 931 |
mksv := make([]stringRv, len(mks)) |
| 932 |
for i, k := range mks { |
| 933 |
v := &mksv[i] |
| 934 |
v.r = k |
| 935 |
v.v = k.String() |
| 936 |
} |
| 937 |
sort.Sort(stringRvSlice(mksv)) |
| 938 |
for i := range mksv { |
| 939 |
if elemsep { |
| 940 |
ee.WriteMapElemKey() |
| 941 |
} |
| 942 |
if asSymbols { |
| 943 |
ee.EncodeSymbol(mksv[i].v) |
| 944 |
} else { |
| 945 |
ee.EncodeString(c_UTF8, mksv[i].v) |
| 946 |
} |
| 947 |
if elemsep { |
| 948 |
ee.WriteMapElemValue() |
| 949 |
} |
| 950 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 951 |
} |
| 952 |
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: |
| 953 |
mksv := make([]uintRv, len(mks)) |
| 954 |
for i, k := range mks { |
| 955 |
v := &mksv[i] |
| 956 |
v.r = k |
| 957 |
v.v = k.Uint() |
| 958 |
} |
| 959 |
sort.Sort(uintRvSlice(mksv)) |
| 960 |
for i := range mksv { |
| 961 |
if elemsep { |
| 962 |
ee.WriteMapElemKey() |
| 963 |
} |
| 964 |
ee.EncodeUint(mksv[i].v) |
| 965 |
if elemsep { |
| 966 |
ee.WriteMapElemValue() |
| 967 |
} |
| 968 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 969 |
} |
| 970 |
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: |
| 971 |
mksv := make([]intRv, len(mks)) |
| 972 |
for i, k := range mks { |
| 973 |
v := &mksv[i] |
| 974 |
v.r = k |
| 975 |
v.v = k.Int() |
| 976 |
} |
| 977 |
sort.Sort(intRvSlice(mksv)) |
| 978 |
for i := range mksv { |
| 979 |
if elemsep { |
| 980 |
ee.WriteMapElemKey() |
| 981 |
} |
| 982 |
ee.EncodeInt(mksv[i].v) |
| 983 |
if elemsep { |
| 984 |
ee.WriteMapElemValue() |
| 985 |
} |
| 986 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 987 |
} |
| 988 |
case reflect.Float32: |
| 989 |
mksv := make([]floatRv, len(mks)) |
| 990 |
for i, k := range mks { |
| 991 |
v := &mksv[i] |
| 992 |
v.r = k |
| 993 |
v.v = k.Float() |
| 994 |
} |
| 995 |
sort.Sort(floatRvSlice(mksv)) |
| 996 |
for i := range mksv { |
| 997 |
if elemsep { |
| 998 |
ee.WriteMapElemKey() |
| 999 |
} |
| 1000 |
ee.EncodeFloat32(float32(mksv[i].v)) |
| 1001 |
if elemsep { |
| 1002 |
ee.WriteMapElemValue() |
| 1003 |
} |
| 1004 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 1005 |
} |
| 1006 |
case reflect.Float64: |
| 1007 |
mksv := make([]floatRv, len(mks)) |
| 1008 |
for i, k := range mks { |
| 1009 |
v := &mksv[i] |
| 1010 |
v.r = k |
| 1011 |
v.v = k.Float() |
| 1012 |
} |
| 1013 |
sort.Sort(floatRvSlice(mksv)) |
| 1014 |
for i := range mksv { |
| 1015 |
if elemsep { |
| 1016 |
ee.WriteMapElemKey() |
| 1017 |
} |
| 1018 |
ee.EncodeFloat64(mksv[i].v) |
| 1019 |
if elemsep { |
| 1020 |
ee.WriteMapElemValue() |
| 1021 |
} |
| 1022 |
e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true) |
| 1023 |
} |
| 1024 |
default: |
| 1025 |
// out-of-band |
| 1026 |
// first encode each key to a []byte first, then sort them, then record |
| 1027 |
var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding |
| 1028 |
e2 := NewEncoderBytes(&mksv, e.hh) |
| 1029 |
mksbv := make([]bytesRv, len(mks)) |
| 1030 |
for i, k := range mks { |
| 1031 |
v := &mksbv[i] |
| 1032 |
l := len(mksv) |
| 1033 |
e2.MustEncode(k) |
| 1034 |
v.r = k |
| 1035 |
v.v = mksv[l:] |
| 1036 |
} |
| 1037 |
sort.Sort(bytesRvSlice(mksbv)) |
| 1038 |
for j := range mksbv { |
| 1039 |
if elemsep { |
| 1040 |
ee.WriteMapElemKey() |
| 1041 |
} |
| 1042 |
e.asis(mksbv[j].v) |
| 1043 |
if elemsep { |
| 1044 |
ee.WriteMapElemValue() |
| 1045 |
} |
| 1046 |
e.encodeValue(rv.MapIndex(mksbv[j].r), valFn, true) |
| 1047 |
} |
| 1048 |
} |
| 1049 |
} |
| 1050 |
|
| 1051 |
// // -------------------------------------------------- |
| 1052 |
|
| 1053 |
// An Encoder writes an object to an output stream in the codec format. |
| 1054 |
type Encoder struct { |
| 1055 |
// hopefully, reduce derefencing cost by laying the encWriter inside the Encoder |
| 1056 |
e encDriver |
| 1057 |
// NOTE: Encoder shouldn't call it's write methods, |
| 1058 |
// as the handler MAY need to do some coordination. |
| 1059 |
w encWriter |
| 1060 |
|
| 1061 |
hh Handle |
| 1062 |
h *BasicHandle |
| 1063 |
|
| 1064 |
// ---- cpu cache line boundary? |
| 1065 |
|
| 1066 |
wi ioEncWriter |
| 1067 |
wb bytesEncWriter |
| 1068 |
bw bufio.Writer |
| 1069 |
|
| 1070 |
// cr containerStateRecv |
| 1071 |
as encDriverAsis |
| 1072 |
// ---- cpu cache line boundary? |
| 1073 |
|
| 1074 |
ci set |
| 1075 |
err error |
| 1076 |
|
| 1077 |
b [scratchByteArrayLen]byte |
| 1078 |
cf codecFner |
| 1079 |
} |
| 1080 |
|
| 1081 |
// NewEncoder returns an Encoder for encoding into an io.Writer. |
| 1082 |
// |
| 1083 |
// For efficiency, Users are encouraged to pass in a memory buffered writer |
| 1084 |
// (eg bufio.Writer, bytes.Buffer). |
| 1085 |
func NewEncoder(w io.Writer, h Handle) *Encoder { |
| 1086 |
e := newEncoder(h) |
| 1087 |
e.Reset(w) |
| 1088 |
return e |
| 1089 |
} |
| 1090 |
|
| 1091 |
// NewEncoderBytes returns an encoder for encoding directly and efficiently |
| 1092 |
// into a byte slice, using zero-copying to temporary slices. |
| 1093 |
// |
| 1094 |
// It will potentially replace the output byte slice pointed to. |
| 1095 |
// After encoding, the out parameter contains the encoded contents. |
| 1096 |
func NewEncoderBytes(out *[]byte, h Handle) *Encoder { |
| 1097 |
e := newEncoder(h) |
| 1098 |
e.ResetBytes(out) |
| 1099 |
return e |
| 1100 |
} |
| 1101 |
|
| 1102 |
func newEncoder(h Handle) *Encoder { |
| 1103 |
e := &Encoder{hh: h, h: h.getBasicHandle()} |
| 1104 |
e.e = h.newEncDriver(e) |
| 1105 |
e.as, _ = e.e.(encDriverAsis) |
| 1106 |
// e.cr, _ = e.e.(containerStateRecv) |
| 1107 |
return e |
| 1108 |
} |
| 1109 |
|
| 1110 |
// Reset the Encoder with a new output stream. |
| 1111 |
// |
| 1112 |
// This accommodates using the state of the Encoder, |
| 1113 |
// where it has "cached" information about sub-engines. |
| 1114 |
func (e *Encoder) Reset(w io.Writer) { |
| 1115 |
var ok bool |
| 1116 |
e.wi.w = w |
| 1117 |
if e.h.WriterBufferSize > 0 { |
| 1118 |
bw := bufio.NewWriterSize(w, e.h.WriterBufferSize) |
| 1119 |
e.bw = *bw |
| 1120 |
e.wi.bw = &e.bw |
| 1121 |
e.wi.sw = &e.bw |
| 1122 |
e.wi.fw = &e.bw |
| 1123 |
e.wi.ww = &e.bw |
| 1124 |
} else { |
| 1125 |
if e.wi.bw, ok = w.(io.ByteWriter); !ok { |
| 1126 |
e.wi.bw = &e.wi |
| 1127 |
} |
| 1128 |
if e.wi.sw, ok = w.(ioEncStringWriter); !ok { |
| 1129 |
e.wi.sw = &e.wi |
| 1130 |
} |
| 1131 |
e.wi.fw, _ = w.(ioEncFlusher) |
| 1132 |
e.wi.ww = w |
| 1133 |
} |
| 1134 |
e.w = &e.wi |
| 1135 |
e.e.reset() |
| 1136 |
e.cf.reset(e.hh) |
| 1137 |
e.err = nil |
| 1138 |
} |
| 1139 |
|
| 1140 |
func (e *Encoder) ResetBytes(out *[]byte) { |
| 1141 |
in := *out |
| 1142 |
if in == nil { |
| 1143 |
in = make([]byte, defEncByteBufSize) |
| 1144 |
} |
| 1145 |
e.wb.b, e.wb.out, e.wb.c = in, out, 0 |
| 1146 |
e.w = &e.wb |
| 1147 |
e.e.reset() |
| 1148 |
e.cf.reset(e.hh) |
| 1149 |
e.err = nil |
| 1150 |
} |
| 1151 |
|
| 1152 |
// Encode writes an object into a stream. |
| 1153 |
// |
| 1154 |
// Encoding can be configured via the struct tag for the fields. |
| 1155 |
// The "codec" key in struct field's tag value is the key name, |
| 1156 |
// followed by an optional comma and options. |
| 1157 |
// Note that the "json" key is used in the absence of the "codec" key. |
| 1158 |
// |
| 1159 |
// To set an option on all fields (e.g. omitempty on all fields), you |
| 1160 |
// can create a field called _struct, and set flags on it. |
| 1161 |
// |
| 1162 |
// Struct values "usually" encode as maps. Each exported struct field is encoded unless: |
| 1163 |
// - the field's tag is "-", OR |
| 1164 |
// - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option. |
| 1165 |
// |
| 1166 |
// When encoding as a map, the first string in the tag (before the comma) |
| 1167 |
// is the map key string to use when encoding. |
| 1168 |
// |
| 1169 |
// However, struct values may encode as arrays. This happens when: |
| 1170 |
// - StructToArray Encode option is set, OR |
| 1171 |
// - the tag on the _struct field sets the "toarray" option |
| 1172 |
// Note that omitempty is ignored when encoding struct values as arrays, |
| 1173 |
// as an entry must be encoded for each field, to maintain its position. |
| 1174 |
// |
| 1175 |
// Values with types that implement MapBySlice are encoded as stream maps. |
| 1176 |
// |
| 1177 |
// The empty values (for omitempty option) are false, 0, any nil pointer |
| 1178 |
// or interface value, and any array, slice, map, or string of length zero. |
| 1179 |
// |
| 1180 |
// Anonymous fields are encoded inline except: |
| 1181 |
// - the struct tag specifies a replacement name (first value) |
| 1182 |
// - the field is of an interface type |
| 1183 |
// |
| 1184 |
// Examples: |
| 1185 |
// |
| 1186 |
// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below. |
| 1187 |
// type MyStruct struct { |
| 1188 |
// _struct bool `codec:",omitempty"` //set omitempty for every field |
| 1189 |
// Field1 string `codec:"-"` //skip this field |
| 1190 |
// Field2 int `codec:"myName"` //Use key "myName" in encode stream |
| 1191 |
// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty. |
| 1192 |
// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty. |
| 1193 |
// io.Reader //use key "Reader". |
| 1194 |
// MyStruct `codec:"my1" //use key "my1". |
| 1195 |
// MyStruct //inline it |
| 1196 |
// ... |
| 1197 |
// } |
| 1198 |
// |
| 1199 |
// type MyStruct struct { |
| 1200 |
// _struct bool `codec:",toarray"` //encode struct as an array |
| 1201 |
// } |
| 1202 |
// |
| 1203 |
// The mode of encoding is based on the type of the value. When a value is seen: |
| 1204 |
// - If a Selfer, call its CodecEncodeSelf method |
| 1205 |
// - If an extension is registered for it, call that extension function |
| 1206 |
// - If it implements encoding.(Binary|Text|JSON)Marshaler, call its Marshal(Binary|Text|JSON) method |
| 1207 |
// - Else encode it based on its reflect.Kind |
| 1208 |
// |
| 1209 |
// Note that struct field names and keys in map[string]XXX will be treated as symbols. |
| 1210 |
// Some formats support symbols (e.g. binc) and will properly encode the string |
| 1211 |
// only once in the stream, and use a tag to refer to it thereafter. |
| 1212 |
func (e *Encoder) Encode(v interface{}) (err error) { |
| 1213 |
defer panicToErrs2(&e.err, &err) |
| 1214 |
e.MustEncode(v) |
| 1215 |
return |
| 1216 |
} |
| 1217 |
|
| 1218 |
// MustEncode is like Encode, but panics if unable to Encode. |
| 1219 |
// This provides insight to the code location that triggered the error. |
| 1220 |
func (e *Encoder) MustEncode(v interface{}) { |
| 1221 |
if e.err != nil { |
| 1222 |
panic(e.err) |
| 1223 |
} |
| 1224 |
e.encode(v) |
| 1225 |
e.e.atEndOfEncode() |
| 1226 |
e.w.atEndOfEncode() |
| 1227 |
} |
| 1228 |
|
| 1229 |
func (e *Encoder) encode(iv interface{}) { |
| 1230 |
if iv == nil || definitelyNil(iv) { |
| 1231 |
e.e.EncodeNil() |
| 1232 |
return |
| 1233 |
} |
| 1234 |
if v, ok := iv.(Selfer); ok { |
| 1235 |
v.CodecEncodeSelf(e) |
| 1236 |
return |
| 1237 |
} |
| 1238 |
|
| 1239 |
switch v := iv.(type) { |
| 1240 |
// case nil: |
| 1241 |
// e.e.EncodeNil() |
| 1242 |
// case Selfer: |
| 1243 |
// v.CodecEncodeSelf(e) |
| 1244 |
case Raw: |
| 1245 |
e.rawBytes(v) |
| 1246 |
case reflect.Value: |
| 1247 |
e.encodeValue(v, nil, true) |
| 1248 |
|
| 1249 |
case string: |
| 1250 |
e.e.EncodeString(c_UTF8, v) |
| 1251 |
case bool: |
| 1252 |
e.e.EncodeBool(v) |
| 1253 |
case int: |
| 1254 |
e.e.EncodeInt(int64(v)) |
| 1255 |
case int8: |
| 1256 |
e.e.EncodeInt(int64(v)) |
| 1257 |
case int16: |
| 1258 |
e.e.EncodeInt(int64(v)) |
| 1259 |
case int32: |
| 1260 |
e.e.EncodeInt(int64(v)) |
| 1261 |
case int64: |
| 1262 |
e.e.EncodeInt(v) |
| 1263 |
case uint: |
| 1264 |
e.e.EncodeUint(uint64(v)) |
| 1265 |
case uint8: |
| 1266 |
e.e.EncodeUint(uint64(v)) |
| 1267 |
case uint16: |
| 1268 |
e.e.EncodeUint(uint64(v)) |
| 1269 |
case uint32: |
| 1270 |
e.e.EncodeUint(uint64(v)) |
| 1271 |
case uint64: |
| 1272 |
e.e.EncodeUint(v) |
| 1273 |
case uintptr: |
| 1274 |
e.e.EncodeUint(uint64(v)) |
| 1275 |
case float32: |
| 1276 |
e.e.EncodeFloat32(v) |
| 1277 |
case float64: |
| 1278 |
e.e.EncodeFloat64(v) |
| 1279 |
|
| 1280 |
case []uint8: |
| 1281 |
e.e.EncodeStringBytes(c_RAW, v) |
| 1282 |
|
| 1283 |
case *string: |
| 1284 |
e.e.EncodeString(c_UTF8, *v) |
| 1285 |
case *bool: |
| 1286 |
e.e.EncodeBool(*v) |
| 1287 |
case *int: |
| 1288 |
e.e.EncodeInt(int64(*v)) |
| 1289 |
case *int8: |
| 1290 |
e.e.EncodeInt(int64(*v)) |
| 1291 |
case *int16: |
| 1292 |
e.e.EncodeInt(int64(*v)) |
| 1293 |
case *int32: |
| 1294 |
e.e.EncodeInt(int64(*v)) |
| 1295 |
case *int64: |
| 1296 |
e.e.EncodeInt(*v) |
| 1297 |
case *uint: |
| 1298 |
e.e.EncodeUint(uint64(*v)) |
| 1299 |
case *uint8: |
| 1300 |
e.e.EncodeUint(uint64(*v)) |
| 1301 |
case *uint16: |
| 1302 |
e.e.EncodeUint(uint64(*v)) |
| 1303 |
case *uint32: |
| 1304 |
e.e.EncodeUint(uint64(*v)) |
| 1305 |
case *uint64: |
| 1306 |
e.e.EncodeUint(*v) |
| 1307 |
case *uintptr: |
| 1308 |
e.e.EncodeUint(uint64(*v)) |
| 1309 |
case *float32: |
| 1310 |
e.e.EncodeFloat32(*v) |
| 1311 |
case *float64: |
| 1312 |
e.e.EncodeFloat64(*v) |
| 1313 |
|
| 1314 |
case *[]uint8: |
| 1315 |
e.e.EncodeStringBytes(c_RAW, *v) |
| 1316 |
|
| 1317 |
default: |
| 1318 |
if !fastpathEncodeTypeSwitch(iv, e) { |
| 1319 |
e.encodeValue(reflect.ValueOf(iv), nil, false) |
| 1320 |
} |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn, checkFastpath bool) { |
| 1325 |
// if a valid fn is passed, it MUST BE for the dereferenced type of rv |
| 1326 |
var sptr uintptr |
| 1327 |
TOP: |
| 1328 |
switch rv.Kind() { |
| 1329 |
case reflect.Ptr: |
| 1330 |
if rv.IsNil() { |
| 1331 |
e.e.EncodeNil() |
| 1332 |
return |
| 1333 |
} |
| 1334 |
rv = rv.Elem() |
| 1335 |
if e.h.CheckCircularRef && rv.Kind() == reflect.Struct { |
| 1336 |
// TODO: Movable pointers will be an issue here. Future problem. |
| 1337 |
sptr = rv.UnsafeAddr() |
| 1338 |
break TOP |
| 1339 |
} |
| 1340 |
goto TOP |
| 1341 |
case reflect.Interface: |
| 1342 |
if rv.IsNil() { |
| 1343 |
e.e.EncodeNil() |
| 1344 |
return |
| 1345 |
} |
| 1346 |
rv = rv.Elem() |
| 1347 |
goto TOP |
| 1348 |
case reflect.Slice, reflect.Map: |
| 1349 |
if rv.IsNil() { |
| 1350 |
e.e.EncodeNil() |
| 1351 |
return |
| 1352 |
} |
| 1353 |
case reflect.Invalid, reflect.Func: |
| 1354 |
e.e.EncodeNil() |
| 1355 |
return |
| 1356 |
} |
| 1357 |
|
| 1358 |
if sptr != 0 && (&e.ci).add(sptr) { |
| 1359 |
e.errorf("circular reference found: # %d", sptr) |
| 1360 |
} |
| 1361 |
|
| 1362 |
if fn == nil { |
| 1363 |
rt := rv.Type() |
| 1364 |
// TODO: calling isRecognizedRtid here is a major slowdown |
| 1365 |
if false && useLookupRecognizedTypes && isRecognizedRtidOrPtr(rt2id(rt)) { |
| 1366 |
e.encode(rv2i(rv)) |
| 1367 |
return |
| 1368 |
} |
| 1369 |
// always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer |
| 1370 |
fn = e.cf.get(rt, checkFastpath, true) |
| 1371 |
} |
| 1372 |
fn.fe(e, &fn.i, rv) |
| 1373 |
if sptr != 0 { |
| 1374 |
(&e.ci).remove(sptr) |
| 1375 |
} |
| 1376 |
} |
| 1377 |
|
| 1378 |
func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) { |
| 1379 |
if fnerr != nil { |
| 1380 |
panic(fnerr) |
| 1381 |
} |
| 1382 |
if bs == nil { |
| 1383 |
e.e.EncodeNil() |
| 1384 |
} else if asis { |
| 1385 |
e.asis(bs) |
| 1386 |
} else { |
| 1387 |
e.e.EncodeStringBytes(c, bs) |
| 1388 |
} |
| 1389 |
} |
| 1390 |
|
| 1391 |
func (e *Encoder) asis(v []byte) { |
| 1392 |
if e.as == nil { |
| 1393 |
e.w.writeb(v) |
| 1394 |
} else { |
| 1395 |
e.as.EncodeAsis(v) |
| 1396 |
} |
| 1397 |
} |
| 1398 |
|
| 1399 |
func (e *Encoder) rawBytes(vv Raw) { |
| 1400 |
v := []byte(vv) |
| 1401 |
if !e.h.Raw { |
| 1402 |
e.errorf("Raw values cannot be encoded: %v", v) |
| 1403 |
} |
| 1404 |
if e.as == nil { |
| 1405 |
e.w.writeb(v) |
| 1406 |
} else { |
| 1407 |
e.as.EncodeAsis(v) |
| 1408 |
} |
| 1409 |
} |
| 1410 |
|
| 1411 |
func (e *Encoder) errorf(format string, params ...interface{}) { |
| 1412 |
err := fmt.Errorf(format, params...) |
| 1413 |
panic(err) |
| 1414 |
} |