forked from fxamacker/cbor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
3187 lines (2778 loc) · 98.8 KB
/
decode.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 (
"encoding"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"math/big"
"reflect"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/x448/float16"
)
// Unmarshal parses the CBOR-encoded data into the value pointed to by v
// using default decoding options. If v is nil, not a pointer, or
// a nil pointer, Unmarshal returns an error.
//
// To unmarshal CBOR into a value implementing the Unmarshaler interface,
// Unmarshal calls that value's UnmarshalCBOR method with a valid
// CBOR value.
//
// To unmarshal CBOR byte string into a value implementing the
// encoding.BinaryUnmarshaler interface, Unmarshal calls that value's
// UnmarshalBinary method with decoded CBOR byte string.
//
// To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil
// if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal
// unmarshals CBOR into the value pointed to by the pointer. If the
// pointer is nil, Unmarshal creates a new value for it to point to.
//
// To unmarshal CBOR into an empty interface value, Unmarshal uses the
// following rules:
//
// CBOR booleans decode to bool.
// CBOR positive integers decode to uint64.
// CBOR negative integers decode to int64 (big.Int if value overflows).
// CBOR floating points decode to float64.
// CBOR byte strings decode to []byte.
// CBOR text strings decode to string.
// CBOR arrays decode to []interface{}.
// CBOR maps decode to map[interface{}]interface{}.
// CBOR null and undefined values decode to nil.
// CBOR times (tag 0 and 1) decode to time.Time.
// CBOR bignums (tag 2 and 3) decode to big.Int.
// CBOR tags with an unrecognized number decode to cbor.Tag
//
// To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice
// if the CBOR array is empty or slice capacity is less than CBOR array length.
// Otherwise Unmarshal overwrites existing elements, and sets slice length
// to CBOR array length.
//
// To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array
// elements into Go array elements. If the Go array is smaller than the
// CBOR array, the extra CBOR array elements are discarded. If the CBOR
// array is smaller than the Go array, the extra Go array elements are
// set to zero values.
//
// To unmarshal a CBOR array into a struct, struct must have a special field "_"
// with struct tag `cbor:",toarray"`. Go array elements are decoded into struct
// fields. Any "omitempty" struct field tag option is ignored in this case.
//
// To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the
// map is nil. Otherwise Unmarshal reuses the existing map and keeps existing
// entries. Unmarshal stores key-value pairs from the CBOR map into Go map.
// See DecOptions.DupMapKey to enable duplicate map key detection.
//
// To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the
// keys in the following priority:
//
// 1. "cbor" key in struct field tag,
// 2. "json" key in struct field tag,
// 3. struct field name.
//
// Unmarshal tries an exact match for field name, then a case-insensitive match.
// Map key-value pairs without corresponding struct fields are ignored. See
// DecOptions.ExtraReturnErrors to return error at unknown field.
//
// To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text
// string formatted in RFC3339. To unmarshal a CBOR integer/float into a
// time.Time value, Unmarshal creates an unix time with integer/float as seconds
// and fractional seconds since January 1, 1970 UTC. As a special case, Infinite
// and NaN float values decode to time.Time's zero value.
//
// To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a
// slice/map/pointer, Unmarshal sets Go value to nil. Because null is often
// used to mean "not present", unmarshalling CBOR null and undefined value
// into any other Go type has no effect and returns no error.
//
// Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time),
// and tag 2 and 3 (bignum).
//
// Unmarshal returns ExtraneousDataError error (without decoding into v)
// if there are any remaining bytes following the first valid CBOR data item.
// See UnmarshalFirst, if you want to unmarshal only the first
// CBOR data item without ExtraneousDataError caused by remaining bytes.
func Unmarshal(data []byte, v interface{}) error {
return defaultDecMode.Unmarshal(data, v)
}
// UnmarshalFirst parses the first CBOR data item into the value pointed to by v
// using default decoding options. Any remaining bytes are returned in rest.
//
// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
//
// See the documentation for Unmarshal for details.
func UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error) {
return defaultDecMode.UnmarshalFirst(data, v)
}
// Valid checks whether data is a well-formed encoded CBOR data item and
// that it complies with default restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
//
// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
//
// Deprecated: Valid is kept for compatibility and should not be used.
// Use Wellformed instead because it has a more appropriate name.
func Valid(data []byte) error {
return defaultDecMode.Valid(data)
}
// Wellformed checks whether data is a well-formed encoded CBOR data item and
// that it complies with default restrictions such as MaxNestedLevels,
// MaxArrayElements, MaxMapPairs, etc.
//
// If there are any remaining bytes after the CBOR data item,
// an ExtraneousDataError is returned.
func Wellformed(data []byte) error {
return defaultDecMode.Wellformed(data)
}
// Unmarshaler is the interface implemented by types that wish to unmarshal
// CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR
// must copy the CBOR data if it needs to use it after returning.
type Unmarshaler interface {
UnmarshalCBOR([]byte) error
}
// InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
type InvalidUnmarshalError struct {
s string
}
func (e *InvalidUnmarshalError) Error() string {
return e.s
}
// UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type.
type UnmarshalTypeError struct {
CBORType string // type of CBOR value
GoType string // type of Go value it could not be decoded into
StructFieldName string // name of the struct field holding the Go value (optional)
errorMsg string // additional error message (optional)
}
func (e *UnmarshalTypeError) Error() string {
var s string
if e.StructFieldName != "" {
s = "cbor: cannot unmarshal " + e.CBORType + " into Go struct field " + e.StructFieldName + " of type " + e.GoType
} else {
s = "cbor: cannot unmarshal " + e.CBORType + " into Go value of type " + e.GoType
}
if e.errorMsg != "" {
s += " (" + e.errorMsg + ")"
}
return s
}
// InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map.
// For example, Go doesn't allow slice as map key.
type InvalidMapKeyTypeError struct {
GoType string
}
func (e *InvalidMapKeyTypeError) Error() string {
return "cbor: invalid map key type: " + e.GoType
}
// DupMapKeyError describes detected duplicate map key in CBOR map.
type DupMapKeyError struct {
Key interface{}
Index int
}
func (e *DupMapKeyError) Error() string {
return fmt.Sprintf("cbor: found duplicate map key \"%v\" at map element index %d", e.Key, e.Index)
}
// UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.
type UnknownFieldError struct {
Index int
}
func (e *UnknownFieldError) Error() string {
return fmt.Sprintf("cbor: found unknown field at map element index %d", e.Index)
}
// UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item
// that is not acceptable to a specific CBOR-based application protocol ("invalid or unexpected" as
// described in RFC 8949 Section 5 Paragraph 3).
type UnacceptableDataItemError struct {
CBORType string
Message string
}
func (e UnacceptableDataItemError) Error() string {
return fmt.Sprintf("cbor: data item of cbor type %s is not accepted by protocol: %s", e.CBORType, e.Message)
}
// ByteStringExpectedFormatError is returned when unmarshaling CBOR byte string fails when
// using non-default ByteStringExpectedFormat decoding option that makes decoder expect
// a specified format such as base64, hex, etc.
type ByteStringExpectedFormatError struct {
expectedFormatOption ByteStringExpectedFormatMode
err error
}
func newByteStringExpectedFormatError(expectedFormatOption ByteStringExpectedFormatMode, err error) *ByteStringExpectedFormatError {
return &ByteStringExpectedFormatError{expectedFormatOption, err}
}
func (e *ByteStringExpectedFormatError) Error() string {
switch e.expectedFormatOption {
case ByteStringExpectedBase64URL:
return fmt.Sprintf("cbor: failed to decode base64url from byte string: %s", e.err)
case ByteStringExpectedBase64:
return fmt.Sprintf("cbor: failed to decode base64 from byte string: %s", e.err)
case ByteStringExpectedBase16:
return fmt.Sprintf("cbor: failed to decode hex from byte string: %s", e.err)
default:
return fmt.Sprintf("cbor: failed to decode byte string in expected format %d: %s", e.expectedFormatOption, e.err)
}
}
func (e *ByteStringExpectedFormatError) Unwrap() error {
return e.err
}
// InadmissibleTagContentTypeError is returned when unmarshaling built-in CBOR tags
// fails because of inadmissible type for tag content. Currently, the built-in
// CBOR tags in this codec are tags 0-3 and 21-23.
// See "Tag validity" in RFC 8949 Section 5.3.2.
type InadmissibleTagContentTypeError struct {
s string
tagNum int
expectedTagContentType string
gotTagContentType string
}
func newInadmissibleTagContentTypeError(
tagNum int,
expectedTagContentType string,
gotTagContentType string,
) *InadmissibleTagContentTypeError {
return &InadmissibleTagContentTypeError{
tagNum: tagNum,
expectedTagContentType: expectedTagContentType,
gotTagContentType: gotTagContentType,
}
}
func newInadmissibleTagContentTypeErrorf(s string) *InadmissibleTagContentTypeError {
return &InadmissibleTagContentTypeError{s: "cbor: " + s} //nolint:goconst // ignore "cbor"
}
func (e *InadmissibleTagContentTypeError) Error() string {
if e.s == "" {
return fmt.Sprintf(
"cbor: tag number %d must be followed by %s, got %s",
e.tagNum,
e.expectedTagContentType,
e.gotTagContentType,
)
}
return e.s
}
// DupMapKeyMode specifies how to enforce duplicate map key. Two map keys are considered duplicates if:
// 1. When decoding into a struct, both keys match the same struct field. The keys are also
// considered duplicates if neither matches any field and decoding to interface{} would produce
// equal (==) values for both keys.
// 2. When decoding into a map, both keys are equal (==) when decoded into values of the
// destination map's key type.
type DupMapKeyMode int
const (
// DupMapKeyQuiet doesn't enforce duplicate map key. Decoder quietly (no error)
// uses faster of "keep first" or "keep last" depending on Go data type and other factors.
DupMapKeyQuiet DupMapKeyMode = iota
// DupMapKeyEnforcedAPF enforces detection and rejection of duplicate map keys.
// APF means "Allow Partial Fill" and the destination map or struct can be partially filled.
// If a duplicate map key is detected, DupMapKeyError is returned without further decoding
// of the map. It's the caller's responsibility to respond to DupMapKeyError by
// discarding the partially filled result if their protocol requires it.
// WARNING: using DupMapKeyEnforcedAPF will decrease performance and increase memory use.
DupMapKeyEnforcedAPF
maxDupMapKeyMode
)
func (dmkm DupMapKeyMode) valid() bool {
return dmkm >= 0 && dmkm < maxDupMapKeyMode
}
// IndefLengthMode specifies whether to allow indefinite length items.
type IndefLengthMode int
const (
// IndefLengthAllowed allows indefinite length items.
IndefLengthAllowed IndefLengthMode = iota
// IndefLengthForbidden disallows indefinite length items.
IndefLengthForbidden
maxIndefLengthMode
)
func (m IndefLengthMode) valid() bool {
return m >= 0 && m < maxIndefLengthMode
}
// TagsMode specifies whether to allow CBOR tags.
type TagsMode int
const (
// TagsAllowed allows CBOR tags.
TagsAllowed TagsMode = iota
// TagsForbidden disallows CBOR tags.
TagsForbidden
maxTagsMode
)
func (tm TagsMode) valid() bool {
return tm >= 0 && tm < maxTagsMode
}
// IntDecMode specifies which Go type (int64, uint64, or big.Int) should
// be used when decoding CBOR integers (major type 0 and 1) to Go interface{}.
type IntDecMode int
const (
// IntDecConvertNone affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR unsigned integer (major type 0) to:
// - uint64
// It decodes CBOR negative integer (major type 1) to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
IntDecConvertNone IntDecMode = iota
// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR integers (major type 0 and 1) to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value < math.MinInt64
// - return UnmarshalTypeError if value > math.MaxInt64
// Deprecated: IntDecConvertSigned should not be used.
// Please use other options, such as IntDecConvertSignedOrError, IntDecConvertSignedOrBigInt, IntDecConvertNone.
IntDecConvertSigned
// IntDecConvertSignedOrFail affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It decodes CBOR integers (major type 0 and 1) to:
// - int64 if value fits
// - return UnmarshalTypeError if value doesn't fit into int64
IntDecConvertSignedOrFail
// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
// It makes CBOR integers (major type 0 and 1) decode to:
// - int64 if value fits
// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
IntDecConvertSignedOrBigInt
maxIntDec
)
func (idm IntDecMode) valid() bool {
return idm >= 0 && idm < maxIntDec
}
// MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2)
// as Go map key when decoding CBOR map key into an empty Go interface value.
// Specifically, this option applies when decoding CBOR map into
// - Go empty interface, or
// - Go map with empty interface as key type.
// The CBOR map key types handled by this option are
// - byte string
// - tagged byte string
// - nested tagged byte string
type MapKeyByteStringMode int
const (
// MapKeyByteStringAllowed allows CBOR byte string to be decoded as Go map key.
// Since Go doesn't allow []byte as map key, CBOR byte string is decoded to
// ByteString which has underlying string type.
// This is the default setting.
MapKeyByteStringAllowed MapKeyByteStringMode = iota
// MapKeyByteStringForbidden forbids CBOR byte string being decoded as Go map key.
// Attempting to decode CBOR byte string as map key into empty interface value
// returns a decoding error.
MapKeyByteStringForbidden
maxMapKeyByteStringMode
)
func (mkbsm MapKeyByteStringMode) valid() bool {
return mkbsm >= 0 && mkbsm < maxMapKeyByteStringMode
}
// ExtraDecErrorCond specifies extra conditions that should be treated as errors.
type ExtraDecErrorCond uint
// ExtraDecErrorNone indicates no extra error condition.
const ExtraDecErrorNone ExtraDecErrorCond = 0
const (
// ExtraDecErrorUnknownField indicates error condition when destination
// Go struct doesn't have a field matching a CBOR map key.
ExtraDecErrorUnknownField ExtraDecErrorCond = 1 << iota
maxExtraDecError
)
func (ec ExtraDecErrorCond) valid() bool {
return ec < maxExtraDecError
}
// UTF8Mode option specifies if decoder should
// decode CBOR Text containing invalid UTF-8 string.
type UTF8Mode int
const (
// UTF8RejectInvalid rejects CBOR Text containing
// invalid UTF-8 string.
UTF8RejectInvalid UTF8Mode = iota
// UTF8DecodeInvalid allows decoding CBOR Text containing
// invalid UTF-8 string.
UTF8DecodeInvalid
maxUTF8Mode
)
func (um UTF8Mode) valid() bool {
return um >= 0 && um < maxUTF8Mode
}
// FieldNameMatchingMode specifies how string keys in CBOR maps are matched to Go struct field names.
type FieldNameMatchingMode int
const (
// FieldNameMatchingPreferCaseSensitive prefers to decode map items into struct fields whose names (or tag
// names) exactly match the item's key. If there is no such field, a map item will be decoded into a field whose
// name is a case-insensitive match for the item's key.
FieldNameMatchingPreferCaseSensitive FieldNameMatchingMode = iota
// FieldNameMatchingCaseSensitive decodes map items only into a struct field whose name (or tag name) is an
// exact match for the item's key.
FieldNameMatchingCaseSensitive
maxFieldNameMatchingMode
)
func (fnmm FieldNameMatchingMode) valid() bool {
return fnmm >= 0 && fnmm < maxFieldNameMatchingMode
}
// BigIntDecMode specifies how to decode CBOR bignum to Go interface{}.
type BigIntDecMode int
const (
// BigIntDecodeValue makes CBOR bignum decode to big.Int (instead of *big.Int)
// when unmarshalling into a Go interface{}.
BigIntDecodeValue BigIntDecMode = iota
// BigIntDecodePointer makes CBOR bignum decode to *big.Int when
// unmarshalling into a Go interface{}.
BigIntDecodePointer
maxBigIntDecMode
)
func (bidm BigIntDecMode) valid() bool {
return bidm >= 0 && bidm < maxBigIntDecMode
}
// ByteStringToStringMode specifies the behavior when decoding a CBOR byte string into a Go string.
type ByteStringToStringMode int
const (
// ByteStringToStringForbidden generates an error on an attempt to decode a CBOR byte string into a Go string.
ByteStringToStringForbidden ByteStringToStringMode = iota
// ByteStringToStringAllowed permits decoding a CBOR byte string into a Go string.
ByteStringToStringAllowed
// ByteStringToStringAllowedWithExpectedLaterEncoding permits decoding a CBOR byte string
// into a Go string. Also, if the byte string is enclosed (directly or indirectly) by one of
// the "expected later encoding" tags (numbers 21 through 23), the destination string will
// be populated by applying the designated text encoding to the contents of the input byte
// string.
ByteStringToStringAllowedWithExpectedLaterEncoding
maxByteStringToStringMode
)
func (bstsm ByteStringToStringMode) valid() bool {
return bstsm >= 0 && bstsm < maxByteStringToStringMode
}
// FieldNameByteStringMode specifies the behavior when decoding a CBOR byte string map key as a Go struct field name.
type FieldNameByteStringMode int
const (
// FieldNameByteStringForbidden generates an error on an attempt to decode a CBOR byte string map key as a Go struct field name.
FieldNameByteStringForbidden FieldNameByteStringMode = iota
// FieldNameByteStringAllowed permits CBOR byte string map keys to be recognized as Go struct field names.
FieldNameByteStringAllowed
maxFieldNameByteStringMode
)
func (fnbsm FieldNameByteStringMode) valid() bool {
return fnbsm >= 0 && fnbsm < maxFieldNameByteStringMode
}
// UnrecognizedTagToAnyMode specifies how to decode unrecognized CBOR tag into an empty interface (any).
// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
type UnrecognizedTagToAnyMode int
const (
// UnrecognizedTagNumAndContentToAny decodes CBOR tag number and tag content to cbor.Tag
// when decoding unrecognized CBOR tag into an empty interface.
UnrecognizedTagNumAndContentToAny UnrecognizedTagToAnyMode = iota
// UnrecognizedTagContentToAny decodes only CBOR tag content (into its default type)
// when decoding unrecognized CBOR tag into an empty interface.
UnrecognizedTagContentToAny
maxUnrecognizedTagToAny
)
func (uttam UnrecognizedTagToAnyMode) valid() bool {
return uttam >= 0 && uttam < maxUnrecognizedTagToAny
}
// TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
type TimeTagToAnyMode int
const (
// TimeTagToTime decodes CBOR tag 0 and 1 into a time.Time value
// when decoding tag 0 or 1 into an empty interface.
TimeTagToTime TimeTagToAnyMode = iota
// TimeTagToRFC3339 decodes CBOR tag 0 and 1 into a time string in RFC3339 format
// when decoding tag 0 or 1 into an empty interface.
TimeTagToRFC3339
// TimeTagToRFC3339Nano decodes CBOR tag 0 and 1 into a time string in RFC3339Nano format
// when decoding tag 0 or 1 into an empty interface.
TimeTagToRFC3339Nano
maxTimeTagToAnyMode
)
func (tttam TimeTagToAnyMode) valid() bool {
return tttam >= 0 && tttam < maxTimeTagToAnyMode
}
// SimpleValueRegistry is a registry of unmarshaling behaviors for each possible CBOR simple value
// number (0...23 and 32...255).
type SimpleValueRegistry struct {
rejected [256]bool
}
// WithRejectedSimpleValue registers the given simple value as rejected. If the simple value is
// encountered in a CBOR input during unmarshaling, an UnacceptableDataItemError is returned.
func WithRejectedSimpleValue(sv SimpleValue) func(*SimpleValueRegistry) error {
return func(r *SimpleValueRegistry) error {
if sv >= 24 && sv <= 31 {
return fmt.Errorf("cbor: cannot set analog for reserved simple value %d", sv)
}
r.rejected[sv] = true
return nil
}
}
// Creates a new SimpleValueRegistry. The registry state is initialized by executing the provided
// functions in order against a registry that is pre-populated with the defaults for all well-formed
// simple value numbers.
func NewSimpleValueRegistryFromDefaults(fns ...func(*SimpleValueRegistry) error) (*SimpleValueRegistry, error) {
var r SimpleValueRegistry
for _, fn := range fns {
if err := fn(&r); err != nil {
return nil, err
}
}
return &r, nil
}
// NaNMode specifies how to decode floating-point values (major type 7, additional information 25
// through 27) representing NaN (not-a-number).
type NaNMode int
const (
// NaNDecodeAllowed will decode NaN values to Go float32 or float64.
NaNDecodeAllowed NaNMode = iota
// NaNDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode a NaN value.
NaNDecodeForbidden
maxNaNDecode
)
func (ndm NaNMode) valid() bool {
return ndm >= 0 && ndm < maxNaNDecode
}
// InfMode specifies how to decode floating-point values (major type 7, additional information 25
// through 27) representing positive or negative infinity.
type InfMode int
const (
// InfDecodeAllowed will decode infinite values to Go float32 or float64.
InfDecodeAllowed InfMode = iota
// InfDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode an
// infinite value.
InfDecodeForbidden
maxInfDecode
)
func (idm InfMode) valid() bool {
return idm >= 0 && idm < maxInfDecode
}
// ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
type ByteStringToTimeMode int
const (
// ByteStringToTimeForbidden generates an error on an attempt to decode a CBOR byte string into a Go time.Time.
ByteStringToTimeForbidden ByteStringToTimeMode = iota
// ByteStringToTimeAllowed permits decoding a CBOR byte string into a Go time.Time.
ByteStringToTimeAllowed
maxByteStringToTimeMode
)
func (bttm ByteStringToTimeMode) valid() bool {
return bttm >= 0 && bttm < maxByteStringToTimeMode
}
// ByteStringExpectedFormatMode specifies how to decode CBOR byte string into Go byte slice
// when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
// the CBOR byte string does not contain the expected format (e.g. base64) specified.
// For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
// in RFC 8949 Section 3.4.5.2.
type ByteStringExpectedFormatMode int
const (
// ByteStringExpectedFormatNone copies the unmodified CBOR byte string into Go byte slice
// if the byte string is not tagged by CBOR tag 21-23.
ByteStringExpectedFormatNone ByteStringExpectedFormatMode = iota
// ByteStringExpectedBase64URL expects CBOR byte strings to contain base64url-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base64url-encoded bytes into Go slice.
ByteStringExpectedBase64URL
// ByteStringExpectedBase64 expects CBOR byte strings to contain base64-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base64-encoded bytes into Go slice.
ByteStringExpectedBase64
// ByteStringExpectedBase16 expects CBOR byte strings to contain base16-encoded bytes
// if the byte string is not tagged by CBOR tag 21-23. The decoder will attempt to decode
// the base16-encoded bytes into Go slice.
ByteStringExpectedBase16
maxByteStringExpectedFormatMode
)
func (bsefm ByteStringExpectedFormatMode) valid() bool {
return bsefm >= 0 && bsefm < maxByteStringExpectedFormatMode
}
// BignumTagMode specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can be
// decoded.
type BignumTagMode int
const (
// BignumTagAllowed allows bignum tags to be decoded.
BignumTagAllowed BignumTagMode = iota
// BignumTagForbidden produces an UnacceptableDataItemError during Unmarshal if a bignum tag
// is encountered in the input.
BignumTagForbidden
maxBignumTag
)
func (btm BignumTagMode) valid() bool {
return btm >= 0 && btm < maxBignumTag
}
// BinaryUnmarshalerMode specifies how to decode into types that implement
// encoding.BinaryUnmarshaler.
type BinaryUnmarshalerMode int
const (
// BinaryUnmarshalerByteString will invoke UnmarshalBinary on the contents of a CBOR byte
// string when decoding into a value that implements BinaryUnmarshaler.
BinaryUnmarshalerByteString BinaryUnmarshalerMode = iota
// BinaryUnmarshalerNone does not recognize BinaryUnmarshaler implementations during decode.
BinaryUnmarshalerNone
maxBinaryUnmarshalerMode
)
func (bum BinaryUnmarshalerMode) valid() bool {
return bum >= 0 && bum < maxBinaryUnmarshalerMode
}
// DecOptions specifies decoding options.
type DecOptions struct {
// DupMapKey specifies whether to enforce duplicate map key.
DupMapKey DupMapKeyMode
// TimeTag specifies whether or not untagged data items, or tags other
// than tag 0 and tag 1, can be decoded to time.Time. If tag 0 or tag 1
// appears in an input, the type of its content is always validated as
// specified in RFC 8949. That behavior is not controlled by this
// option. The behavior of the supported modes are:
//
// DecTagIgnored (default): Untagged text strings and text strings
// enclosed in tags other than 0 and 1 are decoded as though enclosed
// in tag 0. Untagged unsigned integers, negative integers, and
// floating-point numbers (or those enclosed in tags other than 0 and
// 1) are decoded as though enclosed in tag 1. Decoding a tag other
// than 0 or 1 enclosing simple values null or undefined into a
// time.Time does not modify the destination value.
//
// DecTagOptional: Untagged text strings are decoded as though
// enclosed in tag 0. Untagged unsigned integers, negative integers,
// and floating-point numbers are decoded as though enclosed in tag
// 1. Tags other than 0 and 1 will produce an error on attempts to
// decode them into a time.Time.
//
// DecTagRequired: Only tags 0 and 1 can be decoded to time.Time. Any
// other input will produce an error.
TimeTag DecTagMode
// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
// Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
// require larger amounts of stack to deserialize. Don't increase this higher than you require.
MaxNestedLevels int
// MaxArrayElements specifies the max number of elements for CBOR arrays.
// Default is 128*1024=131072 and it can be set to [16, 2147483647]
MaxArrayElements int
// MaxMapPairs specifies the max number of key-value pairs for CBOR maps.
// Default is 128*1024=131072 and it can be set to [16, 2147483647]
MaxMapPairs int
// IndefLength specifies whether to allow indefinite length CBOR items.
IndefLength IndefLengthMode
// TagsMd specifies whether to allow CBOR tags (major type 6).
TagsMd TagsMode
// IntDec specifies which Go integer type (int64 or uint64) to use
// when decoding CBOR int (major type 0 and 1) to Go interface{}.
IntDec IntDecMode
// MapKeyByteString specifies how to decode CBOR byte string as map key
// when decoding CBOR map with byte string key into an empty interface value.
// By default, an error is returned when attempting to decode CBOR byte string
// as map key because Go doesn't allow []byte as map key.
MapKeyByteString MapKeyByteStringMode
// ExtraReturnErrors specifies extra conditions that should be treated as errors.
ExtraReturnErrors ExtraDecErrorCond
// DefaultMapType specifies Go map type to create and decode to
// when unmarshalling CBOR into an empty interface value.
// By default, unmarshal uses map[interface{}]interface{}.
DefaultMapType reflect.Type
// UTF8 specifies if decoder should decode CBOR Text containing invalid UTF-8.
// By default, unmarshal rejects CBOR text containing invalid UTF-8.
UTF8 UTF8Mode
// FieldNameMatching specifies how string keys in CBOR maps are matched to Go struct field names.
FieldNameMatching FieldNameMatchingMode
// BigIntDec specifies how to decode CBOR bignum to Go interface{}.
BigIntDec BigIntDecMode
// DefaultByteStringType is the Go type that should be produced when decoding a CBOR byte
// string into an empty interface value. Types to which a []byte is convertible are valid
// for this option, except for array and pointer-to-array types. If nil, the default is
// []byte.
DefaultByteStringType reflect.Type
// ByteStringToString specifies the behavior when decoding a CBOR byte string into a Go string.
ByteStringToString ByteStringToStringMode
// FieldNameByteString specifies the behavior when decoding a CBOR byte string map key as a
// Go struct field name.
FieldNameByteString FieldNameByteStringMode
// UnrecognizedTagToAny specifies how to decode unrecognized CBOR tag into an empty interface.
// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
UnrecognizedTagToAny UnrecognizedTagToAnyMode
// TimeTagToAny specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
TimeTagToAny TimeTagToAnyMode
// SimpleValues is an immutable mapping from each CBOR simple value to a corresponding
// unmarshal behavior. If nil, the simple values false, true, null, and undefined are mapped
// to the Go analog values false, true, nil, and nil, respectively, and all other simple
// values N (except the reserved simple values 24 through 31) are mapped to
// cbor.SimpleValue(N). In other words, all well-formed simple values can be decoded.
//
// Users may provide a custom SimpleValueRegistry constructed via
// NewSimpleValueRegistryFromDefaults.
SimpleValues *SimpleValueRegistry
// NaN specifies how to decode floating-point values (major type 7, additional information
// 25 through 27) representing NaN (not-a-number).
NaN NaNMode
// Inf specifies how to decode floating-point values (major type 7, additional information
// 25 through 27) representing positive or negative infinity.
Inf InfMode
// ByteStringToTime specifies how to decode CBOR byte string into Go time.Time.
ByteStringToTime ByteStringToTimeMode
// ByteStringExpectedFormat specifies how to decode CBOR byte string into Go byte slice
// when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if
// the CBOR byte string does not contain the expected format (e.g. base64) specified.
// For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
// in RFC 8949 Section 3.4.5.2.
ByteStringExpectedFormat ByteStringExpectedFormatMode
// BignumTag specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can
// be decoded. Unlike BigIntDec, this option applies to all bignum tags encountered in a
// CBOR input, independent of the type of the destination value of a particular Unmarshal
// operation.
BignumTag BignumTagMode
// BinaryUnmarshaler specifies how to decode into types that implement
// encoding.BinaryUnmarshaler.
BinaryUnmarshaler BinaryUnmarshalerMode
}
// DecMode returns DecMode with immutable options and no tags (safe for concurrency).
func (opts DecOptions) DecMode() (DecMode, error) { //nolint:gocritic // ignore hugeParam
return opts.decMode()
}
// validForTags checks that the provided tag set is compatible with these options and returns a
// non-nil error if and only if the provided tag set is incompatible.
func (opts DecOptions) validForTags(tags TagSet) error { //nolint:gocritic // ignore hugeParam
if opts.TagsMd == TagsForbidden {
return errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden")
}
if tags == nil {
return errors.New("cbor: cannot create DecMode with nil value as TagSet")
}
if opts.ByteStringToString == ByteStringToStringAllowedWithExpectedLaterEncoding ||
opts.ByteStringExpectedFormat != ByteStringExpectedFormatNone {
for _, tagNum := range []uint64{
tagNumExpectedLaterEncodingBase64URL,
tagNumExpectedLaterEncodingBase64,
tagNumExpectedLaterEncodingBase16,
} {
if rt := tags.getTypeFromTagNum([]uint64{tagNum}); rt != nil {
return fmt.Errorf("cbor: DecMode with non-default StringExpectedEncoding or ByteSliceExpectedEncoding treats tag %d as built-in and conflicts with the provided TagSet's registration of %v", tagNum, rt)
}
}
}
return nil
}
// DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).
func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
if err := opts.validForTags(tags); err != nil {
return nil, err
}
dm, err := opts.decMode()
if err != nil {
return nil, err
}
// Copy tags
ts := tagSet(make(map[reflect.Type]*tagItem))
syncTags := tags.(*syncTagSet)
syncTags.RLock()
for contentType, tag := range syncTags.t {
if tag.opts.DecTag != DecTagIgnored {
ts[contentType] = tag
}
}
syncTags.RUnlock()
if len(ts) > 0 {
dm.tags = ts
}
return dm, nil
}
// DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).
func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error) { //nolint:gocritic // ignore hugeParam
if err := opts.validForTags(tags); err != nil {
return nil, err
}
dm, err := opts.decMode()
if err != nil {
return nil, err
}
dm.tags = tags
return dm, nil
}
const (
defaultMaxArrayElements = 131072
minMaxArrayElements = 16
maxMaxArrayElements = 2147483647
defaultMaxMapPairs = 131072
minMaxMapPairs = 16
maxMaxMapPairs = 2147483647
defaultMaxNestedLevels = 32
minMaxNestedLevels = 4
maxMaxNestedLevels = 65535
)
var defaultSimpleValues = func() *SimpleValueRegistry {
registry, err := NewSimpleValueRegistryFromDefaults()
if err != nil {
panic(err)
}
return registry
}()
//nolint:gocyclo // Each option comes with some manageable boilerplate
func (opts DecOptions) decMode() (*decMode, error) { //nolint:gocritic // ignore hugeParam
if !opts.DupMapKey.valid() {
return nil, errors.New("cbor: invalid DupMapKey " + strconv.Itoa(int(opts.DupMapKey)))
}
if !opts.TimeTag.valid() {
return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag)))
}
if !opts.IndefLength.valid() {
return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength)))
}
if !opts.TagsMd.valid() {
return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd)))
}
if !opts.IntDec.valid() {
return nil, errors.New("cbor: invalid IntDec " + strconv.Itoa(int(opts.IntDec)))
}
if !opts.MapKeyByteString.valid() {
return nil, errors.New("cbor: invalid MapKeyByteString " + strconv.Itoa(int(opts.MapKeyByteString)))