github.com/patricebensoussan/go/codec@v1.2.99/encode.go (about) 1 // Copyright (c) 2012-2020 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 "encoding" 8 "errors" 9 "io" 10 "reflect" 11 "sort" 12 "strconv" 13 "time" 14 ) 15 16 // defEncByteBufSize is the default size of []byte used 17 // for bufio buffer or []byte (when nil passed) 18 const defEncByteBufSize = 1 << 10 // 4:16, 6:64, 8:256, 10:1024 19 20 var errEncoderNotInitialized = errors.New("Encoder not initialized") 21 22 // encDriver abstracts the actual codec (binc vs msgpack, etc) 23 type encDriver interface { 24 EncodeNil() 25 EncodeInt(i int64) 26 EncodeUint(i uint64) 27 EncodeBool(b bool) 28 EncodeFloat32(f float32) 29 EncodeFloat64(f float64) 30 EncodeRawExt(re *RawExt) 31 EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext) 32 // EncodeString using cUTF8, honor'ing StringToRaw flag 33 EncodeString(v string) 34 EncodeStringBytesRaw(v []byte) 35 EncodeTime(time.Time) 36 WriteArrayStart(length int) 37 WriteArrayEnd() 38 WriteMapStart(length int) 39 WriteMapEnd() 40 41 // reset will reset current encoding runtime state, and cached information from the handle 42 reset() 43 44 encoder() *Encoder 45 46 driverStateManager 47 } 48 49 type encDriverContainerTracker interface { 50 WriteArrayElem() 51 WriteMapElemKey() 52 WriteMapElemValue() 53 } 54 55 type encDriverNoState struct{} 56 57 func (encDriverNoState) captureState() interface{} { return nil } 58 func (encDriverNoState) reset() {} 59 func (encDriverNoState) resetState() {} 60 func (encDriverNoState) restoreState(v interface{}) {} 61 62 type encDriverNoopContainerWriter struct{} 63 64 func (encDriverNoopContainerWriter) WriteArrayStart(length int) {} 65 func (encDriverNoopContainerWriter) WriteArrayEnd() {} 66 func (encDriverNoopContainerWriter) WriteMapStart(length int) {} 67 func (encDriverNoopContainerWriter) WriteMapEnd() {} 68 69 // encStructFieldObj[Slice] is used for sorting when there are missing fields and canonical flag is set 70 type encStructFieldObj struct { 71 key string 72 rv reflect.Value 73 intf interface{} 74 ascii bool 75 isRv bool 76 } 77 78 type encStructFieldObjSlice []encStructFieldObj 79 80 func (p encStructFieldObjSlice) Len() int { return len(p) } 81 func (p encStructFieldObjSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] } 82 func (p encStructFieldObjSlice) Less(i, j int) bool { 83 return p[uint(i)].key < p[uint(j)].key 84 } 85 86 // EncodeOptions captures configuration options during encode. 87 type EncodeOptions struct { 88 // WriterBufferSize is the size of the buffer used when writing. 89 // 90 // if > 0, we use a smart buffer internally for performance purposes. 91 WriterBufferSize int 92 93 // ChanRecvTimeout is the timeout used when selecting from a chan. 94 // 95 // Configuring this controls how we receive from a chan during the encoding process. 96 // - If ==0, we only consume the elements currently available in the chan. 97 // - if <0, we consume until the chan is closed. 98 // - If >0, we consume until this timeout. 99 ChanRecvTimeout time.Duration 100 101 // StructToArray specifies to encode a struct as an array, and not as a map 102 StructToArray bool 103 104 // Canonical representation means that encoding a value will always result in the same 105 // sequence of bytes. 106 // 107 // This only affects maps, as the iteration order for maps is random. 108 // 109 // The implementation MAY use the natural sort order for the map keys if possible: 110 // 111 // - If there is a natural sort order (ie for number, bool, string or []byte keys), 112 // then the map keys are first sorted in natural order and then written 113 // with corresponding map values to the strema. 114 // - If there is no natural sort order, then the map keys will first be 115 // encoded into []byte, and then sorted, 116 // before writing the sorted keys and the corresponding map values to the stream. 117 // 118 Canonical bool 119 120 // CheckCircularRef controls whether we check for circular references 121 // and error fast during an encode. 122 // 123 // If enabled, an error is received if a pointer to a struct 124 // references itself either directly or through one of its fields (iteratively). 125 // 126 // This is opt-in, as there may be a performance hit to checking circular references. 127 CheckCircularRef bool 128 129 // RecursiveEmptyCheck controls how we determine whether a value is empty. 130 // 131 // If true, we descend into interfaces and pointers to reursively check if value is empty. 132 // 133 // We *might* check struct fields one by one to see if empty 134 // (if we cannot directly check if a struct value is equal to its zero value). 135 // If so, we honor IsZero, Comparable, IsCodecEmpty(), etc. 136 // Note: This *may* make OmitEmpty more expensive due to the large number of reflect calls. 137 // 138 // If false, we check if the value is equal to its zero value (newly allocated state). 139 RecursiveEmptyCheck bool 140 141 // Raw controls whether we encode Raw values. 142 // This is a "dangerous" option and must be explicitly set. 143 // If set, we blindly encode Raw values as-is, without checking 144 // if they are a correct representation of a value in that format. 145 // If unset, we error out. 146 Raw bool 147 148 // StringToRaw controls how strings are encoded. 149 // 150 // As a go string is just an (immutable) sequence of bytes, 151 // it can be encoded either as raw bytes or as a UTF string. 152 // 153 // By default, strings are encoded as UTF-8. 154 // but can be treated as []byte during an encode. 155 // 156 // Note that things which we know (by definition) to be UTF-8 157 // are ALWAYS encoded as UTF-8 strings. 158 // These include encoding.TextMarshaler, time.Format calls, struct field names, etc. 159 StringToRaw bool 160 161 // OptimumSize controls whether we optimize for the smallest size. 162 // 163 // Some formats will use this flag to determine whether to encode 164 // in the smallest size possible, even if it takes slightly longer. 165 // 166 // For example, some formats that support half-floats might check if it is possible 167 // to store a float64 as a half float. Doing this check has a small performance cost, 168 // but the benefit is that the encoded message will be smaller. 169 OptimumSize bool 170 171 // NoAddressableReadonly controls whether we try to force a non-addressable value 172 // to be addressable so we can call a pointer method on it e.g. for types 173 // that support Selfer, json.Marshaler, etc. 174 // 175 // Use it in the very rare occurrence that your types modify a pointer value when calling 176 // an encode callback function e.g. JsonMarshal, TextMarshal, BinaryMarshal or CodecEncodeSelf. 177 NoAddressableReadonly bool 178 } 179 180 // --------------------------------------------- 181 182 func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) { 183 e.e.EncodeRawExt(rv2i(rv).(*RawExt)) 184 } 185 186 func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) { 187 e.e.EncodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn) 188 } 189 190 func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) { 191 rv2i(rv).(Selfer).CodecEncodeSelf(e) 192 } 193 194 func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) { 195 bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary() 196 e.marshalRaw(bs, fnerr) 197 } 198 199 func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) { 200 bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText() 201 e.marshalUtf8(bs, fnerr) 202 } 203 204 func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) { 205 bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON() 206 e.marshalAsis(bs, fnerr) 207 } 208 209 func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) { 210 e.rawBytes(rv2i(rv).(Raw)) 211 } 212 213 func (e *Encoder) encodeComplex64(v complex64) { 214 if imag(v) != 0 { 215 e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v)) 216 } 217 e.e.EncodeFloat32(real(v)) 218 } 219 220 func (e *Encoder) encodeComplex128(v complex128) { 221 if imag(v) != 0 { 222 e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v)) 223 } 224 e.e.EncodeFloat64(real(v)) 225 } 226 227 func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) { 228 e.e.EncodeBool(rvGetBool(rv)) 229 } 230 231 func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) { 232 e.e.EncodeTime(rvGetTime(rv)) 233 } 234 235 func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) { 236 e.e.EncodeString(rvGetString(rv)) 237 } 238 239 func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) { 240 e.e.EncodeFloat32(rvGetFloat32(rv)) 241 } 242 243 func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) { 244 e.e.EncodeFloat64(rvGetFloat64(rv)) 245 } 246 247 func (e *Encoder) kComplex64(f *codecFnInfo, rv reflect.Value) { 248 e.encodeComplex64(rvGetComplex64(rv)) 249 } 250 251 func (e *Encoder) kComplex128(f *codecFnInfo, rv reflect.Value) { 252 e.encodeComplex128(rvGetComplex128(rv)) 253 } 254 255 func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) { 256 e.e.EncodeInt(int64(rvGetInt(rv))) 257 } 258 259 func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) { 260 e.e.EncodeInt(int64(rvGetInt8(rv))) 261 } 262 263 func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) { 264 e.e.EncodeInt(int64(rvGetInt16(rv))) 265 } 266 267 func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) { 268 e.e.EncodeInt(int64(rvGetInt32(rv))) 269 } 270 271 func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) { 272 e.e.EncodeInt(int64(rvGetInt64(rv))) 273 } 274 275 func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) { 276 e.e.EncodeUint(uint64(rvGetUint(rv))) 277 } 278 279 func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) { 280 e.e.EncodeUint(uint64(rvGetUint8(rv))) 281 } 282 283 func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) { 284 e.e.EncodeUint(uint64(rvGetUint16(rv))) 285 } 286 287 func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) { 288 e.e.EncodeUint(uint64(rvGetUint32(rv))) 289 } 290 291 func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) { 292 e.e.EncodeUint(uint64(rvGetUint64(rv))) 293 } 294 295 func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) { 296 e.e.EncodeUint(uint64(rvGetUintptr(rv))) 297 } 298 299 func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) { 300 e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv) 301 } 302 303 func chanToSlice(rv reflect.Value, rtslice reflect.Type, timeout time.Duration) (rvcs reflect.Value) { 304 rvcs = rvZeroK(rtslice, reflect.Slice) 305 if timeout < 0 { // consume until close 306 for { 307 recv, recvOk := rv.Recv() 308 if !recvOk { 309 break 310 } 311 rvcs = reflect.Append(rvcs, recv) 312 } 313 } else { 314 cases := make([]reflect.SelectCase, 2) 315 cases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: rv} 316 if timeout == 0 { 317 cases[1] = reflect.SelectCase{Dir: reflect.SelectDefault} 318 } else { 319 tt := time.NewTimer(timeout) 320 cases[1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tt.C)} 321 } 322 for { 323 chosen, recv, recvOk := reflect.Select(cases) 324 if chosen == 1 || !recvOk { 325 break 326 } 327 rvcs = reflect.Append(rvcs, recv) 328 } 329 } 330 return 331 } 332 333 func (e *Encoder) kSeqFn(rtelem reflect.Type) (fn *codecFn) { 334 for rtelem.Kind() == reflect.Ptr { 335 rtelem = rtelem.Elem() 336 } 337 // if kind is reflect.Interface, do not pre-determine the encoding type, 338 // because preEncodeValue may break it down to a concrete type and kInterface will bomb. 339 if rtelem.Kind() != reflect.Interface { 340 fn = e.h.fn(rtelem) 341 } 342 return 343 } 344 345 func (e *Encoder) kSliceWMbs(rv reflect.Value, ti *typeInfo) { 346 var l = rvLenSlice(rv) 347 if l == 0 { 348 e.mapStart(0) 349 } else { 350 e.haltOnMbsOddLen(l) 351 e.mapStart(l >> 1) // e.mapStart(l / 2) 352 fn := e.kSeqFn(ti.elem) 353 for j := 0; j < l; j++ { 354 if j&1 == 0 { // j%2 == 0 { 355 e.mapElemKey() 356 } else { 357 e.mapElemValue() 358 } 359 e.encodeValue(rvSliceIndex(rv, j, ti), fn) 360 } 361 } 362 e.mapEnd() 363 } 364 365 func (e *Encoder) kSliceW(rv reflect.Value, ti *typeInfo) { 366 var l = rvLenSlice(rv) 367 e.arrayStart(l) 368 if l > 0 { 369 fn := e.kSeqFn(ti.elem) 370 for j := 0; j < l; j++ { 371 e.arrayElem() 372 e.encodeValue(rvSliceIndex(rv, j, ti), fn) 373 } 374 } 375 e.arrayEnd() 376 } 377 378 func (e *Encoder) kArrayWMbs(rv reflect.Value, ti *typeInfo) { 379 var l = rv.Len() 380 if l == 0 { 381 e.mapStart(0) 382 } else { 383 e.haltOnMbsOddLen(l) 384 e.mapStart(l >> 1) // e.mapStart(l / 2) 385 fn := e.kSeqFn(ti.elem) 386 for j := 0; j < l; j++ { 387 if j&1 == 0 { // j%2 == 0 { 388 e.mapElemKey() 389 } else { 390 e.mapElemValue() 391 } 392 e.encodeValue(rv.Index(j), fn) 393 } 394 } 395 e.mapEnd() 396 } 397 398 func (e *Encoder) kArrayW(rv reflect.Value, ti *typeInfo) { 399 var l = rv.Len() 400 e.arrayStart(l) 401 if l > 0 { 402 fn := e.kSeqFn(ti.elem) 403 for j := 0; j < l; j++ { 404 e.arrayElem() 405 e.encodeValue(rv.Index(j), fn) 406 } 407 } 408 e.arrayEnd() 409 } 410 411 func (e *Encoder) kChan(f *codecFnInfo, rv reflect.Value) { 412 if f.ti.chandir&uint8(reflect.RecvDir) == 0 { 413 e.errorf("send-only channel cannot be encoded") 414 } 415 if !f.ti.mbs && uint8TypId == rt2id(f.ti.elem) { 416 e.kSliceBytesChan(rv) 417 return 418 } 419 rtslice := reflect.SliceOf(f.ti.elem) 420 rv = chanToSlice(rv, rtslice, e.h.ChanRecvTimeout) 421 ti := e.h.getTypeInfo(rt2id(rtslice), rtslice) 422 if f.ti.mbs { 423 e.kSliceWMbs(rv, ti) 424 } else { 425 e.kSliceW(rv, ti) 426 } 427 } 428 429 func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) { 430 if f.ti.mbs { 431 e.kSliceWMbs(rv, f.ti) 432 } else if f.ti.rtid == uint8SliceTypId || uint8TypId == rt2id(f.ti.elem) { 433 e.e.EncodeStringBytesRaw(rvGetBytes(rv)) 434 } else { 435 e.kSliceW(rv, f.ti) 436 } 437 } 438 439 func (e *Encoder) kArray(f *codecFnInfo, rv reflect.Value) { 440 if f.ti.mbs { 441 e.kArrayWMbs(rv, f.ti) 442 } else if handleBytesWithinKArray && uint8TypId == rt2id(f.ti.elem) { 443 e.e.EncodeStringBytesRaw(rvGetArrayBytes(rv, []byte{})) 444 } else { 445 e.kArrayW(rv, f.ti) 446 } 447 } 448 449 func (e *Encoder) kSliceBytesChan(rv reflect.Value) { 450 // do not use range, so that the number of elements encoded 451 // does not change, and encoding does not hang waiting on someone to close chan. 452 453 bs0 := e.blist.peek(32, true) 454 bs := bs0 455 456 irv := rv2i(rv) 457 ch, ok := irv.(<-chan byte) 458 if !ok { 459 ch = irv.(chan byte) 460 } 461 462 L1: 463 switch timeout := e.h.ChanRecvTimeout; { 464 case timeout == 0: // only consume available 465 for { 466 select { 467 case b := <-ch: 468 bs = append(bs, b) 469 default: 470 break L1 471 } 472 } 473 case timeout > 0: // consume until timeout 474 tt := time.NewTimer(timeout) 475 for { 476 select { 477 case b := <-ch: 478 bs = append(bs, b) 479 case <-tt.C: 480 // close(tt.C) 481 break L1 482 } 483 } 484 default: // consume until close 485 for b := range ch { 486 bs = append(bs, b) 487 } 488 } 489 490 e.e.EncodeStringBytesRaw(bs) 491 e.blist.put(bs) 492 if !byteSliceSameData(bs0, bs) { 493 e.blist.put(bs0) 494 } 495 } 496 497 func (e *Encoder) kStructSfi(f *codecFnInfo) []*structFieldInfo { 498 if e.h.Canonical { 499 return f.ti.sfi.sorted() 500 } 501 return f.ti.sfi.source() 502 } 503 504 func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) { 505 var tisfi []*structFieldInfo 506 if f.ti.toArray || e.h.StructToArray { // toArray 507 tisfi = f.ti.sfi.source() 508 e.arrayStart(len(tisfi)) 509 for _, si := range tisfi { 510 e.arrayElem() 511 e.encodeValue(si.path.field(rv), nil) 512 } 513 e.arrayEnd() 514 } else { 515 tisfi = e.kStructSfi(f) 516 e.mapStart(len(tisfi)) 517 keytyp := f.ti.keyType 518 for _, si := range tisfi { 519 e.mapElemKey() 520 e.kStructFieldKey(keytyp, si.path.encNameAsciiAlphaNum, si.encName) 521 e.mapElemValue() 522 e.encodeValue(si.path.field(rv), nil) 523 } 524 e.mapEnd() 525 } 526 } 527 528 func (e *Encoder) kStructFieldKey(keyType valueType, encNameAsciiAlphaNum bool, encName string) { 529 encStructFieldKey(encName, e.e, e.w(), keyType, encNameAsciiAlphaNum, e.js) 530 } 531 532 func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { 533 var newlen int 534 ti := f.ti 535 toMap := !(ti.toArray || e.h.StructToArray) 536 var mf map[string]interface{} 537 if ti.flagMissingFielder { 538 mf = rv2i(rv).(MissingFielder).CodecMissingFields() 539 toMap = true 540 newlen += len(mf) 541 } else if ti.flagMissingFielderPtr { 542 rv2 := e.addrRV(rv, ti.rt, ti.ptr) 543 mf = rv2i(rv2).(MissingFielder).CodecMissingFields() 544 toMap = true 545 newlen += len(mf) 546 } 547 tisfi := ti.sfi.source() 548 newlen += len(tisfi) 549 550 var fkvs = e.slist.get(newlen)[:newlen] 551 552 recur := e.h.RecursiveEmptyCheck 553 554 var kv sfiRv 555 var j int 556 if toMap { 557 newlen = 0 558 for _, si := range e.kStructSfi(f) { 559 kv.r = si.path.field(rv) 560 if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) { 561 continue 562 } 563 kv.v = si 564 fkvs[newlen] = kv 565 newlen++ 566 } 567 568 var mf2s []stringIntf 569 if len(mf) > 0 { 570 mf2s = make([]stringIntf, 0, len(mf)) 571 for k, v := range mf { 572 if k == "" { 573 continue 574 } 575 if ti.infoFieldOmitempty && isEmptyValue(reflect.ValueOf(v), e.h.TypeInfos, recur) { 576 continue 577 } 578 mf2s = append(mf2s, stringIntf{k, v}) 579 } 580 } 581 582 e.mapStart(newlen + len(mf2s)) 583 584 // When there are missing fields, and Canonical flag is set, 585 // we cannot have the missing fields and struct fields sorted independently. 586 // We have to capture them together and sort as a unit. 587 588 if len(mf2s) > 0 && e.h.Canonical { 589 mf2w := make([]encStructFieldObj, newlen+len(mf2s)) 590 for j = 0; j < newlen; j++ { 591 kv = fkvs[j] 592 mf2w[j] = encStructFieldObj{kv.v.encName, kv.r, nil, kv.v.path.encNameAsciiAlphaNum, true} 593 } 594 for _, v := range mf2s { 595 mf2w[j] = encStructFieldObj{v.v, reflect.Value{}, v.i, false, false} 596 j++ 597 } 598 sort.Sort((encStructFieldObjSlice)(mf2w)) 599 for _, v := range mf2w { 600 e.mapElemKey() 601 e.kStructFieldKey(ti.keyType, v.ascii, v.key) 602 e.mapElemValue() 603 if v.isRv { 604 e.encodeValue(v.rv, nil) 605 } else { 606 e.encode(v.intf) 607 } 608 } 609 } else { 610 keytyp := ti.keyType 611 for j = 0; j < newlen; j++ { 612 kv = fkvs[j] 613 e.mapElemKey() 614 e.kStructFieldKey(keytyp, kv.v.path.encNameAsciiAlphaNum, kv.v.encName) 615 e.mapElemValue() 616 e.encodeValue(kv.r, nil) 617 } 618 for _, v := range mf2s { 619 e.mapElemKey() 620 e.kStructFieldKey(keytyp, false, v.v) 621 e.mapElemValue() 622 e.encode(v.i) 623 } 624 } 625 626 e.mapEnd() 627 } else { 628 newlen = len(tisfi) 629 for i, si := range tisfi { // use unsorted array (to match sequence in struct) 630 kv.r = si.path.field(rv) 631 // use the zero value. 632 // if a reference or struct, set to nil (so you do not output too much) 633 if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) { 634 switch kv.r.Kind() { 635 case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice: 636 kv.r = reflect.Value{} //encode as nil 637 } 638 } 639 fkvs[i] = kv 640 } 641 // encode it all 642 e.arrayStart(newlen) 643 for j = 0; j < newlen; j++ { 644 e.arrayElem() 645 e.encodeValue(fkvs[j].r, nil) 646 } 647 e.arrayEnd() 648 } 649 650 // do not use defer. Instead, use explicit pool return at end of function. 651 // defer has a cost we are trying to avoid. 652 // If there is a panic and these slices are not returned, it is ok. 653 e.slist.put(fkvs) 654 } 655 656 func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { 657 l := rvLenMap(rv) 658 e.mapStart(l) 659 if l == 0 { 660 e.mapEnd() 661 return 662 } 663 664 // determine the underlying key and val encFn's for the map. 665 // This eliminates some work which is done for each loop iteration i.e. 666 // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn. 667 // 668 // However, if kind is reflect.Interface, do not pre-determine the 669 // encoding type, because preEncodeValue may break it down to 670 // a concrete type and kInterface will bomb. 671 672 var keyFn, valFn *codecFn 673 674 ktypeKind := reflect.Kind(f.ti.keykind) 675 vtypeKind := reflect.Kind(f.ti.elemkind) 676 677 rtval := f.ti.elem 678 rtvalkind := vtypeKind 679 for rtvalkind == reflect.Ptr { 680 rtval = rtval.Elem() 681 rtvalkind = rtval.Kind() 682 } 683 if rtvalkind != reflect.Interface { 684 valFn = e.h.fn(rtval) 685 } 686 687 var rvv = mapAddrLoopvarRV(f.ti.elem, vtypeKind) 688 689 if e.h.Canonical { 690 e.kMapCanonical(f.ti, rv, rvv, valFn) 691 e.mapEnd() 692 return 693 } 694 695 rtkey := f.ti.key 696 var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid 697 if !keyTypeIsString { 698 for rtkey.Kind() == reflect.Ptr { 699 rtkey = rtkey.Elem() 700 } 701 if rtkey.Kind() != reflect.Interface { 702 keyFn = e.h.fn(rtkey) 703 } 704 } 705 706 var rvk = mapAddrLoopvarRV(f.ti.key, ktypeKind) 707 708 var it mapIter 709 mapRange(&it, rv, rvk, rvv, true) 710 711 for it.Next() { 712 e.mapElemKey() 713 if keyTypeIsString { 714 e.e.EncodeString(it.Key().String()) 715 } else { 716 e.encodeValue(it.Key(), keyFn) 717 } 718 e.mapElemValue() 719 e.encodeValue(it.Value(), valFn) 720 } 721 it.Done() 722 723 e.mapEnd() 724 } 725 726 func (e *Encoder) kMapCanonical(ti *typeInfo, rv, rvv reflect.Value, valFn *codecFn) { 727 // we previously did out-of-band if an extension was registered. 728 // This is not necessary, as the natural kind is sufficient for ordering. 729 730 rtkey := ti.key 731 mks := rv.MapKeys() 732 rtkeyKind := rtkey.Kind() 733 kfast := mapKeyFastKindFor(rtkeyKind) 734 visindirect := mapStoresElemIndirect(uintptr(ti.elemsize)) 735 visref := refBitset.isset(ti.elemkind) 736 737 switch rtkeyKind { 738 case reflect.Bool: 739 mksv := make([]boolRv, len(mks)) 740 for i, k := range mks { 741 v := &mksv[i] 742 v.r = k 743 v.v = k.Bool() 744 } 745 sort.Sort(boolRvSlice(mksv)) 746 for i := range mksv { 747 e.mapElemKey() 748 e.e.EncodeBool(mksv[i].v) 749 e.mapElemValue() 750 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 751 } 752 case reflect.String: 753 mksv := make([]stringRv, len(mks)) 754 for i, k := range mks { 755 v := &mksv[i] 756 v.r = k 757 v.v = k.String() 758 } 759 sort.Sort(stringRvSlice(mksv)) 760 for i := range mksv { 761 e.mapElemKey() 762 e.e.EncodeString(mksv[i].v) 763 e.mapElemValue() 764 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 765 } 766 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: 767 mksv := make([]uint64Rv, len(mks)) 768 for i, k := range mks { 769 v := &mksv[i] 770 v.r = k 771 v.v = k.Uint() 772 } 773 sort.Sort(uint64RvSlice(mksv)) 774 for i := range mksv { 775 e.mapElemKey() 776 e.e.EncodeUint(mksv[i].v) 777 e.mapElemValue() 778 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 779 } 780 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 781 mksv := make([]int64Rv, len(mks)) 782 for i, k := range mks { 783 v := &mksv[i] 784 v.r = k 785 v.v = k.Int() 786 } 787 sort.Sort(int64RvSlice(mksv)) 788 for i := range mksv { 789 e.mapElemKey() 790 e.e.EncodeInt(mksv[i].v) 791 e.mapElemValue() 792 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 793 } 794 case reflect.Float32: 795 mksv := make([]float64Rv, len(mks)) 796 for i, k := range mks { 797 v := &mksv[i] 798 v.r = k 799 v.v = k.Float() 800 } 801 sort.Sort(float64RvSlice(mksv)) 802 for i := range mksv { 803 e.mapElemKey() 804 e.e.EncodeFloat32(float32(mksv[i].v)) 805 e.mapElemValue() 806 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 807 } 808 case reflect.Float64: 809 mksv := make([]float64Rv, len(mks)) 810 for i, k := range mks { 811 v := &mksv[i] 812 v.r = k 813 v.v = k.Float() 814 } 815 sort.Sort(float64RvSlice(mksv)) 816 for i := range mksv { 817 e.mapElemKey() 818 e.e.EncodeFloat64(mksv[i].v) 819 e.mapElemValue() 820 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 821 } 822 case reflect.Struct: 823 if rtkey == timeTyp { 824 mksv := make([]timeRv, len(mks)) 825 for i, k := range mks { 826 v := &mksv[i] 827 v.r = k 828 v.v = rv2i(k).(time.Time) 829 } 830 sort.Sort(timeRvSlice(mksv)) 831 for i := range mksv { 832 e.mapElemKey() 833 e.e.EncodeTime(mksv[i].v) 834 e.mapElemValue() 835 e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn) 836 } 837 break 838 } 839 fallthrough 840 default: 841 // out-of-band 842 // first encode each key to a []byte first, then sort them, then record 843 bs0 := e.blist.get(len(mks) * 16) 844 mksv := bs0 845 mksbv := make([]bytesRv, len(mks)) 846 847 func() { 848 // replicate sideEncode logic 849 defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) { 850 e.wb = wb 851 e.bytes = bytes 852 e.c = c 853 e.e.restoreState(state) 854 }(e.wb, e.bytes, e.c, e.e.captureState()) 855 856 // e2 := NewEncoderBytes(&mksv, e.hh) 857 e.wb = bytesEncAppender{mksv[:0], &mksv} 858 e.bytes = true 859 e.c = 0 860 e.e.resetState() 861 862 for i, k := range mks { 863 v := &mksbv[i] 864 l := len(mksv) 865 866 e.encodeValue(k, nil) 867 e.atEndOfEncode() 868 e.w().end() 869 870 v.r = k 871 v.v = mksv[l:] 872 } 873 }() 874 875 sort.Sort(bytesRvSlice(mksbv)) 876 for j := range mksbv { 877 e.mapElemKey() 878 e.encWr.writeb(mksbv[j].v) 879 e.mapElemValue() 880 e.encodeValue(mapGet(rv, mksbv[j].r, rvv, kfast, visindirect, visref), valFn) 881 } 882 e.blist.put(mksv) 883 if !byteSliceSameData(bs0, mksv) { 884 e.blist.put(bs0) 885 } 886 } 887 } 888 889 // Encoder writes an object to an output stream in a supported format. 890 // 891 // Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used 892 // concurrently in multiple goroutines. 893 // 894 // However, as Encoder could be allocation heavy to initialize, a Reset method is provided 895 // so its state can be reused to decode new input streams repeatedly. 896 // This is the idiomatic way to use. 897 type Encoder struct { 898 panicHdl 899 900 e encDriver 901 902 h *BasicHandle 903 904 // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder 905 encWr 906 907 // ---- cpu cache line boundary 908 hh Handle 909 910 blist bytesFreelist 911 err error 912 913 // ---- cpu cache line boundary 914 915 // ---- writable fields during execution --- *try* to keep in sep cache line 916 917 // ci holds interfaces during an encoding (if CheckCircularRef=true) 918 // 919 // We considered using a []uintptr (slice of pointer addresses) retrievable via rv.UnsafeAddr. 920 // However, it is possible for the same pointer to point to 2 different types e.g. 921 // type T struct { tHelper } 922 // Here, for var v T; &v and &v.tHelper are the same pointer. 923 // Consequently, we need a tuple of type and pointer, which interface{} natively provides. 924 ci []interface{} // []uintptr 925 926 perType encPerType 927 928 slist sfiRvFreelist 929 } 930 931 // NewEncoder returns an Encoder for encoding into an io.Writer. 932 // 933 // For efficiency, Users are encouraged to configure WriterBufferSize on the handle 934 // OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer). 935 func NewEncoder(w io.Writer, h Handle) *Encoder { 936 e := h.newEncDriver().encoder() 937 if w != nil { 938 e.Reset(w) 939 } 940 return e 941 } 942 943 // NewEncoderBytes returns an encoder for encoding directly and efficiently 944 // into a byte slice, using zero-copying to temporary slices. 945 // 946 // It will potentially replace the output byte slice pointed to. 947 // After encoding, the out parameter contains the encoded contents. 948 func NewEncoderBytes(out *[]byte, h Handle) *Encoder { 949 e := h.newEncDriver().encoder() 950 if out != nil { 951 e.ResetBytes(out) 952 } 953 return e 954 } 955 956 func (e *Encoder) init(h Handle) { 957 initHandle(h) 958 e.err = errEncoderNotInitialized 959 e.bytes = true 960 e.hh = h 961 e.h = h.getBasicHandle() 962 e.be = e.hh.isBinary() 963 } 964 965 func (e *Encoder) w() *encWr { 966 return &e.encWr 967 } 968 969 func (e *Encoder) resetCommon() { 970 e.e.reset() 971 if e.ci != nil { 972 e.ci = e.ci[:0] 973 } 974 e.c = 0 975 e.calls = 0 976 e.seq = 0 977 e.err = nil 978 } 979 980 // Reset resets the Encoder with a new output stream. 981 // 982 // This accommodates using the state of the Encoder, 983 // where it has "cached" information about sub-engines. 984 func (e *Encoder) Reset(w io.Writer) { 985 e.bytes = false 986 if e.wf == nil { 987 e.wf = new(bufioEncWriter) 988 } 989 e.wf.reset(w, e.h.WriterBufferSize, &e.blist) 990 e.resetCommon() 991 } 992 993 // ResetBytes resets the Encoder with a new destination output []byte. 994 func (e *Encoder) ResetBytes(out *[]byte) { 995 e.bytes = true 996 e.wb.reset(encInBytes(out), out) 997 e.resetCommon() 998 } 999 1000 // Encode writes an object into a stream. 1001 // 1002 // Encoding can be configured via the struct tag for the fields. 1003 // The key (in the struct tags) that we look at is configurable. 1004 // 1005 // By default, we look up the "codec" key in the struct field's tags, 1006 // and fall bak to the "json" key if "codec" is absent. 1007 // That key in struct field's tag value is the key name, 1008 // followed by an optional comma and options. 1009 // 1010 // To set an option on all fields (e.g. omitempty on all fields), you 1011 // can create a field called _struct, and set flags on it. The options 1012 // which can be set on _struct are: 1013 // - omitempty: so all fields are omitted if empty 1014 // - toarray: so struct is encoded as an array 1015 // - int: so struct key names are encoded as signed integers (instead of strings) 1016 // - uint: so struct key names are encoded as unsigned integers (instead of strings) 1017 // - float: so struct key names are encoded as floats (instead of strings) 1018 // More details on these below. 1019 // 1020 // Struct values "usually" encode as maps. Each exported struct field is encoded unless: 1021 // - the field's tag is "-", OR 1022 // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option. 1023 // 1024 // When encoding as a map, the first string in the tag (before the comma) 1025 // is the map key string to use when encoding. 1026 // ... 1027 // This key is typically encoded as a string. 1028 // However, there are instances where the encoded stream has mapping keys encoded as numbers. 1029 // For example, some cbor streams have keys as integer codes in the stream, but they should map 1030 // to fields in a structured object. Consequently, a struct is the natural representation in code. 1031 // For these, configure the struct to encode/decode the keys as numbers (instead of string). 1032 // This is done with the int,uint or float option on the _struct field (see above). 1033 // 1034 // However, struct values may encode as arrays. This happens when: 1035 // - StructToArray Encode option is set, OR 1036 // - the tag on the _struct field sets the "toarray" option 1037 // Note that omitempty is ignored when encoding struct values as arrays, 1038 // as an entry must be encoded for each field, to maintain its position. 1039 // 1040 // Values with types that implement MapBySlice are encoded as stream maps. 1041 // 1042 // The empty values (for omitempty option) are false, 0, any nil pointer 1043 // or interface value, and any array, slice, map, or string of length zero. 1044 // 1045 // Anonymous fields are encoded inline except: 1046 // - the struct tag specifies a replacement name (first value) 1047 // - the field is of an interface type 1048 // 1049 // Examples: 1050 // 1051 // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below. 1052 // type MyStruct struct { 1053 // _struct bool `codec:",omitempty"` //set omitempty for every field 1054 // Field1 string `codec:"-"` //skip this field 1055 // Field2 int `codec:"myName"` //Use key "myName" in encode stream 1056 // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty. 1057 // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty. 1058 // io.Reader //use key "Reader". 1059 // MyStruct `codec:"my1" //use key "my1". 1060 // MyStruct //inline it 1061 // ... 1062 // } 1063 // 1064 // type MyStruct struct { 1065 // _struct bool `codec:",toarray"` //encode struct as an array 1066 // } 1067 // 1068 // type MyStruct struct { 1069 // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys 1070 // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1) 1071 // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2) 1072 // } 1073 // 1074 // The mode of encoding is based on the type of the value. When a value is seen: 1075 // - If a Selfer, call its CodecEncodeSelf method 1076 // - If an extension is registered for it, call that extension function 1077 // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method 1078 // - Else encode it based on its reflect.Kind 1079 // 1080 // Note that struct field names and keys in map[string]XXX will be treated as symbols. 1081 // Some formats support symbols (e.g. binc) and will properly encode the string 1082 // only once in the stream, and use a tag to refer to it thereafter. 1083 func (e *Encoder) Encode(v interface{}) (err error) { 1084 // tried to use closure, as runtime optimizes defer with no params. 1085 // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc). 1086 // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139 1087 if !debugging { 1088 defer func() { 1089 // if error occurred during encoding, return that error; 1090 // else if error occurred on end'ing (i.e. during flush), return that error. 1091 if x := recover(); x != nil { 1092 panicValToErr(e, x, &e.err) 1093 err = e.err 1094 } 1095 }() 1096 } 1097 1098 e.MustEncode(v) 1099 return 1100 } 1101 1102 // MustEncode is like Encode, but panics if unable to Encode. 1103 // 1104 // Note: This provides insight to the code location that triggered the error. 1105 func (e *Encoder) MustEncode(v interface{}) { 1106 halt.onerror(e.err) 1107 if e.hh == nil { 1108 halt.onerror(errNoFormatHandle) 1109 } 1110 1111 e.calls++ 1112 e.encode(v) 1113 e.calls-- 1114 if e.calls == 0 { 1115 e.atEndOfEncode() 1116 e.w().end() 1117 } 1118 } 1119 1120 // Release releases shared (pooled) resources. 1121 // 1122 // It is important to call Release() when done with an Encoder, so those resources 1123 // are released instantly for use by subsequently created Encoders. 1124 // 1125 // Deprecated: Release is a no-op as pooled resources are not used with an Encoder. 1126 // This method is kept for compatibility reasons only. 1127 func (e *Encoder) Release() { 1128 } 1129 1130 func (e *Encoder) encode(iv interface{}) { 1131 // MARKER: a switch with only concrete types can be optimized. 1132 // consequently, we deal with nil and interfaces outside the switch. 1133 1134 if iv == nil { 1135 e.e.EncodeNil() 1136 return 1137 } 1138 1139 rv, ok := isNil(iv) 1140 if ok { 1141 e.e.EncodeNil() 1142 return 1143 } 1144 1145 switch v := iv.(type) { 1146 // case nil: 1147 // case Selfer: 1148 case Raw: 1149 e.rawBytes(v) 1150 case reflect.Value: 1151 e.encodeValue(v, nil) 1152 1153 case string: 1154 e.e.EncodeString(v) 1155 case bool: 1156 e.e.EncodeBool(v) 1157 case int: 1158 e.e.EncodeInt(int64(v)) 1159 case int8: 1160 e.e.EncodeInt(int64(v)) 1161 case int16: 1162 e.e.EncodeInt(int64(v)) 1163 case int32: 1164 e.e.EncodeInt(int64(v)) 1165 case int64: 1166 e.e.EncodeInt(v) 1167 case uint: 1168 e.e.EncodeUint(uint64(v)) 1169 case uint8: 1170 e.e.EncodeUint(uint64(v)) 1171 case uint16: 1172 e.e.EncodeUint(uint64(v)) 1173 case uint32: 1174 e.e.EncodeUint(uint64(v)) 1175 case uint64: 1176 e.e.EncodeUint(v) 1177 case uintptr: 1178 e.e.EncodeUint(uint64(v)) 1179 case float32: 1180 e.e.EncodeFloat32(v) 1181 case float64: 1182 e.e.EncodeFloat64(v) 1183 case complex64: 1184 e.encodeComplex64(v) 1185 case complex128: 1186 e.encodeComplex128(v) 1187 case time.Time: 1188 e.e.EncodeTime(v) 1189 case []byte: 1190 e.e.EncodeStringBytesRaw(v) 1191 case *Raw: 1192 e.rawBytes(*v) 1193 case *string: 1194 e.e.EncodeString(*v) 1195 case *bool: 1196 e.e.EncodeBool(*v) 1197 case *int: 1198 e.e.EncodeInt(int64(*v)) 1199 case *int8: 1200 e.e.EncodeInt(int64(*v)) 1201 case *int16: 1202 e.e.EncodeInt(int64(*v)) 1203 case *int32: 1204 e.e.EncodeInt(int64(*v)) 1205 case *int64: 1206 e.e.EncodeInt(*v) 1207 case *uint: 1208 e.e.EncodeUint(uint64(*v)) 1209 case *uint8: 1210 e.e.EncodeUint(uint64(*v)) 1211 case *uint16: 1212 e.e.EncodeUint(uint64(*v)) 1213 case *uint32: 1214 e.e.EncodeUint(uint64(*v)) 1215 case *uint64: 1216 e.e.EncodeUint(*v) 1217 case *uintptr: 1218 e.e.EncodeUint(uint64(*v)) 1219 case *float32: 1220 e.e.EncodeFloat32(*v) 1221 case *float64: 1222 e.e.EncodeFloat64(*v) 1223 case *complex64: 1224 e.encodeComplex64(*v) 1225 case *complex128: 1226 e.encodeComplex128(*v) 1227 case *time.Time: 1228 e.e.EncodeTime(*v) 1229 case *[]byte: 1230 if *v == nil { 1231 e.e.EncodeNil() 1232 } else { 1233 e.e.EncodeStringBytesRaw(*v) 1234 } 1235 default: 1236 // we can't check non-predefined types, as they might be a Selfer or extension. 1237 if skipFastpathTypeSwitchInDirectCall || !fastpathEncodeTypeSwitch(iv, e) { 1238 e.encodeValue(rv, nil) 1239 } 1240 } 1241 } 1242 1243 // encodeValue will encode a value. 1244 // 1245 // Note that encodeValue will handle nil in the stream early, so that the 1246 // subsequent calls i.e. kXXX methods, etc do not have to handle it themselves. 1247 func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn) { 1248 // if a valid fn is passed, it MUST BE for the dereferenced type of rv 1249 1250 // MARKER: We check if value is nil here, so that the kXXX method do not have to. 1251 1252 var sptr interface{} 1253 var rvp reflect.Value 1254 var rvpValid bool 1255 TOP: 1256 switch rv.Kind() { 1257 case reflect.Ptr: 1258 if rvIsNil(rv) { 1259 e.e.EncodeNil() 1260 return 1261 } 1262 rvpValid = true 1263 rvp = rv 1264 rv = rv.Elem() 1265 goto TOP 1266 case reflect.Interface: 1267 if rvIsNil(rv) { 1268 e.e.EncodeNil() 1269 return 1270 } 1271 rvpValid = false 1272 rvp = reflect.Value{} 1273 rv = rv.Elem() 1274 goto TOP 1275 case reflect.Struct: 1276 if rvpValid && e.h.CheckCircularRef { 1277 sptr = rv2i(rvp) 1278 for _, vv := range e.ci { 1279 if eq4i(sptr, vv) { // error if sptr already seen 1280 e.errorf("circular reference found: %p, %T", sptr, sptr) 1281 } 1282 } 1283 e.ci = append(e.ci, sptr) 1284 } 1285 case reflect.Slice, reflect.Map, reflect.Chan: 1286 if rvIsNil(rv) { 1287 e.e.EncodeNil() 1288 return 1289 } 1290 case reflect.Invalid, reflect.Func: 1291 e.e.EncodeNil() 1292 return 1293 } 1294 1295 if fn == nil { 1296 fn = e.h.fn(rvType(rv)) 1297 } 1298 1299 if !fn.i.addrE { // typically, addrE = false, so check it first 1300 // keep rv same 1301 } else if rvpValid { 1302 rv = rvp 1303 } else { 1304 rv = e.addrRV(rv, fn.i.ti.rt, fn.i.ti.ptr) 1305 } 1306 fn.fe(e, &fn.i, rv) 1307 1308 if sptr != nil { // remove sptr 1309 e.ci = e.ci[:len(e.ci)-1] 1310 } 1311 } 1312 1313 // addrRV returns a addressable value which may be readonly 1314 func (e *Encoder) addrRV(rv reflect.Value, typ, ptrType reflect.Type) (rva reflect.Value) { 1315 if rv.CanAddr() { 1316 return rvAddr(rv, ptrType) 1317 } 1318 if e.h.NoAddressableReadonly { 1319 rva = reflect.New(typ) 1320 rvSetDirect(rva.Elem(), rv) 1321 return 1322 } 1323 return rvAddr(e.perType.AddressableRO(rv), ptrType) 1324 } 1325 1326 func (e *Encoder) marshalUtf8(bs []byte, fnerr error) { 1327 e.onerror(fnerr) 1328 if bs == nil { 1329 e.e.EncodeNil() 1330 } else { 1331 e.e.EncodeString(stringView(bs)) 1332 } 1333 } 1334 1335 func (e *Encoder) marshalAsis(bs []byte, fnerr error) { 1336 e.onerror(fnerr) 1337 if bs == nil { 1338 e.e.EncodeNil() 1339 } else { 1340 e.encWr.writeb(bs) // e.asis(bs) 1341 } 1342 } 1343 1344 func (e *Encoder) marshalRaw(bs []byte, fnerr error) { 1345 e.onerror(fnerr) 1346 if bs == nil { 1347 e.e.EncodeNil() 1348 } else { 1349 e.e.EncodeStringBytesRaw(bs) 1350 } 1351 } 1352 1353 func (e *Encoder) rawBytes(vv Raw) { 1354 v := []byte(vv) 1355 if !e.h.Raw { 1356 e.errorf("Raw values cannot be encoded: %v", v) 1357 } 1358 e.encWr.writeb(v) 1359 } 1360 1361 func (e *Encoder) wrapErr(v error, err *error) { 1362 *err = wrapCodecErr(v, e.hh.Name(), 0, true) 1363 } 1364 1365 // ---- container tracker methods 1366 // Note: We update the .c after calling the callback. 1367 // This way, the callback can know what the last status was. 1368 1369 func (e *Encoder) mapStart(length int) { 1370 e.e.WriteMapStart(length) 1371 e.c = containerMapStart 1372 } 1373 1374 func (e *Encoder) mapElemKey() { 1375 if e.js { 1376 e.jsondriver().WriteMapElemKey() 1377 } 1378 e.c = containerMapKey 1379 } 1380 1381 func (e *Encoder) mapElemValue() { 1382 if e.js { 1383 e.jsondriver().WriteMapElemValue() 1384 } 1385 e.c = containerMapValue 1386 } 1387 1388 func (e *Encoder) mapEnd() { 1389 e.e.WriteMapEnd() 1390 e.c = 0 1391 } 1392 1393 func (e *Encoder) arrayStart(length int) { 1394 e.e.WriteArrayStart(length) 1395 e.c = containerArrayStart 1396 } 1397 1398 func (e *Encoder) arrayElem() { 1399 if e.js { 1400 e.jsondriver().WriteArrayElem() 1401 } 1402 e.c = containerArrayElem 1403 } 1404 1405 func (e *Encoder) arrayEnd() { 1406 e.e.WriteArrayEnd() 1407 e.c = 0 1408 } 1409 1410 // ---------- 1411 1412 func (e *Encoder) haltOnMbsOddLen(length int) { 1413 if length&1 != 0 { // similar to &1==1 or %2 == 1 1414 e.errorf("mapBySlice requires even slice length, but got %v", length) 1415 } 1416 } 1417 1418 func (e *Encoder) atEndOfEncode() { 1419 // e.e.atEndOfEncode() 1420 if e.js { 1421 e.jsondriver().atEndOfEncode() 1422 } 1423 } 1424 1425 func (e *Encoder) sideEncode(v interface{}, basetype reflect.Type, bs *[]byte) { 1426 // rv := baseRV(v) 1427 // e2 := NewEncoderBytes(bs, e.hh) 1428 // e2.encodeValue(rv, e2.h.fnNoExt(basetype)) 1429 // e2.atEndOfEncode() 1430 // e2.w().end() 1431 1432 defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) { 1433 e.wb = wb 1434 e.bytes = bytes 1435 e.c = c 1436 e.e.restoreState(state) 1437 }(e.wb, e.bytes, e.c, e.e.captureState()) 1438 1439 e.wb = bytesEncAppender{encInBytes(bs)[:0], bs} 1440 e.bytes = true 1441 e.c = 0 1442 e.e.resetState() 1443 1444 // must call using fnNoExt 1445 rv := baseRV(v) 1446 e.encodeValue(rv, e.h.fnNoExt(basetype)) 1447 e.atEndOfEncode() 1448 e.w().end() 1449 } 1450 1451 func encInBytes(out *[]byte) (in []byte) { 1452 in = *out 1453 if in == nil { 1454 in = make([]byte, defEncByteBufSize) 1455 } 1456 return 1457 } 1458 1459 func encStructFieldKey(encName string, ee encDriver, w *encWr, 1460 keyType valueType, encNameAsciiAlphaNum bool, js bool) { 1461 // use if-else-if, not switch (which compiles to binary-search) 1462 // since keyType is typically valueTypeString, branch prediction is pretty good. 1463 1464 if keyType == valueTypeString { 1465 if js && encNameAsciiAlphaNum { // keyType == valueTypeString 1466 w.writeqstr(encName) 1467 } else { // keyType == valueTypeString 1468 ee.EncodeString(encName) 1469 } 1470 } else if keyType == valueTypeInt { 1471 ee.EncodeInt(must.Int(strconv.ParseInt(encName, 10, 64))) 1472 } else if keyType == valueTypeUint { 1473 ee.EncodeUint(must.Uint(strconv.ParseUint(encName, 10, 64))) 1474 } else if keyType == valueTypeFloat { 1475 ee.EncodeFloat64(must.Float(strconv.ParseFloat(encName, 64))) 1476 } else { 1477 halt.errorf("invalid struct key type: %v", keyType) 1478 } 1479 }