-
Notifications
You must be signed in to change notification settings - Fork 60
/
encode.go
1135 lines (1001 loc) · 33.3 KB
/
encode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Faye Amacker. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
package cbor
import (
"bytes"
"encoding"
"encoding/binary"
"errors"
"io"
"math"
"reflect"
"sort"
"strconv"
"sync"
"time"
"github.com/x448/float16"
)
// Marshal returns the CBOR encoding of v using the default encoding options.
//
// Marshal uses the following type-dependent default encodings:
//
// Boolean values encode as CBOR booleans (type 7).
//
// Positive integer values encode as CBOR positive integers (type 0).
//
// Negative integer values encode as CBOR negative integers (type 1).
//
// Floating point values encode as CBOR floating points (type 7).
//
// String values encode as CBOR text strings (type 3).
//
// []byte values encode as CBOR byte strings (type 2).
//
// Array and slice values encode as CBOR arrays (type 4).
//
// Map values encode as CBOR maps (type 5).
//
// Struct values encode as CBOR maps (type 5). Each exported struct field
// becomes a pair with field name encoded as CBOR text string (type 3) and
// field value encoded based on its type.
//
// Pointer values encode as the value pointed to.
//
// Nil slice/map/pointer/interface values encode as CBOR nulls (type 7).
//
// time.Time values encode as text strings specified in RFC3339 when
// EncOptions.TimeRFC3339 is true; otherwise, time.Time values encode as
// numerical representation of seconds since January 1, 1970 UTC.
//
// If value implements the Marshaler interface, Marshal calls its MarshalCBOR
// method. If value implements encoding.BinaryMarshaler instead, Marhsal
// calls its MarshalBinary method and encode it as CBOR byte string.
//
// Marshal supports format string stored under the "cbor" key in the struct
// field's tag. CBOR format string can specify the name of the field, "omitempty"
// and "keyasint" options, and special case "-" for field omission. If "cbor"
// key is absent, Marshal uses "json" key.
//
// Struct field name is treated as integer if it has "keyasint" option in
// its format string. The format string must specify an integer as its
// field name.
//
// Special struct field "_" is used to specify struct level options, such as
// "toarray". "toarray" option enables Go struct to be encoded as CBOR array.
// "omitempty" is disabled by "toarray" to ensure that the same number
// of elements are encoded every time.
//
// Anonymous struct fields are usually marshaled as if their exported fields
// were fields in the outer struct. Marshal follows the same struct fields
// visibility rules used by JSON encoding package. An anonymous struct field
// with a name given in its CBOR tag is treated as having that name, rather
// than being anonymous. An anonymous struct field of interface type is
// treated the same as having that type as its name, rather than being anonymous.
//
// Interface values encode as the value contained in the interface. A nil
// interface value encodes as the null CBOR value.
//
// Channel, complex, and functon values cannot be encoded in CBOR. Attempting
// to encode such a value causes Marshal to return an UnsupportedTypeError.
func Marshal(v interface{}) ([]byte, error) {
return defaultEncMode.Marshal(v)
}
// Marshaler is the interface implemented by types that can marshal themselves
// into valid CBOR.
type Marshaler interface {
MarshalCBOR(EncMode) ([]byte, error)
}
// UnsupportedTypeError is returned by Marshal when attempting to encode an
// unsupported value type.
type UnsupportedTypeError struct {
Type reflect.Type
}
func (e *UnsupportedTypeError) Error() string {
return "cbor: unsupported type: " + e.Type.String()
}
// SortMode identifies supported sorting order.
type SortMode int
const (
// SortNone means no sorting.
SortNone SortMode = 0
// SortLengthFirst causes map keys or struct fields to be sorted such that:
// - If two keys have different lengths, the shorter one sorts earlier;
// - If two keys have the same length, the one with the lower value in
// (byte-wise) lexical order sorts earlier.
// It is used in "Canonical CBOR" encoding in RFC 7049 3.9.
SortLengthFirst SortMode = 1
// SortBytewiseLexical causes map keys or struct fields to be sorted in the
// bytewise lexicographic order of their deterministic CBOR encodings.
// It is used in "CTAP2 Canonical CBOR" and "Core Deterministic Encoding"
// in RFC 7049bis.
SortBytewiseLexical SortMode = 2
// SortCanonical is used in "Canonical CBOR" encoding in RFC 7049 3.9.
SortCanonical SortMode = SortLengthFirst
// SortCTAP2 is used in "CTAP2 Canonical CBOR".
SortCTAP2 SortMode = SortBytewiseLexical
// SortCoreDeterministic is used in "Core Deterministic Encoding" in RFC 7049bis.
SortCoreDeterministic SortMode = SortBytewiseLexical
maxSortMode SortMode = 3
)
func (sm SortMode) valid() bool {
return sm < maxSortMode
}
// ShortestFloatMode specifies which floating-point format should
// be used as the shortest possible format for CBOR encoding.
// It is not used for encoding Infinity and NaN values.
type ShortestFloatMode int
const (
// ShortestFloatNone makes float values encode without any conversion.
// This is the default for ShortestFloatMode in v1.
// E.g. a float32 in Go will encode to CBOR float32. And
// a float64 in Go will encode to CBOR float64.
ShortestFloatNone ShortestFloatMode = iota
// ShortestFloat16 specifies float16 as the shortest form that preserves value.
// E.g. if float64 can convert to float32 while preserving value, then
// encoding will also try to convert float32 to float16. So a float64 might
// encode as CBOR float64, float32 or float16 depending on the value.
ShortestFloat16
maxShortestFloat
)
func (sfm ShortestFloatMode) valid() bool {
return sfm < maxShortestFloat
}
// NaNConvertMode specifies how to encode NaN and overrides ShortestFloatMode.
// ShortestFloatMode is not used for encoding Infinity and NaN values.
type NaNConvertMode int
const (
// NaNConvert7e00 always encodes NaN to 0xf97e00 (CBOR float16 = 0x7e00).
NaNConvert7e00 NaNConvertMode = iota
// NaNConvertNone never modifies or converts NaN to other representations
// (float64 NaN stays float64, etc. even if it can use float16 without losing
// any bits).
NaNConvertNone
// NaNConvertPreserveSignal converts NaN to the smallest form that preserves
// value (quiet bit + payload) as described in RFC 7049bis Draft 12.
NaNConvertPreserveSignal
// NaNConvertQuiet always forces quiet bit = 1 and shortest form that preserves
// NaN payload.
NaNConvertQuiet
maxNaNConvert
)
func (ncm NaNConvertMode) valid() bool {
return ncm < maxNaNConvert
}
// InfConvertMode specifies how to encode Infinity and overrides ShortestFloatMode.
// ShortestFloatMode is not used for encoding Infinity and NaN values.
type InfConvertMode int
const (
// InfConvertFloat16 always converts Inf to lossless IEEE binary16 (float16).
InfConvertFloat16 InfConvertMode = iota
// InfConvertNone never converts (used by CTAP2 Canonical CBOR).
InfConvertNone
maxInfConvert
)
func (icm InfConvertMode) valid() bool {
return icm < maxInfConvert
}
// TimeMode specifies how to encode time.Time values.
type TimeMode int
const (
// TimeUnix causes time.Time to be encoded as epoch time in integer with second precision.
TimeUnix TimeMode = iota
// TimeUnixMicro causes time.Time to be encoded as epoch time in float-point rounded to microsecond precision.
TimeUnixMicro
// TimeUnixDynamic causes time.Time to be encoded as integer if time.Time doesn't have fractional seconds,
// otherwise float-point rounded to microsecond precision.
TimeUnixDynamic
// TimeRFC3339 causes time.Time to be encoded as RFC3339 formatted string with second precision.
TimeRFC3339
// TimeRFC3339Nano causes time.Time to be encoded as RFC3339 formatted string with nanosecond precision.
TimeRFC3339Nano
maxTimeMode
)
func (tm TimeMode) valid() bool {
return tm < maxTimeMode
}
// EncOptions specifies encoding options.
type EncOptions struct {
// Sort specifies sorting order.
Sort SortMode
// ShortestFloat specifies the shortest floating-point encoding that preserves
// the value being encoded.
ShortestFloat ShortestFloatMode
// NaNConvert specifies how to encode NaN and it overrides ShortestFloatMode.
NaNConvert NaNConvertMode
// InfConvert specifies how to encode Inf and it overrides ShortestFloatMode.
InfConvert InfConvertMode
// Time specifies how to encode time.Time.
Time TimeMode
disableIndefiniteLength bool
}
// CanonicalEncOptions returns EncOptions for "Canonical CBOR" encoding,
// defined in RFC 7049 Section 3.9 with the following rules:
//
// 1. "Integers must be as small as possible."
// 2. "The expression of lengths in major types 2 through 5 must be as short as possible."
// 3. The keys in every map must be sorted in length-first sorting order.
// See SortLengthFirst for details.
// 4. "Indefinite-length items must be made into definite-length items."
// 5. "If a protocol allows for IEEE floats, then additional canonicalization rules might
// need to be added. One example rule might be to have all floats start as a 64-bit
// float, then do a test conversion to a 32-bit float; if the result is the same numeric
// value, use the shorter value and repeat the process with a test conversion to a
// 16-bit float. (This rule selects 16-bit float for positive and negative Infinity
// as well.) Also, there are many representations for NaN. If NaN is an allowed value,
// it must always be represented as 0xf97e00."
//
func CanonicalEncOptions() EncOptions {
return EncOptions{
Sort: SortCanonical,
ShortestFloat: ShortestFloat16,
NaNConvert: NaNConvert7e00,
InfConvert: InfConvertFloat16,
disableIndefiniteLength: true,
}
}
// CTAP2EncOptions returns EncOptions for "CTAP2 Canonical CBOR" encoding,
// defined in CTAP specification, with the following rules:
//
// 1. "Integers must be encoded as small as possible."
// 2. "The representations of any floating-point values are not changed."
// 3. "The expression of lengths in major types 2 through 5 must be as short as possible."
// 4. "Indefinite-length items must be made into definite-length items.""
// 5. The keys in every map must be sorted in bytewise lexicographic order.
// See SortBytewiseLexical for details.
// 6. "Tags as defined in Section 2.4 in [RFC7049] MUST NOT be present."
//
func CTAP2EncOptions() EncOptions {
return EncOptions{
Sort: SortCTAP2,
ShortestFloat: ShortestFloatNone,
NaNConvert: NaNConvertNone,
InfConvert: InfConvertNone,
disableIndefiniteLength: true,
}
}
// CoreDetEncOptions returns EncOptions for "Core Deterministic" encoding,
// defined in RFC 7049bis with the following rules:
//
// 1. "Preferred serialization MUST be used. In particular, this means that arguments
// (see Section 3) for integers, lengths in major types 2 through 5, and tags MUST
// be as short as possible"
// "Floating point values also MUST use the shortest form that preserves the value"
// 2. "Indefinite-length items MUST NOT appear."
// 3. "The keys in every map MUST be sorted in the bytewise lexicographic order of
// their deterministic encodings."
//
func CoreDetEncOptions() EncOptions {
return EncOptions{
Sort: SortCoreDeterministic,
ShortestFloat: ShortestFloat16,
NaNConvert: NaNConvert7e00,
InfConvert: InfConvertFloat16,
disableIndefiniteLength: true,
}
}
// PreferredUnsortedEncOptions returns EncOptions for "Preferred Serialization" encoding,
// defined in RFC 7049bis with the following rules:
//
// 1. "The preferred serialization always uses the shortest form of representing the argument
// (Section 3);"
// 2. "it also uses the shortest floating-point encoding that preserves the value being
// encoded (see Section 5.5)."
// "The preferred encoding for a floating-point value is the shortest floating-point encoding
// that preserves its value, e.g., 0xf94580 for the number 5.5, and 0xfa45ad9c00 for the
// number 5555.5, unless the CBOR-based protocol specifically excludes the use of the shorter
// floating-point encodings. For NaN values, a shorter encoding is preferred if zero-padding
// the shorter significand towards the right reconstitutes the original NaN value (for many
// applications, the single NaN encoding 0xf97e00 will suffice)."
// 3. "Definite length encoding is preferred whenever the length is known at the time the
// serialization of the item starts."
//
func PreferredUnsortedEncOptions() EncOptions {
return EncOptions{
Sort: SortNone,
ShortestFloat: ShortestFloat16,
NaNConvert: NaNConvert7e00,
InfConvert: InfConvertFloat16,
}
}
// EncMode returns an EncMode interface from EncOptions.
func (opts EncOptions) EncMode() (EncMode, error) {
if !opts.Sort.valid() {
return nil, errors.New("cbor: invalid SortMode " + strconv.Itoa(int(opts.Sort)))
}
if !opts.ShortestFloat.valid() {
return nil, errors.New("cbor: invalid ShortestFloatMode " + strconv.Itoa(int(opts.ShortestFloat)))
}
if !opts.NaNConvert.valid() {
return nil, errors.New("cbor: invalid NaNConvertMode " + strconv.Itoa(int(opts.NaNConvert)))
}
if !opts.InfConvert.valid() {
return nil, errors.New("cbor: invalid InfConvertMode " + strconv.Itoa(int(opts.InfConvert)))
}
if !opts.Time.valid() {
return nil, errors.New("cbor: invalid TimeMode " + strconv.Itoa(int(opts.Time)))
}
em := encMode{
sort: opts.Sort,
shortestFloat: opts.ShortestFloat,
nanConvert: opts.NaNConvert,
infConvert: opts.InfConvert,
time: opts.Time,
disableIndefiniteLength: opts.disableIndefiniteLength,
}
return &em, nil
}
// EncMode is the main interface for CBOR encoding.
type EncMode interface {
Marshal(v interface{}) ([]byte, error)
NewEncoder(w io.Writer) *Encoder
EncOptions() EncOptions
}
type encMode struct {
sort SortMode
shortestFloat ShortestFloatMode
nanConvert NaNConvertMode
infConvert InfConvertMode
time TimeMode
disableIndefiniteLength bool
}
var defaultEncMode = &encMode{}
// EncOptions returns user specified options used to create this EncMode.
func (em *encMode) EncOptions() EncOptions {
return EncOptions{
Sort: em.sort,
ShortestFloat: em.shortestFloat,
NaNConvert: em.nanConvert,
InfConvert: em.infConvert,
Time: em.time,
disableIndefiniteLength: em.disableIndefiniteLength,
}
}
// Marshal returns the CBOR encoding of v using em EncMode.
//
// See the documentation for Marshal for details.
func (em *encMode) Marshal(v interface{}) ([]byte, error) {
e := getEncodeState()
_, err := encode(e, em, reflect.ValueOf(v))
if err != nil {
putEncodeState(e)
return nil, err
}
buf := make([]byte, e.Len())
copy(buf, e.Bytes())
putEncodeState(e)
return buf, nil
}
// NewEncoder returns a new encoder that writes to w using em EncMode.
func (em *encMode) NewEncoder(w io.Writer) *Encoder {
return &Encoder{w: w, em: em, e: getEncodeState()}
}
// An encodeState encodes CBOR into a bytes.Buffer.
type encodeState struct {
bytes.Buffer
scratch [16]byte
}
// encodeStatePool caches unused encodeState objects for later reuse.
var encodeStatePool = sync.Pool{
New: func() interface{} {
e := new(encodeState)
e.Grow(32) // TODO: make this configurable
return e
},
}
func getEncodeState() *encodeState {
return encodeStatePool.Get().(*encodeState)
}
// putEncodeState returns e to encodeStatePool.
func putEncodeState(e *encodeState) {
e.Reset()
encodeStatePool.Put(e)
}
type encodeFunc func(e *encodeState, em *encMode, v reflect.Value) (int, error)
var (
cborFalse = []byte{0xf4}
cborTrue = []byte{0xf5}
cborNil = []byte{0xf6}
cborNaN = []byte{0xf9, 0x7e, 0x00}
cborPositiveInfinity = []byte{0xf9, 0x7c, 0x00}
cborNegativeInfinity = []byte{0xf9, 0xfc, 0x00}
)
func encode(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if !v.IsValid() {
// v is zero value
e.Write(cborNil)
return 1, nil
}
f := getEncodeFunc(v.Type())
if f == nil {
return 0, &UnsupportedTypeError{v.Type()}
}
return f(e, em, v)
}
func encodeBool(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if v.Bool() {
return e.Write(cborTrue)
}
return e.Write(cborFalse)
}
func encodeInt(e *encodeState, em *encMode, v reflect.Value) (int, error) {
i := v.Int()
if i >= 0 {
return encodeHead(e, byte(cborTypePositiveInt), uint64(i)), nil
}
n := v.Int()*(-1) - 1
return encodeHead(e, byte(cborTypeNegativeInt), uint64(n)), nil
}
func encodeUint(e *encodeState, em *encMode, v reflect.Value) (int, error) {
return encodeHead(e, byte(cborTypePositiveInt), v.Uint()), nil
}
func encodeFloat(e *encodeState, em *encMode, v reflect.Value) (int, error) {
f64 := v.Float()
if math.IsNaN(f64) {
return encodeNaN(e, em, v)
}
if math.IsInf(f64, 0) {
return encodeInf(e, em, v)
}
fopt := em.shortestFloat
if v.Kind() == reflect.Float64 && (fopt == ShortestFloatNone || cannotFitFloat32(f64)) {
// Encode float64
// Don't use encodeFloat64() because it cannot be inlined.
e.scratch[0] = byte(cborTypePrimitives) | byte(27)
binary.BigEndian.PutUint64(e.scratch[1:], math.Float64bits(f64))
return e.Write(e.scratch[:9])
}
f32 := float32(f64)
if fopt == ShortestFloat16 {
var f16 float16.Float16
p := float16.PrecisionFromfloat32(f32)
if p == float16.PrecisionExact {
// Roundtrip float32->float16->float32 test isn't needed.
f16 = float16.Fromfloat32(f32)
} else if p == float16.PrecisionUnknown {
// Try roundtrip float32->float16->float32 to determine if float32 can fit into float16.
f16 = float16.Fromfloat32(f32)
if f16.Float32() == f32 {
p = float16.PrecisionExact
}
}
if p == float16.PrecisionExact {
// Encode float16
// Don't use encodeFloat16() because it cannot be inlined.
e.scratch[0] = byte(cborTypePrimitives) | byte(25)
binary.BigEndian.PutUint16(e.scratch[1:], uint16(f16))
return e.Write(e.scratch[:3])
}
}
// Encode float32
// Don't use encodeFloat32() because it cannot be inlined.
e.scratch[0] = byte(cborTypePrimitives) | byte(26)
binary.BigEndian.PutUint32(e.scratch[1:], math.Float32bits(f32))
return e.Write(e.scratch[:5])
}
func encodeInf(e *encodeState, em *encMode, v reflect.Value) (int, error) {
f64 := v.Float()
if em.infConvert == InfConvertFloat16 {
if f64 > 0 {
return e.Write(cborPositiveInfinity)
}
return e.Write(cborNegativeInfinity)
}
if v.Kind() == reflect.Float64 {
return encodeFloat64(e, f64)
}
return encodeFloat32(e, float32(f64))
}
func encodeNaN(e *encodeState, em *encMode, v reflect.Value) (int, error) {
switch em.nanConvert {
case NaNConvert7e00:
return e.Write(cborNaN)
case NaNConvertNone:
if v.Kind() == reflect.Float64 {
return encodeFloat64(e, v.Float())
}
f32 := float32NaNFromReflectValue(v)
return encodeFloat32(e, f32)
default: // NaNConvertPreserveSignal, NaNConvertQuiet
if v.Kind() == reflect.Float64 {
f64 := v.Float()
f64bits := math.Float64bits(f64)
if em.nanConvert == NaNConvertQuiet && f64bits&(1<<51) == 0 {
f64bits |= 1 << 51 // Set quiet bit = 1
f64 = math.Float64frombits(f64bits)
}
// The lower 29 bits are dropped when converting from float64 to float32.
if f64bits&0x1fffffff != 0 {
// Encode NaN as float64 because dropped coef bits from float64 to float32 are not all 0s.
return encodeFloat64(e, f64)
}
// Create float32 from float64 manually because float32(f64) always turns on NaN's quiet bits.
sign := uint32(f64bits>>32) & (1 << 31)
exp := uint32(0x7f800000)
coef := uint32((f64bits & 0xfffffffffffff) >> 29)
f32bits := sign | exp | coef
f32 := math.Float32frombits(f32bits)
// The lower 13 bits are dropped when converting from float32 to float16.
if f32bits&0x1fff != 0 {
// Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s.
return encodeFloat32(e, f32)
}
// Encode NaN as float16
f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN.
return encodeFloat16(e, f16)
}
f32 := float32NaNFromReflectValue(v)
f32bits := math.Float32bits(f32)
if em.nanConvert == NaNConvertQuiet && f32bits&(1<<22) == 0 {
f32bits |= 1 << 22 // Set quiet bit = 1
f32 = math.Float32frombits(f32bits)
}
// The lower 13 bits are dropped coef bits when converting from float32 to float16.
if f32bits&0x1fff != 0 {
// Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s.
return encodeFloat32(e, f32)
}
f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN.
return encodeFloat16(e, f16)
}
}
func encodeFloat16(e *encodeState, f16 float16.Float16) (int, error) {
e.scratch[0] = byte(cborTypePrimitives) | byte(25)
binary.BigEndian.PutUint16(e.scratch[1:], uint16(f16))
return e.Write(e.scratch[:3])
}
func encodeFloat32(e *encodeState, f32 float32) (int, error) {
e.scratch[0] = byte(cborTypePrimitives) | byte(26)
binary.BigEndian.PutUint32(e.scratch[1:], math.Float32bits(f32))
return e.Write(e.scratch[:5])
}
func encodeFloat64(e *encodeState, f64 float64) (int, error) {
e.scratch[0] = byte(cborTypePrimitives) | byte(27)
binary.BigEndian.PutUint64(e.scratch[1:], math.Float64bits(f64))
return e.Write(e.scratch[:9])
}
func encodeByteString(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if v.Kind() == reflect.Slice && v.IsNil() {
return e.Write(cborNil)
}
slen := v.Len()
if slen == 0 {
return 1, e.WriteByte(byte(cborTypeByteString))
}
n1 := encodeHead(e, byte(cborTypeByteString), uint64(slen))
if v.Kind() == reflect.Array {
for i := 0; i < slen; i++ {
e.WriteByte(byte(v.Index(i).Uint()))
}
return n1 + slen, nil
}
n2, _ := e.Write(v.Bytes())
return n1 + n2, nil
}
func encodeString(e *encodeState, em *encMode, v reflect.Value) (int, error) {
s := v.String()
n1 := encodeHead(e, byte(cborTypeTextString), uint64(len(s)))
n2, _ := e.WriteString(s)
return n1 + n2, nil
}
type arrayEncoder struct {
f encodeFunc
}
func (ae arrayEncoder) encodeArray(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if ae.f == nil {
return 0, &UnsupportedTypeError{v.Type()}
}
if v.Kind() == reflect.Slice && v.IsNil() {
return e.Write(cborNil)
}
alen := v.Len()
if alen == 0 {
return 1, e.WriteByte(byte(cborTypeArray))
}
n := encodeHead(e, byte(cborTypeArray), uint64(alen))
for i := 0; i < alen; i++ {
n1, err := ae.f(e, em, v.Index(i))
if err != nil {
return 0, err
}
n += n1
}
return n, nil
}
type mapEncoder struct {
kf, ef encodeFunc
}
func (me mapEncoder) encodeMap(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if em.sort != SortNone {
return me.encodeMapCanonical(e, em, v)
}
if me.kf == nil || me.ef == nil {
return 0, &UnsupportedTypeError{v.Type()}
}
if v.IsNil() {
return e.Write(cborNil)
}
mlen := v.Len()
if mlen == 0 {
return 1, e.WriteByte(byte(cborTypeMap))
}
n := encodeHead(e, byte(cborTypeMap), uint64(mlen))
iter := v.MapRange()
for iter.Next() {
n1, err := me.kf(e, em, iter.Key())
if err != nil {
return 0, err
}
n2, err := me.ef(e, em, iter.Value())
if err != nil {
return 0, err
}
n += n1 + n2
}
return n, nil
}
type keyValue struct {
keyCBORData, keyValueCBORData []byte
keyLen, keyValueLen int
}
type bytewiseKeyValueSorter struct {
kvs []keyValue
}
func (x *bytewiseKeyValueSorter) Len() int {
return len(x.kvs)
}
func (x *bytewiseKeyValueSorter) Swap(i, j int) {
x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i]
}
func (x *bytewiseKeyValueSorter) Less(i, j int) bool {
return bytes.Compare(x.kvs[i].keyCBORData, x.kvs[j].keyCBORData) <= 0
}
type lengthFirstKeyValueSorter struct {
kvs []keyValue
}
func (x *lengthFirstKeyValueSorter) Len() int {
return len(x.kvs)
}
func (x *lengthFirstKeyValueSorter) Swap(i, j int) {
x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i]
}
func (x *lengthFirstKeyValueSorter) Less(i, j int) bool {
if len(x.kvs[i].keyCBORData) != len(x.kvs[j].keyCBORData) {
return len(x.kvs[i].keyCBORData) < len(x.kvs[j].keyCBORData)
}
return bytes.Compare(x.kvs[i].keyCBORData, x.kvs[j].keyCBORData) <= 0
}
var keyValuePool = sync.Pool{}
func getKeyValues(length int) *[]keyValue {
v := keyValuePool.Get()
if v == nil {
y := make([]keyValue, length)
return &y
}
x := v.(*[]keyValue)
if cap(*x) >= length {
*x = (*x)[:length]
return x
}
// []keyValue from the pool does not have enough capacity.
// Return it back to the pool and create a new one.
keyValuePool.Put(x)
y := make([]keyValue, length)
return &y
}
func putKeyValues(x *[]keyValue) {
*x = (*x)[:0]
keyValuePool.Put(x)
}
func (me mapEncoder) encodeMapCanonical(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if me.kf == nil || me.ef == nil {
return 0, &UnsupportedTypeError{v.Type()}
}
if v.IsNil() {
return e.Write(cborNil)
}
if v.Len() == 0 {
return 1, e.WriteByte(byte(cborTypeMap))
}
kve := getEncodeState() // accumulated cbor encoded key-values
kvsp := getKeyValues(v.Len()) // for sorting keys
kvs := *kvsp
iter := v.MapRange()
for i := 0; iter.Next(); i++ {
n1, err := me.kf(kve, em, iter.Key())
if err != nil {
putEncodeState(kve)
putKeyValues(kvsp)
return 0, err
}
n2, err := me.ef(kve, em, iter.Value())
if err != nil {
putEncodeState(kve)
putKeyValues(kvsp)
return 0, err
}
// Save key and keyvalue length to create slice later.
kvs[i] = keyValue{keyLen: n1, keyValueLen: n1 + n2}
}
b := kve.Bytes()
for i, off := 0, 0; i < len(kvs); i++ {
kvs[i].keyCBORData = b[off : off+kvs[i].keyLen]
kvs[i].keyValueCBORData = b[off : off+kvs[i].keyValueLen]
off += kvs[i].keyValueLen
}
if em.sort == SortBytewiseLexical {
sort.Sort(&bytewiseKeyValueSorter{kvs})
} else {
sort.Sort(&lengthFirstKeyValueSorter{kvs})
}
n := encodeHead(e, byte(cborTypeMap), uint64(len(kvs)))
for i := 0; i < len(kvs); i++ {
n1, _ := e.Write(kvs[i].keyValueCBORData)
n += n1
}
putEncodeState(kve)
putKeyValues(kvsp)
return n, nil
}
func encodeStructToArray(e *encodeState, em *encMode, v reflect.Value, flds fields) (int, error) {
n := encodeHead(e, byte(cborTypeArray), uint64(len(flds)))
FieldLoop:
for i := 0; i < len(flds); i++ {
fv := v
for k, n := range flds[i].idx {
if k > 0 {
if fv.Kind() == reflect.Ptr && fv.Type().Elem().Kind() == reflect.Struct {
if fv.IsNil() {
// Write nil for null pointer to embedded struct
e.Write(cborNil)
continue FieldLoop
}
fv = fv.Elem()
}
}
fv = fv.Field(n)
}
n1, err := flds[i].ef(e, em, fv)
if err != nil {
return 0, err
}
n += n1
}
return n, nil
}
func encodeFixedLengthStruct(e *encodeState, em *encMode, v reflect.Value, flds fields) (int, error) {
n := encodeHead(e, byte(cborTypeMap), uint64(len(flds)))
for i := 0; i < len(flds); i++ {
n1, _ := e.Write(flds[i].cborName)
fv := v.Field(flds[i].idx[0])
n2, err := flds[i].ef(e, em, fv)
if err != nil {
return 0, err
}
n += n1 + n2
}
return n, nil
}
func encodeStruct(e *encodeState, em *encMode, v reflect.Value) (int, error) {
structType := getEncodingStructType(v.Type())
if structType.err != nil {
return 0, structType.err
}
if structType.toArray {
return encodeStructToArray(e, em, v, structType.fields)
}
flds := structType.getFields(em)
if !structType.hasAnonymousField && !structType.omitEmpty {
return encodeFixedLengthStruct(e, em, v, flds)
}
kve := getEncodeState() // encode key-value pairs based on struct field tag options
kvcount := 0
FieldLoop:
for i := 0; i < len(flds); i++ {
fv := v
for k, n := range flds[i].idx {
if k > 0 {
if fv.Kind() == reflect.Ptr && fv.Type().Elem().Kind() == reflect.Struct {
if fv.IsNil() {
// Null pointer to embedded struct
continue FieldLoop
}
fv = fv.Elem()
}
}
fv = fv.Field(n)
}
if flds[i].omitEmpty && isEmptyValue(fv) {
continue
}
kve.Write(flds[i].cborName)
if _, err := flds[i].ef(kve, em, fv); err != nil {
putEncodeState(kve)
return 0, err
}
kvcount++
}
n1 := encodeHead(e, byte(cborTypeMap), uint64(kvcount))
n2, err := e.Write(kve.Bytes())
putEncodeState(kve)
return n1 + n2, err
}
func encodeIntf(e *encodeState, em *encMode, v reflect.Value) (int, error) {
if v.IsNil() {
return e.Write(cborNil)
}
return encode(e, em, v.Elem())
}
func encodeTime(e *encodeState, em *encMode, v reflect.Value) (int, error) {
t := v.Interface().(time.Time)
if t.IsZero() {
return e.Write(cborNil)
}
switch em.time {
case TimeUnix:
secs := t.Unix()
return encodeInt(e, em, reflect.ValueOf(secs))
case TimeUnixMicro:
t = t.UTC().Round(time.Microsecond)
f := float64(t.UnixNano()) / 1e9
return encodeFloat(e, em, reflect.ValueOf(f))
case TimeUnixDynamic:
t = t.UTC().Round(time.Microsecond)
secs, nsecs := t.Unix(), uint64(t.Nanosecond())
if nsecs == 0 {
return encodeInt(e, em, reflect.ValueOf(secs))
}
f := float64(secs) + float64(nsecs)/1e9
return encodeFloat(e, em, reflect.ValueOf(f))
case TimeRFC3339:
s := t.Format(time.RFC3339)
return encodeString(e, em, reflect.ValueOf(s))
default: // TimeRFC3339Nano:
s := t.Format(time.RFC3339Nano)
return encodeString(e, em, reflect.ValueOf(s))
}
}
func encodeBinaryMarshalerType(e *encodeState, em *encMode, v reflect.Value) (int, error) {
m, ok := v.Interface().(encoding.BinaryMarshaler)
if !ok {
pv := reflect.New(v.Type())
pv.Elem().Set(v)
m = pv.Interface().(encoding.BinaryMarshaler)
}
data, err := m.MarshalBinary()
if err != nil {
return 0, err
}
n1 := encodeHead(e, byte(cborTypeByteString), uint64(len(data)))
n2, _ := e.Write(data)
return n1 + n2, nil
}
func encodeMarshalerType(e *encodeState, em *encMode, v reflect.Value) (int, error) {
m, ok := v.Interface().(Marshaler)