diff options
Diffstat (limited to 'vendor/github.com/fxamacker/cbor')
18 files changed, 5787 insertions, 0 deletions
diff --git a/vendor/github.com/fxamacker/cbor/v2/.gitignore b/vendor/github.com/fxamacker/cbor/v2/.gitignore new file mode 100644 index 0000000000..f1c181ec9c --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/.gitignore @@ -0,0 +1,12 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out diff --git a/vendor/github.com/fxamacker/cbor/v2/.golangci.yml b/vendor/github.com/fxamacker/cbor/v2/.golangci.yml new file mode 100644 index 0000000000..0448042649 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/.golangci.yml @@ -0,0 +1,86 @@ +# Do not delete linter settings. Linters like gocritic can be enabled on the command line. + +linters-settings: + dupl: + threshold: 100 + funlen: + lines: 100 + statements: 50 + goconst: + min-len: 2 + min-occurrences: 3 + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + disabled-checks: + - dupImport # https://github.com/go-critic/go-critic/issues/845 + - ifElseChain + - octalLiteral + - paramTypeCombine + - whyNoLint + - wrapperFunc + gofmt: + simplify: false + goimports: + local-prefixes: github.com/fxamacker/cbor + golint: + min-confidence: 0 + govet: + check-shadowing: true + lll: + line-length: 140 + maligned: + suggest-new: true + misspell: + locale: US + +linters: + disable-all: true + enable: + - deadcode + - errcheck + - goconst + - gocyclo + - gofmt + - goimports + - golint + - gosec + - govet + - ineffassign + - maligned + - misspell + - staticcheck + - structcheck + - typecheck + - unconvert + - unused + - varcheck + + +issues: + # max-issues-per-linter default is 50. Set to 0 to disable limit. + max-issues-per-linter: 0 + # max-same-issues default is 3. Set to 0 to disable limit. + max-same-issues: 0 + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + - path: _test\.go + linters: + - goconst + - dupl + - gomnd + - lll + - path: doc\.go + linters: + - goimports + - gomnd + - lll + +# golangci.com configuration +# https://github.com/golangci/golangci/wiki/Configuration +service: + golangci-lint-version: 1.23.x # use the fixed version to not introduce new linters unexpectedly diff --git a/vendor/github.com/fxamacker/cbor/v2/CBOR_BENCHMARKS.md b/vendor/github.com/fxamacker/cbor/v2/CBOR_BENCHMARKS.md new file mode 100644 index 0000000000..d4ea18990c --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/CBOR_BENCHMARKS.md @@ -0,0 +1,264 @@ +# CBOR Benchmarks for fxamacker/cbor + +See [bench_test.go](bench_test.go). + +Benchmarks on Feb. 22, 2020 with cbor v2.2.0: +* [Go builtin types](#go-builtin-types) +* [Go structs](#go-structs) +* [Go structs with "keyasint" struct tag](#go-structs-with-keyasint-struct-tag) +* [Go structs with "toarray" struct tag](#go-structs-with-toarray-struct-tag) +* [COSE data](#cose-data) +* [CWT claims data](#cwt-claims-data) +* [SenML data](#SenML-data) + +## Go builtin types + +Benchmarks use data representing the following values: + +* Boolean: `true` +* Positive integer: `18446744073709551615` +* Negative integer: `-1000` +* Float: `-4.1` +* Byte string: `h'0102030405060708090a0b0c0d0e0f101112131415161718191a'` +* Text string: `"The quick brown fox jumps over the lazy dog"` +* Array: `[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]` +* Map: `{"a": "A", "b": "B", "c": "C", "d": "D", "e": "E", "f": "F", "g": "G", "h": "H", "i": "I", "j": "J", "l": "L", "m": "M", "n": "N"}}` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshal/CBOR_bool_to_Go_interface_{}-2 | 110 ns/op | 16 B/op | 1 allocs/op +BenchmarkUnmarshal/CBOR_bool_to_Go_bool-2 | 99.3 ns/op | 1 B/op | 1 allocs/op +BenchmarkUnmarshal/CBOR_positive_int_to_Go_interface_{}-2 | 135 ns/op | 24 B/op | 2 allocs/op +BenchmarkUnmarshal/CBOR_positive_int_to_Go_uint64-2 | 116 ns/op | 8 B/op | 1 allocs/op +BenchmarkUnmarshal/CBOR_negative_int_to_Go_interface_{}-2 | 133 ns/op | 24 B/op | 2 allocs/op +BenchmarkUnmarshal/CBOR_negative_int_to_Go_int64-2 | 113 ns/op | 8 B/op | 1 allocs/op +BenchmarkUnmarshal/CBOR_float_to_Go_interface_{}-2 | 137 ns/op | 24 B/op | 2 allocs/op +BenchmarkUnmarshal/CBOR_float_to_Go_float64-2 | 115 ns/op | 8 B/op | 1 allocs/op +BenchmarkUnmarshal/CBOR_bytes_to_Go_interface_{}-2 | 179 ns/op | 80 B/op | 3 allocs/op +BenchmarkUnmarshal/CBOR_bytes_to_Go_[]uint8-2 | 194 ns/op | 64 B/op | 2 allocs/op +BenchmarkUnmarshal/CBOR_text_to_Go_interface_{}-2 | 209 ns/op | 80 B/op | 3 allocs/op +BenchmarkUnmarshal/CBOR_text_to_Go_string-2 | 193 ns/op | 64 B/op | 2 allocs/op +BenchmarkUnmarshal/CBOR_array_to_Go_interface_{}-2 |1068 ns/op | 672 B/op | 29 allocs/op +BenchmarkUnmarshal/CBOR_array_to_Go_[]int-2 | 1073 ns/op | 272 B/op | 3 allocs/op +BenchmarkUnmarshal/CBOR_map_to_Go_interface_{}-2 | 2926 ns/op | 1420 B/op | 30 allocs/op +BenchmarkUnmarshal/CBOR_map_to_Go_map[string]interface_{}-2 | 3755 ns/op | 965 B/op | 19 allocs/op +BenchmarkUnmarshal/CBOR_map_to_Go_map[string]string-2 | 2586 ns/op | 740 B/op | 5 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshal/Go_bool_to_CBOR_bool-2 | 86.1 ns/op | 1 B/op | 1 allocs/op +BenchmarkMarshal/Go_uint64_to_CBOR_positive_int-2 | 97.0 ns/op | 16 B/op | 1 allocs/op +BenchmarkMarshal/Go_int64_to_CBOR_negative_int-2 | 90.3 ns/op | 3 B/op | 1 allocs/op +BenchmarkMarshal/Go_float64_to_CBOR_float-2 | 97.9 ns/op | 16 B/op | 1 allocs/op +BenchmarkMarshal/Go_[]uint8_to_CBOR_bytes-2 | 121 ns/op | 32 B/op | 1 allocs/op +BenchmarkMarshal/Go_string_to_CBOR_text-2 | 115 ns/op | 48 B/op | 1 allocs/op +BenchmarkMarshal/Go_[]int_to_CBOR_array-2 | 529 ns/op | 32 B/op | 1 allocs/op +BenchmarkMarshal/Go_map[string]string_to_CBOR_map-2 | 2115 ns/op | 576 B/op | 28 allocs/op + +## Go structs + +Benchmarks use struct and map[string]interface{} representing the following value: + +``` +{ + "T": true, + "Ui": uint(18446744073709551615), + "I": -1000, + "F": -4.1, + "B": []byte{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}, + "S": "The quick brown fox jumps over the lazy dog", + "Slci": []int{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}, + "Mss": map[string]string{"a": "A", "b": "B", "c": "C", "d": "D", "e": "E", "f": "F", "g": "G", "h": "H", "i": "I", "j": "J", "l": "L", "m": "M", "n": "N"}, +} +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshal/CBOR_map_to_Go_map[string]interface{}-2 | 6221 ns/op | 2621 B/op | 73 allocs/op +BenchmarkUnmarshal/CBOR_map_to_Go_struct-2 | 4458 ns/op | 1172 B/op | 10 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshal/Go_map[string]interface{}_to_CBOR_map-2 | 4441 ns/op | 1072 B/op | 45 allocs/op +BenchmarkMarshal/Go_struct_to_CBOR_map-2 | 2866 ns/op | 720 B/op | 28 allocs/op + +## Go structs with "keyasint" struct tag + +Benchmarks use struct (with keyasint struct tag) and map[int]interface{} representing the following value: + +``` +{ + 1: true, + 2: uint(18446744073709551615), + 3: -1000, + 4: -4.1, + 5: []byte{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}, + 6: "The quick brown fox jumps over the lazy dog", + 7: []int{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}, + 8: map[string]string{"a": "A", "b": "B", "c": "C", "d": "D", "e": "E", "f": "F", "g": "G", "h": "H", "i": "I", "j": "J", "l": "L", "m": "M", "n": "N"}, +} +``` + +Struct type with keyasint struct tag is used to handle CBOR map with integer keys. + +``` +type T struct { + T bool `cbor:"1,keyasint"` + Ui uint `cbor:"2,keyasint"` + I int `cbor:"3,keyasint"` + F float64 `cbor:"4,keyasint"` + B []byte `cbor:"5,keyasint"` + S string `cbor:"6,keyasint"` + Slci []int `cbor:"7,keyasint"` + Mss map[string]string `cbor:"8,keyasint"` +} +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshal/CBOR_map_to_Go_map[int]interface{}-2| 6030 ns/op | 2517 B/op | 70 allocs/op +BenchmarkUnmarshal/CBOR_map_to_Go_struct_keyasint-2 | 4332 ns/op | 1173 B/op | 10 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshal/Go_map[int]interface{}_to_CBOR_map-2 | 4348 ns/op | 992 B/op | 45 allocs/op +BenchmarkMarshal/Go_struct_keyasint_to_CBOR_map-2 | 2847 ns/op | 704 B/op | 28 allocs/op + +## Go structs with "toarray" struct tag + +Benchmarks use struct (with toarray struct tag) and []interface{} representing the following value: + +``` +[ + true, + uint(18446744073709551615), + -1000, + -4.1, + []byte{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}, + "The quick brown fox jumps over the lazy dog", + []int{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}, + map[string]string{"a": "A", "b": "B", "c": "C", "d": "D", "e": "E", "f": "F", "g": "G", "h": "H", "i": "I", "j": "J", "l": "L", "m": "M", "n": "N"} +] +``` + +Struct type with toarray struct tag is used to handle CBOR array. + +``` +type T struct { + _ struct{} `cbor:",toarray"` + T bool + Ui uint + I int + F float64 + B []byte + S string + Slci []int + Mss map[string]string +} +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshal/CBOR_array_to_Go_[]interface{}-2 | 4863 ns/op | 2404 B/op | 67 allocs/op +BenchmarkUnmarshal/CBOR_array_to_Go_struct_toarray-2 | 4173 ns/op | 1164 B/op | 9 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshal/Go_[]interface{}_to_CBOR_map-2 | 3240 ns/op | 704 B/op | 28 allocs/op +BenchmarkMarshal/Go_struct_toarray_to_CBOR_array-2 | 2823 ns/op | 704 B/op | 28 allocs/op + +## COSE data + +Benchmarks use COSE data from https://tools.ietf.org/html/rfc8392#appendix-A section A.2 + +``` +// 128-Bit Symmetric COSE_Key +{ + / k / -1: h'231f4c4d4d3051fdc2ec0a3851d5b383' + / kty / 1: 4 / Symmetric /, + / kid / 2: h'53796d6d6574726963313238' / 'Symmetric128' /, + / alg / 3: 10 / AES-CCM-16-64-128 / +} +// 256-Bit Symmetric COSE_Key +{ + / k / -1: h'403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1 + ec99192d79569388' + / kty / 1: 4 / Symmetric /, + / kid / 4: h'53796d6d6574726963323536' / 'Symmetric256' /, + / alg / 3: 4 / HMAC 256/64 / +} +// ECDSA 256-Bit COSE Key +{ + / d / -4: h'6c1382765aec5358f117733d281c1c7bdc39884d04a45a1e + 6c67c858bc206c19', + / y / -3: h'60f7f1a780d8a783bfb7a2dd6b2796e8128dbbcef9d3d168 + db9529971a36e7b9', + / x / -2: h'143329cce7868e416927599cf65a34f3ce2ffda55a7eca69 + ed8919a394d42f0f', + / crv / -1: 1 / P-256 /, + / kty / 1: 2 / EC2 /, + / kid / 2: h'4173796d6d657472696345434453413 + 23536' / 'AsymmetricECDSA256' /, + / alg / 3: -7 / ECDSA 256 / +} +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshalCOSE/128-Bit_Symmetric_Key-2 | 562 ns/op | 240 B/op | 4 allocs/op +BenchmarkUnmarshalCOSE/256-Bit_Symmetric_Key-2 | 568 ns/op | 256 B/op | 4 allocs/op +BenchmarkUnmarshalCOSE/ECDSA_P256_256-Bit_Key-2 | 968 ns/op | 360 B/op | 7 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshalCOSE/128-Bit_Symmetric_Key-2 | 523 ns/op | 224 B/op | 2 allocs/op +BenchmarkMarshalCOSE/256-Bit_Symmetric_Key-2 | 521 ns/op | 240 B/op | 2 allocs/op +BenchmarkMarshalCOSE/ECDSA_P256_256-Bit_Key-2 | 668 ns/op | 320 B/op | 2 allocs/op + +## CWT claims data + +Benchmarks use CTW claims data from https://tools.ietf.org/html/rfc8392#appendix-A section A.1 + +``` +{ + / iss / 1: "coap://as.example.com", + / sub / 2: "erikw", + / aud / 3: "coap://light.example.com", + / exp / 4: 1444064944, + / nbf / 5: 1443944944, + / iat / 6: 1443944944, + / cti / 7: h'0b71' +} +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshalCWTClaims-2 | 765 ns/op | 176 B/op | 6 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshalCWTClaims-2 | 451 ns/op | 176 B/op | 2 allocs/op + +## SenML data + +Benchmarks use SenML data from https://tools.ietf.org/html/rfc8428#section-6 + +``` +[ + {-2: "urn:dev:ow:10e2073a0108006:", -3: 1276020076.001, -4: "A", -1: 5, 0: "voltage", 1: "V", 2: 120.1}, + {0: "current", 6: -5, 2: 1.2}, + {0: "current", 6: -4, 2: 1.3}, + {0: "current", 6: -3, 2: 1.4}, + {0: "current", 6: -2, 2: 1.5}, + {0: "current", 6: -1, 2: 1.6}, + {0: "current", 6: 0, 2: 1.7} +] +``` + +Decoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkUnmarshalSenML-2 | 3106 ns/op | 1544 B/op | 18 allocs/op + +Encoding Benchmark | Time | Memory | Allocs +--- | ---: | ---: | ---: +BenchmarkMarshalSenML-2 | 2976 ns/op | 272 B/op | 2 allocs/op diff --git a/vendor/github.com/fxamacker/cbor/v2/CBOR_GOLANG.md b/vendor/github.com/fxamacker/cbor/v2/CBOR_GOLANG.md new file mode 100644 index 0000000000..c9360ca70d --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/CBOR_GOLANG.md @@ -0,0 +1,32 @@ +π [Comparisons](https://github.com/fxamacker/cbor#comparisons) β’ [Status](https://github.com/fxamacker/cbor#current-status) β’ [Design Goals](https://github.com/fxamacker/cbor#design-goals) β’ [Features](https://github.com/fxamacker/cbor#features) β’ [Standards](https://github.com/fxamacker/cbor#standards) β’ [Fuzzing](https://github.com/fxamacker/cbor#fuzzing-and-code-coverage) β’ [Usage](https://github.com/fxamacker/cbor#usage) β’ [Security Policy](https://github.com/fxamacker/cbor#security-policy) β’ [License](https://github.com/fxamacker/cbor#license) + +# CBOR +[CBOR](https://en.wikipedia.org/wiki/CBOR) is a data format designed to allow small code size and small message size. CBOR is defined in [RFC 7049 Concise Binary Object Representation](https://tools.ietf.org/html/rfc7049), an [IETF](http://ietf.org/) Internet Standards Document. + +CBOR is also designed to be stable for decades, be extensible without need for version negotiation, and not require a schema. + +While JSON uses text, CBOR uses binary. CDDL can be used to express CBOR (and JSON) in an easy and unambiguous way. CDDL is defined in (RFC 8610 Concise Data Definition Language). + +## CBOR in Golang (Go) +[Golang](https://golang.org/) is a nickname for the Go programming language. Go is specified in [The Go Programming Language Specification](https://golang.org/ref/spec). + +__[fxamacker/cbor](https://github.com/fxamacker/cbor)__ is a library (written in Go) that encodes and decodes CBOR. The API design of fxamacker/cbor is based on Go's [`encoding/json`](https://golang.org/pkg/encoding/json/). The design and reliability of fxamacker/cbor makes it ideal for encoding and decoding COSE. + +## COSE +COSE is a protocol using CBOR for basic security services. COSE is defined in ([RFC 8152 CBOR Object Signing and Encryption](https://tools.ietf.org/html/rfc8152)). + +COSE describes how to create and process signatures, message authentication codes, and encryption using CBOR for serialization. COSE specification also describes how to represent cryptographic keys using CBOR. COSE is used by WebAuthn. + +## CWT +CBOR Web Token (CWT) is defined in [RFC 8392](http://tools.ietf.org/html/rfc8392). CWT is based on COSE and was derived in part from JSON Web Token (JWT). CWT is a compact way to securely represent claims to be transferred between two parties. + +## WebAuthn +[WebAuthn](https://en.wikipedia.org/wiki/WebAuthn) (Web Authentication) is a web standard for authenticating users to web-based apps and services. It's a core component of FIDO2, the successor of FIDO U2F legacy protocol. + +__[fxamacker/webauthn](https://github.com/fxamacker/webauthn)__ is a library (written in Go) that performs server-side authentication for clients using FIDO2 keys, legacy FIDO U2F keys, tpm, and etc. + +Copyright (c) Faye Amacker and contributors. + +<hr> + +π [Comparisons](https://github.com/fxamacker/cbor#comparisons) β’ [Status](https://github.com/fxamacker/cbor#current-status) β’ [Design Goals](https://github.com/fxamacker/cbor#design-goals) β’ [Features](https://github.com/fxamacker/cbor#features) β’ [Standards](https://github.com/fxamacker/cbor#standards) β’ [Fuzzing](https://github.com/fxamacker/cbor#fuzzing-and-code-coverage) β’ [Usage](https://github.com/fxamacker/cbor#usage) β’ [Security Policy](https://github.com/fxamacker/cbor#security-policy) β’ [License](https://github.com/fxamacker/cbor#license) diff --git a/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md b/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..bc1f077baa --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at faye.github@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md b/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md new file mode 100644 index 0000000000..1a2321c5d1 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# How to contribute + +This project started because I needed an easy, small, and crash-proof CBOR library for my [WebAuthn (FIDO2) server library](https://github.com/fxamacker/webauthn). I believe this was the first and still only standalone CBOR library (in Go) that is fuzz tested as of November 10, 2019. + +To my surprise, Stefan Tatschner (rumpelsepp) submitted the first 2 issues when I didn't expect this project to be noticed. So I decided to make it more full-featured for others by announcing releases and asking for feedback. Even this document exists because Montgomery Edwardsβ΄β΄βΈ (x448) opened [issue #22](https://github.com/fxamacker/cbor/issues/22). In other words, you can contribute by opening an issue that helps the project improve. Especially in the early stages. + +When I announced v1.2 on Go Forum, Jakob Borg (calmh) responded with a thumbs up and encouragement. Another project of equal priority needed my time and Jakob's kind words tipped the scale for me to work on this one (speedups for [milestone v1.3](https://github.com/fxamacker/cbor/issues?q=is%3Aopen+is%3Aissue+milestone%3Av1.3.0).) So words of appreciation or encouragement is nice way to contribute to open source projects. + +Another way is by using this library in your project. It can lead to features that benefit both projects, which is what happened when oasislabs/oasis-core switched to this CBOR libary -- thanks Yawning Angel (yawning) for requesting BinaryMarshaler/BinaryUnmarshaler and Jernej Kos (kostco) for requesting RawMessage! + +If you'd like to contribute code or send CBOR data, please read on (it can save you time!) + +## Private reports +Usually, all issues are tracked publicly on [GitHub](https://github.com/fxamacker/cbor/issues). + +To report security vulnerabilities, please email faye.github@gmail.com and allow time for the problem to be resolved before disclosing it to the public. For more info, see [Security Policy](https://github.com/fxamacker/cbor#security-policy). + +Please do not send data that might contain personally identifiable information, even if you think you have permission. That type of support requires payment and a contract where I'm indemnified, held harmless, and defended for any data you send to me. + +## Prerequisites to pull requests +Please [create an issue](https://github.com/fxamacker/cbor/issues/new/choose), if one doesn't already exist, and describe your concern. You'll need a [GitHub account](https://github.com/signup/free) to do this. + +If you submit a pull request without creating an issue and getting a response, you risk having your work unused because the bugfix or feature was already done by others and being reviewed before reaching Github. + +## Describe your issue +Clearly describe the issue: +* If it's a bug, please provide: **version of this library** and **Go** (`go version`), **unmodified error message**, and describe **how to reproduce it**. Also state **what you expected to happen** instead of the error. +* If you propose a change or addition, try to give an example how the improved code could look like or how to use it. +* If you found a compilation error, please confirm you're using a supported version of Go. If you are, then provide the output of `go version` first, followed by the complete error message. + +## Please don't +Please don't send data containing personally identifiable information, even if you think you have permission. That type of support requires payment and a contract where I'm indemnified, held harmless, and defended for any data you send to me. + +Please don't send CBOR data larger than 512 bytes. If you want to send crash-producing CBOR data > 512 bytes, please get my permission before sending it to me. + +## Wanted +* Opening issues that are helpful to the project +* Using this library in your project and letting me know +* Sending well-formed CBOR data (<= 512 bytes) that causes crashes (none found yet). +* Sending malformed CBOR data (<= 512 bytes) that causes crashes (none found yet, but bad actors are better than me at breaking things). +* Sending tests or data for unit tests that increase code coverage (currently at 97.8% for v1.2.) +* Pull requests with small changes that are well-documented and easily understandable. +* Sponsors, donations, bounties, subscriptions: I'd like to run uninterrupted fuzzing between releases on a server with dedicated CPUs (after v1.3 or v1.4.) + +## Credits +This guide used nlohmann/json contribution guidelines for inspiration as suggested in issue #22. + diff --git a/vendor/github.com/fxamacker/cbor/v2/LICENSE b/vendor/github.com/fxamacker/cbor/v2/LICENSE new file mode 100644 index 0000000000..8d9b736a48 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 - present Faye Amacker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/fxamacker/cbor/v2/README.md b/vendor/github.com/fxamacker/cbor/v2/README.md new file mode 100644 index 0000000000..09ac3351a0 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/README.md @@ -0,0 +1,938 @@ +[![CBOR Library - Slideshow and Latest Docs.](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_slides.gif)](https://github.com/fxamacker/cbor/blob/master/README.md) + +# CBOR library in Go +[__`fxamacker/cbor`__](https://github.com/fxamacker/cbor) is a CBOR encoder & decoder in [Go](https://golang.org). It has a standard API, CBOR tags, options for duplicate map keys, float64β32β16, `toarray`, `keyasint`, etc. Each release passes 375+ tests and 250+ million execs fuzzing. + +[![](https://github.com/fxamacker/cbor/workflows/ci/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3Aci) +[![](https://github.com/fxamacker/cbor/workflows/cover%20%E2%89%A598%25/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3A%22cover+%E2%89%A598%25%22) +[![](https://github.com/fxamacker/cbor/workflows/linters/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3Alinters) +[![Go Report Card](https://goreportcard.com/badge/github.com/fxamacker/cbor)](https://goreportcard.com/report/github.com/fxamacker/cbor) +[![Release](https://img.shields.io/github/release/fxamacker/cbor.svg?style=flat-square)](https://github.com/fxamacker/cbor/releases) +[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/fxamacker/cbor/master/LICENSE) + +__What is CBOR__? [CBOR](CBOR_GOLANG.md) ([RFC 7049](https://tools.ietf.org/html/rfc7049)) is a binary data format inspired by JSON and MessagePack. CBOR is used in [IETF](https://www.ietf.org) Internet Standards such as COSE ([RFC 8152](https://tools.ietf.org/html/rfc8152)) and CWT ([RFC 8392 CBOR Web Token](https://tools.ietf.org/html/rfc8392)). WebAuthn also uses CBOR. + +__`fxamacker/cbor`__ is safe and fast. It safely handles malformed CBOR data: + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_security_table.svg?sanitize=1 "CBOR Security Comparison") + +__`fxamacker/cbor`__ is fast when using CBOR data with Go structs: + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_speed_table.svg?sanitize=1 "CBOR Speed Comparison") + +Benchmarks used data from [RFC 8392 Appendix A.1](https://tools.ietf.org/html/rfc8392#appendix-A.1) and default options for each CBOR library. + +__`fxamacker/cbor`__ produces smaller binaries. All builds of cisco/senml had MessagePack feature removed: + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_size_comparison.png "CBOR library and program size comparison chart") + +<hr> + +__Standard API__: functions with signatures identical to [`encoding/json`](https://golang.org/pkg/encoding/json/) include: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, and `decoder.Decode`. + +__Standard interfaces__ allow custom encoding or decoding: +`BinaryMarshaler`, `BinaryUnmarshaler`, `Marshaler`, and `Unmarshaler`. + +__Struct tags__ like __`toarray`__ & __`keyasint`__ translate Go struct fields to CBOR array elements, etc. + +<br> + +[![CBOR API](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_api_struct_tags.png)](#usage) + +<hr> + +__`fxamacker/cbor`__ is a full-featured CBOR encoder and decoder. Support for CBOR includes: + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_features.svg?sanitize=1 "CBOR Features") + +<hr> + +β [__Installation__](#installation) β’ [__System Requirements__](#system-requirements) β’ [__Quick Start Guide__](#quick-start) + +<hr> + +__Why this CBOR library?__ It doesn't crash and it has well-balanced qualities: small, fast, safe and easy. It also has a standard API, CBOR tags (built-in and user-defined), float64β32β16, and duplicate map key options. + +* __Standard API__. Codec functions with signatures identical to [`encoding/json`](https://golang.org/pkg/encoding/json/) include: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, and `decoder.Decode`. + +* __Customizable__. Standard interfaces are provided to allow user-implemented encoding or decoding: +`BinaryMarshaler`, `BinaryUnmarshaler`, `Marshaler`, and `Unmarshaler`. + +* __Small apps__. Same programs are 4-9 MB smaller by switching to this library. No code gen and the only imported pkg is [x448/float16](https://github.com/x448/float16) which is maintained by the same team as this library. + +* __Small data__. The `toarray`, `keyasint`, and `omitempty` struct tags shrink size of Go structs encoded to CBOR. Integers encode to smallest form that fits. Floats can shrink from float64 -> float32 -> float16 if values fit. + +* __Fast__. v1.3 became faster than a well-known library that uses `unsafe` optimizations and code gen. Faster libraries will always exist, but speed is only one factor. This library doesn't use `unsafe` optimizations or code gen. + +* __Safe__ and reliable. It prevents crashes on malicious CBOR data by using extensive tests, coverage-guided fuzzing, data validation, and avoiding Go's [`unsafe`](https://golang.org/pkg/unsafe/) pkg. Decoder settings include: `MaxNestedLevels`, `MaxArrayElements`, `MaxMapPairs`, and `IndefLength`. + +* __Easy__ and saves time. Simple (no param) functions return preset `EncOptions` so you don't have to know the differences between Canonical CBOR and CTAP2 Canonical CBOR to use those standards. + +π‘ Struct tags are a Go language feature. CBOR tags relate to a CBOR data type (major type 6). + +Struct tags for CBOR and JSON like `` `cbor:"name,omitempty"` `` and `` `json:"name,omitempty"` `` are supported so you can leverage your existing code. If both `cbor:` and `json:` tags exist then it will use `cbor:`. + +New struct tags like __`keyasint`__ and __`toarray`__ make compact CBOR data such as COSE, CWT, and SenML easier to use. + +β [Quick Start](#quick-start) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Installation + +π If Go modules aren't used, delete or modify example_test.go +from `"github.com/fxamacker/cbor/v2"` to `"github.com/fxamacker/cbor"` + +Using Go modules is recommended. +``` +$ GO111MODULE=on go get github.com/fxamacker/cbor/v2 +``` + +```go +import ( + "github.com/fxamacker/cbor/v2" // imports as package "cbor" +) +``` + +[Released versions](https://github.com/fxamacker/cbor/releases) benefit from longer fuzz tests. + +## System Requirements + +Using Go modules is recommended but not required. + +* Go 1.12 (or newer). +* amd64, arm64, ppc64le and s390x. Other architectures may also work but they are not tested as frequently. + +If Go modules feature isn't used, please see [Installation](#installation) about deleting or modifying example_test.go. + +## Quick Start +π‘οΈ Use Go's `io.LimitReader` to limit size when decoding very large or indefinite size data. + +Functions with identical signatures to encoding/json include: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, `decoder.Decode`. + +__Default Mode__ + +If default options are acceptable, package level functions can be used for encoding and decoding. + +```go +b, err := cbor.Marshal(v) // encode v to []byte b + +err := cbor.Unmarshal(b, &v) // decode []byte b to v + +encoder := cbor.NewEncoder(w) // create encoder with io.Writer w + +decoder := cbor.NewDecoder(r) // create decoder with io.Reader r +``` + +__Modes__ + +If you need to use options or CBOR tags, then you'll want to create a mode. + +"Mode" means defined way of encoding or decoding -- it links the standard API to your CBOR options and CBOR tags. This way, you don't pass around options and the API remains identical to `encoding/json`. + +EncMode and DecMode are interfaces created from EncOptions or DecOptions structs. +For example, `em, err := cbor.EncOptions{...}.EncMode()` or `em, err := cbor.CanonicalEncOptions().EncMode()`. + +EncMode and DecMode use immutable options so their behavior won't accidentally change at runtime. Modes are reusable, safe for concurrent use, and allow fast parallelism. + +__Creating and Using Encoding Modes__ + +π‘ Avoid using init(). For best performance, reuse EncMode and DecMode after creating them. + +Most apps will probably create one EncMode and DecMode before init(). However, there's no limit and each can use different options. + +```go +// Create EncOptions using either struct literal or a function. +opts := cbor.CanonicalEncOptions() + +// If needed, modify opts. For example: opts.Time = cbor.TimeUnix + +// Create reusable EncMode interface with immutable options, safe for concurrent use. +em, err := opts.EncMode() + +// Use EncMode like encoding/json, with same function signatures. +b, err := em.Marshal(v) // encode v to []byte b + +encoder := em.NewEncoder(w) // create encoder with io.Writer w +err := encoder.Encode(v) // encode v to io.Writer w +``` + +__Creating Modes With CBOR Tags__ + +A TagSet is used to specify CBOR tags. + +```go +em, err := opts.EncMode() // no tags +em, err := opts.EncModeWithTags(ts) // immutable tags +em, err := opts.EncModeWithSharedTags(ts) // mutable shared tags +``` + +TagSet and all modes using it are safe for concurrent use. Equivalent API is available for DecMode. + +__Predefined Encoding Options__ + +```go +func CanonicalEncOptions() EncOptions {} // settings for RFC 7049 Canonical CBOR +func CTAP2EncOptions() EncOptions {} // settings for FIDO2 CTAP2 Canonical CBOR +func CoreDetEncOptions() EncOptions {} // settings from a draft RFC (subject to change) +func PreferredUnsortedEncOptions() EncOptions {} // settings from a draft RFC (subject to change) +``` + +The empty curly braces prevent a syntax highlighting bug on GitHub, please ignore them. + +__Struct Tags (keyasint, toarray, omitempty)__ + +The `keyasint`, `toarray`, and `omitempty` struct tags make it easy to use compact CBOR message formats. Internet standards often use CBOR arrays and CBOR maps with int keys to save space. + +__More Info About API, Options, and Usage__ + +Options are listed in the Features section: [Encoding Options](#encoding-options) and [Decoding Options](#decoding-options) + +For more details about each setting, see [Options](#options) section. + +For additional API and usage examples, see [API](#api) and [Usage](#usage) sections. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Current Status +Latest version is v2.x, which has: + +* __Stable API__ β Six codec function signatures will never change. No breaking API changes for other funcs in same major version. And these two functions are subject to change until the draft RFC is approved by IETF (est. in 2020): + * CoreDetEncOptions() is subject to change because it uses draft standard. + * PreferredUnsortedEncOptions() is subject to change because it uses draft standard. +* __Passed all tests__ β v2.x passed all 375+ tests on amd64, arm64, ppc64le and s390x with linux. +* __Passed fuzzing__ β v2.2 passed 459+ million execs in coverage-guided fuzzing on Feb 24, 2020 (still fuzzing.) + +__Why v2.x?__: + +v1 required breaking API changes to support new features like CBOR tags, detection of duplicate map keys, and having more functions with identical signatures to `encoding/json`. + +v2.1 is roughly 26% faster and uses 57% fewer allocs than v1.x when decoding COSE and CWT using default options. + +__Recent Activity__: + +* Release v2.1 (Feb. 17, 2020) + - [x] CBOR tags (major type 6) for encoding and decoding. + - [x] Decoding options for duplicate map key detection: `DupMapKeyQuiet` (default) and `DupMapKeyEnforcedAPF` + - [x] Decoding optimizations. Structs using keyasint tag (like COSE and CWT) is + 24-28% faster and 53-61% fewer allocs than both v1.5 and v2.0.1. + +* Release v2.2 (Feb. 24, 2020) + - [x] CBOR BSTR <--> Go byte array (byte slices were already supported) + - [x] Add more encoding and decoding options (MaxNestedLevels, MaxArrayElements, MaxMapKeyPairs, TagsMd, etc.) + - [x] Fix potential error when decoding shorter CBOR indef length array to Go array (slice wasn't affected). This bug affects all prior versions of 1.x and 2.x. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Design Goals +This library is designed to be a generic CBOR encoder and decoder. It was initially created for a [WebAuthn (FIDO2) server library](https://github.com/fxamacker/webauthn), because existing CBOR libraries (in Go) didn't meet certain criteria in 2019. + +This library is designed to be: + +* __Easy__ β API is like `encoding/json` plus `keyasint` and `toarray` struct tags. +* __Small__ β Programs in cisco/senml are 4 MB smaller by switching to this library. In extreme cases programs can be smaller by 9+ MB. No code gen and the only imported pkg is x448/float16 which is maintained by the same team. +* __Safe and reliable__ β No `unsafe` pkg, coverage >95%, coverage-guided fuzzing, and data validation to avoid crashes on malformed or malicious data. Decoder settings include: `MaxNestedLevels`, `MaxArrayElements`, `MaxMapPairs`, and `IndefLength`. + +Avoiding `unsafe` package has benefits. The `unsafe` package [warns](https://golang.org/pkg/unsafe/): + +> Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines. + +All releases prioritize reliability to avoid crashes on decoding malformed CBOR data. See [Fuzzing and Coverage](#fuzzing-and-code-coverage). + +Competing factors are balanced: + +* __Speed__ vs __safety__ vs __size__ β to keep size small, avoid code generation. For safety, validate data and avoid Go's `unsafe` pkg. For speed, use safe optimizations such as caching struct metadata. This library is faster than a well-known library that uses `unsafe` and code gen. +* __Standards compliance__ vs __size__ β Supports CBOR RFC 7049 with minor [limitations](#limitations). To limit bloat, CBOR tags are supported but not all tags are built-in. The API allows users to add tags that aren't built-in. The API also allows custom encoding and decoding of user-defined Go types. + +__Click to expand topic:__ + +<details> + <summary>Supported CBOR Features (Highlights)</summary><p> + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_features.svg?sanitize=1 "CBOR Features") + +</details> + +<details> + <summary>v2.0 API Design</summary><p> + +v2.0 decoupled options from CBOR encoding & decoding functions: + +* More encoding/decoding function signatures are identical to encoding/json. +* More function signatures can remain stable forever. +* More flexibility for evolving internal data types, optimizations, and concurrency. +* Features like CBOR tags can be added without more breaking API changes. +* Options to handle duplicate map keys can be added without more breaking API changes. + +</details> + +Features not in Go's standard library are usually not added. However, the __`toarray`__ struct tag in __ugorji/go__ was too useful to ignore. It was added in v1.3 when a project mentioned they were using it with CBOR to save disk space. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Features + +### Standard API + +Many function signatures are identical to encoding/json, including: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, `decoder.Decode`. + +`RawMessage` can be used to delay CBOR decoding or precompute CBOR encoding, like `encoding/json`. + +Standard interfaces allow user-defined types to have custom CBOR encoding and decoding. They include: +`BinaryMarshaler`, `BinaryUnmarshaler`, `Marshaler`, and `Unmarshaler`. + +`Marshaler` and `Unmarshaler` interfaces are satisfied by `MarshalCBOR` and `UnmarshalCBOR` functions using same params and return types as Go's MarshalJSON and UnmarshalJSON. + +### Struct Tags + +Support "cbor" and "json" keys in Go's struct tags. If both are specified, then "cbor" is used. + +* `toarray` struct tag allows named struct fields for elements of CBOR arrays. +* `keyasint` struct tag allows named struct fields for elements of CBOR maps with int keys. +* `omitempty` struct tag excludes empty field values from being encoded. + +See [Usage](#usage). + +### CBOR Tags (New in v2.1) + +There are three broad categories of CBOR tags: + +* __Default built-in CBOR tags__ currently include tag numbers 0 and 1 (Time). Additional default built-in tags in future releases may include tag numbers 2 and 3 (Bignum). + +* __Optional built-in CBOR tags__ may be provided in the future via build flags or optional package(s) to help reduce bloat. + +* __User-defined CBOR tags__ are easy by using TagSet to associate tag numbers to user-defined Go types. + +### Preferred Serialization + +Preferred serialization encodes integers and floating-point values using the fewest bytes possible. + +* Integers are always encoded using the fewest bytes possible. +* Floating-point values can optionally encode from float64->float32->float16 when values fit. + +### Compact Data Size + +The combination of preferred serialization and struct tags (toarray, keyasint, omitempty) allows very compact data size. + +### Predefined Encoding Options + +Easy-to-use functions (no params) return preset EncOptions struct: +`CanonicalEncOptions`, `CTAP2EncOptions`, `CoreDetEncOptions`, `PreferredUnsortedEncOptions` + +### Encoding Options + +Integers always encode to the shortest form that preserves value. By default, time values are encoded without tags. + +Encoding of other data types and map key sort order are determined by encoder options. + +| Encoding Option | Available Settings (defaults in bold, aliases in italics) | +| --------------- | --------------------------------------------------------- | +| EncOptions.Sort | __`SortNone`__, `SortLengthFirst`, `SortBytewiseLexical`, _`SortCanonical`_, _`SortCTAP2`_, _`SortCoreDeterministic`_ | +| EncOptions.Time | __`TimeUnix`__, `TimeUnixMicro`, `TimeUnixDynamic`, `TimeRFC3339`, `TimeRFC3339Nano` | +| EncOptions.TimeTag | __`EncTagNone`__, `EncTagRequired` | +| EncOptions.ShortestFloat | __`ShortestFloatNone`__, `ShortestFloat16` | +| EncOptions.InfConvert | __`InfConvertFloat16`__, `InfConvertNone` | +| EncOptions.NaNConvert | __`NaNConvert7e00`__, `NaNConvertNone`, `NaNConvertQuiet`, `NaNConvertPreserveSignal` | +| EncOptions.IndefLength | __`IndefLengthAllowed`__, `IndefLengthForbidden` | +| EncOptions.TagsMd | __`TagsAllowed`__, `TagsForbidden` | + +See [Options](#options) section for details about each setting. + +### Decoding Options + +| Decoding Option | Available Settings (defaults in bold, aliases in italics) | +| --------------- | --------------------------------------------------------- | +| DecOptions.TimeTag | __`DecTagIgnored`__, `DecTagOptional`, `DecTagRequired` | +| DecOptions.DupMapKey | __`DupMapKeyQuiet`__, `DupMapKeyEnforcedAPF` | +| DecOptions.IndefLength | __`IndefLengthAllowed`__, `IndefLengthForbidden` | +| DecOptions.TagsMd | __`TagsAllowed`__, `TagsForbidden` | +| DecOptions.MaxNestedLevels | __32__, can be set to [4, 256] | +| DecOptions.MaxArrayElements | __131072__, can be set to [16, 134217728] | +| DecOptions.MaxMapPairs | __131072__, can be set to [16, 134217728] | + +See [Options](#options) section for details about each setting. + +### Additional Features + +* Decoder always checks for invalid UTF-8 string errors. +* Decoder always decodes in-place to slices, maps, and structs. +* Decoder tries case-sensitive first and falls back to case-insensitive field name match when decoding to structs. +* Both encoder and decoder support indefinite length CBOR data (["streaming"](https://tools.ietf.org/html/rfc7049#section-2.2)). +* Both encoder and decoder correctly handles nil slice, map, pointer, and interface values. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Standards +This library is a full-featured generic CBOR [(RFC 7049)](https://tools.ietf.org/html/rfc7049) encoder and decoder. Notable CBOR features include: + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_features.svg?sanitize=1 "CBOR Features") + +See the Features section for list of [Encoding Options](#encoding-options) and [Decoding Options](#decoding-options). + +Known limitations are noted in the [Limitations section](#limitations). + +Go nil values for slices, maps, pointers, etc. are encoded as CBOR null. Empty slices, maps, etc. are encoded as empty CBOR arrays and maps. + +Decoder checks for all required well-formedness errors, including all "subkinds" of syntax errors and too little data. + +After well-formedness is verified, basic validity errors are handled as follows: + +* Invalid UTF-8 string: Decoder always checks and returns invalid UTF-8 string error. +* Duplicate keys in a map: Decoder has options to ignore or enforce rejection of duplicate map keys. + +When decoding well-formed CBOR arrays and maps, decoder saves the first error it encounters and continues with the next item. Options to handle this differently may be added in the future. + +See [Options](#options) section for detailed settings or [Features](#features) section for a summary of options. + +__Click to expand topic:__ + +<details> + <summary>Duplicate Map Keys</summary><p> + +This library provides options for fast detection and rejection of duplicate map keys based on applying a Go-specific data model to CBOR's extended generic data model in order to determine duplicate vs distinct map keys. Detection relies on whether the CBOR map key would be a duplicate "key" when decoded and applied to the user-provided Go map or struct. + +`DupMapKeyQuiet` turns off detection of duplicate map keys. It tries to use a "keep fastest" method by choosing either "keep first" or "keep last" depending on the Go data type. + +`DupMapKeyEnforcedAPF` enforces detection and rejection of duplidate map keys. Decoding stops immediately and returns `DupMapKeyError` when the first duplicate key is detected. The error includes the duplicate map key and the index number. + +APF suffix means "Allow Partial Fill" so the destination map or struct can contain some decoded values at the time of error. It is the caller's responsibility to respond to the `DupMapKeyError` by discarding the partially filled result if that's required by their protocol. + +</details> + +## Limitations + +If any of these limitations prevent you from using this library, please open an issue along with a link to your project. + +* CBOR negative int (type 1) that cannot fit into Go's int64 are not supported, such as RFC 7049 example -18446744073709551616. Decoding these values returns `cbor.UnmarshalTypeError` like Go's `encoding/json`. However, this may be resolved in a future release by adding support for `big.Int`. Until then, users can use the API for custom encoding and decoding. +* CBOR `Undefined` (0xf7) value decodes to Go's `nil` value. CBOR `Null` (0xf6) more closely matches Go's `nil`. +* CBOR map keys with data types not supported by Go for map keys are ignored and an error is returned after continuing to decode remaining items. +* When using io.Reader interface to read very large or indefinite length CBOR data, Go's `io.LimitReader` should be used to limit size. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## API +Many function signatures are identical to Go's encoding/json, such as: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, and `decoder.Decode`. + +Interfaces identical or comparable to Go's encoding, encoding/json, or encoding/gob include: +`Marshaler`, `Unmarshaler`, `BinaryMarshaler`, and `BinaryUnmarshaler`. + +Like `encoding/json`, `RawMessage` can be used to delay CBOR decoding or precompute CBOR encoding. + +"Mode" in this API means defined way of encoding or decoding -- it links the standard API to CBOR options and CBOR tags. + +EncMode and DecMode are interfaces created from EncOptions or DecOptions structs. +For example, `em, err := cbor.EncOptions{...}.EncMode()` or `em, err := cbor.CanonicalEncOptions().EncMode()`. + +EncMode and DecMode use immutable options so their behavior won't accidentally change at runtime. Modes are intended to be reused and are safe for concurrent use. + +__API for Default Mode__ + +If default options are acceptable, then you don't need to create EncMode or DecMode. + +```go +Marshal(v interface{}) ([]byte, error) +NewEncoder(w io.Writer) *Encoder + +Unmarshal(data []byte, v interface{}) error +NewDecoder(r io.Reader) *Decoder +``` + +__API for Creating & Using Encoding Modes__ + +```go +// EncMode interface uses immutable options and is safe for concurrent use. +type EncMode interface { + Marshal(v interface{}) ([]byte, error) + NewEncoder(w io.Writer) *Encoder + EncOptions() EncOptions // returns copy of options +} + +// EncOptions specifies encoding options. +type EncOptions struct { +... +} + +// EncMode returns an EncMode interface created from EncOptions. +func (opts EncOptions) EncMode() (EncMode, error) {} + +// EncModeWithTags returns EncMode with options and tags that are both immutable. +func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error) {} + +// EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags. +func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error) {} +``` + +The empty curly braces prevent a syntax highlighting bug, please ignore them. + +__API for Predefined Encoding Options__ + +```go +func CanonicalEncOptions() EncOptions {} // settings for RFC 7049 Canonical CBOR +func CTAP2EncOptions() EncOptions {} // settings for FIDO2 CTAP2 Canonical CBOR +func CoreDetEncOptions() EncOptions {} // settings from a draft RFC (subject to change) +func PreferredUnsortedEncOptions() EncOptions {} // settings from a draft RFC (subject to change) +``` + +__API for Creating & Using Decoding Modes__ + +```go +// DecMode interface uses immutable options and is safe for concurrent use. +type DecMode interface { + Unmarshal(data []byte, v interface{}) error + NewDecoder(r io.Reader) *Decoder + DecOptions() DecOptions // returns copy of options +} + +// DecOptions specifies decoding options. +type DecOptions struct { +... +} + +// DecMode returns a DecMode interface created from DecOptions. +func (opts DecOptions) DecMode() (DecMode, error) {} + +// DecModeWithTags returns DecMode with options and tags that are both immutable. +func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) {} + +// DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags. +func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error) {} +``` + +The empty curly braces prevent a syntax highlighting bug, please ignore them. + +__API for Using CBOR Tags__ + +`TagSet` can be used to associate user-defined Go type(s) to tag number(s). It's also used to create EncMode or DecMode. For example, `em := EncOptions{...}.EncModeWithTags(ts)` or `em := EncOptions{...}.EncModeWithSharedTags(ts)`. This allows every standard API exported by em (like `Marshal` and `NewEncoder`) to use the specified tags automatically. + +`Tag` and `RawTag` can be used to encode/decode a tag number with a Go value, but `TagSet` is generally recommended. + +```go +type TagSet interface { + // Add adds given tag number(s), content type, and tag options to TagSet. + Add(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) error + + // Remove removes given tag content type from TagSet. + Remove(contentType reflect.Type) +} +``` + +`Tag` and `RawTag` types can also be used to encode/decode tag number with Go value. + +```go +type Tag struct { + Number uint64 + Content interface{} +} + +type RawTag struct { + Number uint64 + Content RawMessage +} +``` + +See [API docs (godoc.org)](https://godoc.org/github.com/fxamacker/cbor) for more details and more functions. See [Usage section](#usage) for usage and code examples. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Options + +Options for the decoding and encoding are listed here. + +### Decoding Options + +| DecOptions.TimeTag | Description | +| ------------------ | ----------- | +| DecTagIgnored (default) | Tag numbers are ignored (if present) for time values. | +| DecTagOptional | Tag numbers are only checked for validity if present for time values. | +| DecTagRequired | Tag numbers must be provided for time values except for CBOR Null and CBOR Undefined. | + +CBOR Null and CBOR Undefined are silently treated as Go's zero time instant. Go's `time` package provides `IsZero` function, which reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC. + +| DecOptions.DupMapKey | Description | +| -------------------- | ----------- | +| DupMapKeyQuiet (default) | turns off detection of duplicate map keys. It uses a "keep fastest" method by choosing either "keep first" or "keep last" depending on the Go data type. | +| DupMapKeyEnforcedAPF | enforces detection and rejection of duplidate map keys. Decoding stops immediately and returns `DupMapKeyError` when the first duplicate key is detected. The error includes the duplicate map key and the index number. | + +`DupMapKeyEnforcedAPF` uses "Allow Partial Fill" so the destination map or struct can contain some decoded values at the time of error. Users can respond to the `DupMapKeyError` by discarding the partially filled result if that's required by their protocol. + +| DecOptions.IndefLength | Description | +| ---------------------- | ----------- | +|IndefLengthAllowed (default) | allow indefinite length data | +|IndefLengthForbidden | forbid indefinite length data | + +| DecOptions.TagsMd | Description | +| ----------------- | ----------- | +|TagsAllowed (default) | allow CBOR tags (major type 6) | +|TagsForbidden | forbid CBOR tags (major type 6) | + +| DecOptions.MaxNestedLevels | Description | +| -------------------------- | ----------- | +| 32 (default) | allowed setting is [4, 256] | + +| DecOptions.MaxArrayElements | Description | +| --------------------------- | ----------- | +| 131072 (default) | allowed setting is [16, 134217728] | + +| DecOptions.MaxMapPairs | Description | +| ---------------------- | ----------- | +| 131072 (default) | allowed setting is [16, 134217728] | + +### Encoding Options + +__Integers always encode to the shortest form that preserves value__. Encoding of other data types and map key sort order are determined by encoding options. + +These functions are provided to create and return a modifiable EncOptions struct with predefined settings. + +| Predefined EncOptions | Description | +| --------------------- | ----------- | +| CanonicalEncOptions() |[Canonical CBOR (RFC 7049 Section 3.9)](https://tools.ietf.org/html/rfc7049#section-3.9). | +| CTAP2EncOptions() |[CTAP2 Canonical CBOR (FIDO2 CTAP2)](https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#ctap2-canonical-cbor-encoding-form). | +| PreferredUnsortedEncOptions() |Unsorted, encode float64->float32->float16 when values fit, NaN values encoded as float16 0x7e00. | +| CoreDetEncOptions() |PreferredUnsortedEncOptions() + map keys are sorted bytewise lexicographic. | + +π± CoreDetEncOptions() and PreferredUnsortedEncOptions() are subject to change until the draft RFC they used is approved by IETF. + +| EncOptions.Sort | Description | +| --------------- | ----------- | +| SortNone (default) |No sorting for map keys. | +| SortLengthFirst |Length-first map key ordering. | +| SortBytewiseLexical |Bytewise lexicographic map key ordering | +| SortCanonical |(alias) Same as SortLengthFirst [(RFC 7049 Section 3.9)](https://tools.ietf.org/html/rfc7049#section-3.9) | +| SortCTAP2 |(alias) Same as SortBytewiseLexical [(CTAP2 Canonical CBOR)](https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#ctap2-canonical-cbor-encoding-form). | +| SortCoreDeterministic |(alias) Same as SortBytewiseLexical. | + +| EncOptions.Time | Description | +| --------------- | ----------- | +| TimeUnix (default) | (seconds) Encode as integer. | +| TimeUnixMicro | (microseconds) Encode as floating-point. ShortestFloat option determines size. | +| TimeUnixDynamic | (seconds or microseconds) Encode as integer if time doesn't have fractional seconds, otherwise encode as floating-point rounded to microseconds. | +| TimeRFC3339 | (seconds) Encode as RFC 3339 formatted string. | +| TimeRFC3339Nano | (nanoseconds) Encode as RFC3339 formatted string. | + +| EncOptions.TimeTag | Description | +| ------------------ | ----------- | +| EncTagNone (default) | Tag number will not be encoded for time values. | +| EncTagRequired | Tag number (0 or 1) will be encoded unless time value is undefined/zero-instant. | + +__Undefined Time Values__ + +By default, undefined (zero instant) time values will encode as CBOR Null without tag number for both EncTagNone and EncTagRequired. Although CBOR Undefined might be technically more correct for EncTagRequired, CBOR Undefined might not be supported by other generic decoders and it isn't supported by JSON. + +Go's `time` package provides `IsZero` function, which reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC. + +__Floating-Point Options__ + +Encoder has 3 types of options for floating-point data: ShortestFloatMode, InfConvertMode, and NaNConvertMode. + +| EncOptions.ShortestFloat | Description | +| ------------------------ | ----------- | +| ShortestFloatNone (default) | No size conversion. Encode float32 and float64 to CBOR floating-point of same bit-size. | +| ShortestFloat16 | Encode float64 -> float32 -> float16 ([IEEE 754 binary16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format)) when values fit. | + +Conversions for infinity and NaN use InfConvert and NaNConvert settings. + +| EncOptions.InfConvert | Description | +| --------------------- | ----------- | +| InfConvertFloat16 (default) | Convert +- infinity to float16 since they always preserve value (recommended) | +| InfConvertNone |Don't convert +- infinity to other representations -- used by CTAP2 Canonical CBOR | + +| EncOptions.NaNConvert | Description | +| --------------------- | ----------- | +| NaNConvert7e00 (default) | Encode to 0xf97e00 (CBOR float16 = 0x7e00) -- used by RFC 7049 Canonical CBOR. | +| NaNConvertNone | Don't convert NaN to other representations -- used by CTAP2 Canonical CBOR. | +| NaNConvertQuiet | Force quiet bit = 1 and use shortest form that preserves NaN payload. | +| NaNConvertPreserveSignal | Convert to smallest form that preserves value (quit bit unmodified and NaN payload preserved). | + +| EncOptions.IndefLength | Description | +| ---------------------- | ----------- | +|IndefLengthAllowed (default) | allow indefinite length data | +|IndefLengthForbidden | forbid indefinite length data | + +| EncOptions.TagsMd | Description | +| ----------------- | ----------- | +|TagsAllowed (default) | allow CBOR tags (major type 6) | +|TagsForbidden | forbid CBOR tags (major type 6) | + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Usage +π‘οΈ Use Go's `io.LimitReader` to limit size when decoding very large or indefinite size data. + +Functions with identical signatures to encoding/json include: +`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, `decoder.Decode`. + +__Default Mode__ + +If default options are acceptable, package level functions can be used for encoding and decoding. + +```go +b, err := cbor.Marshal(v) // encode v to []byte b + +err := cbor.Unmarshal(b, &v) // decode []byte b to v + +encoder := cbor.NewEncoder(w) // create encoder with io.Writer w + +decoder := cbor.NewDecoder(r) // create decoder with io.Reader r +``` + +__Modes__ + +If you need to use options or CBOR tags, then you'll want to create a mode. + +"Mode" means defined way of encoding or decoding -- it links the standard API to your CBOR options and CBOR tags. This way, you don't pass around options and the API remains identical to `encoding/json`. + +EncMode and DecMode are interfaces created from EncOptions or DecOptions structs. +For example, `em, err := cbor.EncOptions{...}.EncMode()` or `em, err := cbor.CanonicalEncOptions().EncMode()`. + +EncMode and DecMode use immutable options so their behavior won't accidentally change at runtime. Modes are reusable, safe for concurrent use, and allow fast parallelism. + +__Creating and Using Encoding Modes__ + +EncMode is an interface ([API](#api)) created from EncOptions struct. EncMode uses immutable options after being created and is safe for concurrent use. For best performance, EncMode should be reused. + +```go +// Create EncOptions using either struct literal or a function. +opts := cbor.CanonicalEncOptions() + +// If needed, modify opts. For example: opts.Time = cbor.TimeUnix + +// Create reusable EncMode interface with immutable options, safe for concurrent use. +em, err := opts.EncMode() + +// Use EncMode like encoding/json, with same function signatures. +b, err := em.Marshal(v) // encode v to []byte b + +encoder := em.NewEncoder(w) // create encoder with io.Writer w +err := encoder.Encode(v) // encode v to io.Writer w +``` + +__Struct Tags (keyasint, toarray, omitempty)__ + +The `keyasint`, `toarray`, and `omitempty` struct tags make it easy to use compact CBOR message formats. Internet standards often use CBOR arrays and CBOR maps with int keys to save space. + +<hr> + +[![CBOR API](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_api_struct_tags.png)](#usage) + +<hr> + +__Decoding CWT (CBOR Web Token)__ using `keyasint` and `toarray` struct tags: + +```go +// Signed CWT is defined in RFC 8392 +type signedCWT struct { + _ struct{} `cbor:",toarray"` + Protected []byte + Unprotected coseHeader + Payload []byte + Signature []byte +} + +// Part of COSE header definition +type coseHeader struct { + Alg int `cbor:"1,keyasint,omitempty"` + Kid []byte `cbor:"4,keyasint,omitempty"` + IV []byte `cbor:"5,keyasint,omitempty"` +} + +// data is []byte containing signed CWT + +var v signedCWT +if err := cbor.Unmarshal(data, &v); err != nil { + return err +} +``` + +__Encoding CWT (CBOR Web Token)__ using `keyasint` and `toarray` struct tags: + +```go +// Use signedCWT struct defined in "Decoding CWT" example. + +var v signedCWT +... +if data, err := cbor.Marshal(v); err != nil { + return err +} +``` + +__Encoding and Decoding CWT (CBOR Web Token) with CBOR Tags__ + +```go +// Use signedCWT struct defined in "Decoding CWT" example. + +// Create TagSet (safe for concurrency). +tags := cbor.NewTagSet() +// Register tag COSE_Sign1 18 with signedCWT type. +tags.Add( + cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, + reflect.TypeOf(signedCWT{}), + 18) + +// Create DecMode with immutable tags. +dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) + +// Unmarshal to signedCWT with tag support. +var v signedCWT +if err := dm.Unmarshal(data, &v); err != nil { + return err +} + +// Create EncMode with immutable tags. +em, _ := cbor.EncOptions{}.EncModeWithTags(tags) + +// Marshal signedCWT with tag number. +if data, err := cbor.Marshal(v); err != nil { + return err +} +``` + +For more examples, see [examples_test.go](example_test.go). + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Comparisons + +Comparisons are between this newer library and a well-known library that had 1,000+ stars before this library was created. Default build settings for each library were used for all comparisons. + +__This library is safer__. Small malicious CBOR messages are rejected quickly before they exhaust system resources. + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_security_table.svg?sanitize=1 "CBOR Security Comparison") + +__This library is smaller__. Programs like senmlCat can be 4 MB smaller by switching to this library. Programs using more complex CBOR data types can be 9.2 MB smaller. + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_size_comparison.png "CBOR library and program size comparison chart") + +__This library is faster__ for encoding and decoding CBOR Web Token (CWT). However, speed is only one factor and it can vary depending on data types and sizes. Unlike the other library, this one doesn't use Go's ```unsafe``` package or code gen. + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_speed_comparison.png "CBOR library speed comparison chart") + +The resource intensive `codec.CborHandle` initialization (in the other library) was placed outside the benchmark loop to make sure their library wasn't penalized. + +__This library uses less memory__ for encoding and decoding CBOR Web Token (CWT) using test data from RFC 8392 A.1. + +![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.2.0/cbor_memory_table.svg?sanitize=1 "CBOR Speed Comparison") + +Doing your own comparisons is highly recommended. Use your most common message sizes and data types. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Benchmarks + +Go structs are faster than maps with string keys: + +* decoding into struct is >28% faster than decoding into map. +* encoding struct is >35% faster than encoding map. + +Go structs with `keyasint` struct tag are faster than maps with integer keys: + +* decoding into struct is >28% faster than decoding into map. +* encoding struct is >34% faster than encoding map. + +Go structs with `toarray` struct tag are faster than slice: + +* decoding into struct is >15% faster than decoding into slice. +* encoding struct is >12% faster than encoding slice. + +Doing your own benchmarks is highly recommended. Use your most common message sizes and data types. + +See [Benchmarks for fxamacker/cbor](CBOR_BENCHMARKS.md). + +## Fuzzing and Code Coverage + +__Over 375 tests__ must pass on 4 architectures before tagging a release. They include all RFC 7049 examples, bugs found by fuzzing, maliciously crafted CBOR data, and over 87 tests with malformed data. + +__Code coverage__ must not fall below 95% when tagging a release. Code coverage is 98.6% (`go test -cover`) for cbor v2.2 which is among the highest for libraries (in Go) of this type. + +__Coverage-guided fuzzing__ must pass 250+ million execs before tagging a release. Fuzzing uses [fxamacker/cbor-fuzz](https://github.com/fxamacker/cbor-fuzz). Default corpus has: + +* 2 files related to WebAuthn (FIDO U2F key). +* 3 files with custom struct. +* 9 files with [CWT examples (RFC 8392 Appendix A)](https://tools.ietf.org/html/rfc8392#appendix-A). +* 17 files with [COSE examples (RFC 8152 Appendix B & C)](https://github.com/cose-wg/Examples/tree/master/RFC8152). +* 81 files with [CBOR examples (RFC 7049 Appendix A) ](https://tools.ietf.org/html/rfc7049#appendix-A). It excludes 1 errata first reported in [issue #46](https://github.com/fxamacker/cbor/issues/46). + +Over 1,100 files (corpus) are used for fuzzing because it includes fuzz-generated corpus. + +To prevent excessive delays, fuzzing is not restarted for a release if changes are limited to docs and comments. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) + +## Versions and API Changes +This project uses [Semantic Versioning](https://semver.org), so the API is always backwards compatible unless the major version number changes. + +These functions have signatures identical to encoding/json and they will likely never change even after major new releases: `Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `encoder.Encode`, and `decoder.Decode`. + +Newly added API documented as "subject to change" are excluded from SemVer. + +Newly added API in the master branch that has never been release tagged are excluded from SemVer. + +## Code of Conduct +This project has adopted the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). Contact [faye.github@gmail.com](mailto:faye.github@gmail.com) with any questions or comments. + +## Contributing +Please refer to [How to Contribute](CONTRIBUTING.md). + +## Security Policy +Security fixes are provided for the latest released version. + +To report security vulnerabilities, please email [faye.github@gmail.com](mailto:faye.github@gmail.com) and allow time for the problem to be resolved before reporting it to the public. + +## Disclaimers +Phrases like "no crashes" or "doesn't crash" mean there are no known crash bugs in the latest version based on results of unit tests and coverage-guided fuzzing. It doesn't imply the software is 100% bug-free or 100% invulnerable to all known and unknown attacks. + +Please read the license for additional disclaimers and terms. + +## Special Thanks + +__Making this library better__ + +* Montgomery Edwardsβ΄β΄βΈ for [x448/float16](https://github.com/x448/float16), updating the docs, creating charts & slideshow, filing issues, nudging me to ask for feedback from users, helping with design of v2.0-v2.1 API, and general idea for DupMapKeyEnforcedAPF. +* Stefan Tatschner for using this library in [sep](https://git.sr.ht/~rumpelsepp/sep), being the 1st to discover my CBOR library, requesting time.Time in issue #1, and submitting this library in a [PR to cbor.io](https://github.com/cbor/cbor.github.io/pull/56) on Aug 12, 2019. +* Yawning Angel for using this library to [oasis-core](https://github.com/oasislabs/oasis-core), and requesting BinaryMarshaler in issue #5. +* Jernej Kos for requesting RawMessage in issue #11 and offering feedback on v2.1 API for CBOR tags. +* ZenGround0 for using this library in [go-filecoin](https://github.com/filecoin-project/go-filecoin), filing "toarray" bug in issue #129, and requesting +CBOR BSTR <--> Go array in #133. +* Keith Randall for [fixing Go bugs and providing workarounds](https://github.com/golang/go/issues/36400) so we don't have to wait for new versions of Go. + +__Help clarifying CBOR RFC 7049 or 7049bis__ + +* Carsten Bormann for RFC 7049 (CBOR), his fast confirmation to my RFC 7049 errata, approving my pull request to 7049bis, and his patience when I misread a line in 7049bis. +* Laurence Lundblade for his help on the IETF mailing list for 7049bis and for pointing out on a CBORbis issue that CBOR Undefined might be problematic translating to JSON. +* Jeffrey Yasskin for his help on the IETF mailing list for 7049bis. + +__Words of encouragement and support__ + +* Jakob Borg for his words of encouragement about this library at Go Forum. This is especially appreciated in the early stages when there's a lot of rough edges. + + +## License +Copyright Β© 2019-present [Faye Amacker](https://github.com/fxamacker). + +fxamacker/cbor is licensed under the MIT License. See [LICENSE](LICENSE) for the full license text. + +<hr> + +β [Install](#installation) β’ [Status](#current-status) β’ [Design Goals](#design-goals) β’ [Features](#features) β’ [Standards](#standards) β’ [API](#api) β’ [Usage](#usage) β’ [Fuzzing](#fuzzing-and-code-coverage) β’ [Security Policy](#security-policy) β’ [License](#license) diff --git a/vendor/github.com/fxamacker/cbor/v2/cache.go b/vendor/github.com/fxamacker/cbor/v2/cache.go new file mode 100644 index 0000000000..ace1669b26 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/cache.go @@ -0,0 +1,308 @@ +// 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" + "errors" + "reflect" + "sort" + "strconv" + "strings" + "sync" +) + +var ( + decodingStructTypeCache sync.Map // map[reflect.Type]*decodingStructType + encodingStructTypeCache sync.Map // map[reflect.Type]*encodingStructType + encodeFuncCache sync.Map // map[reflect.Type]encodeFunc + typeInfoCache sync.Map // map[reflect.Type]*typeInfo +) + +type specialType int + +const ( + specialTypeNone specialType = iota + specialTypeUnmarshalerIface + specialTypeEmptyIface + specialTypeTag + specialTypeTime +) + +type typeInfo struct { + elemTypeInfo *typeInfo + keyTypeInfo *typeInfo + typ reflect.Type + kind reflect.Kind + nonPtrType reflect.Type + nonPtrKind reflect.Kind + spclType specialType +} + +func newTypeInfo(t reflect.Type) *typeInfo { + tInfo := typeInfo{typ: t, kind: t.Kind()} + + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + + k := t.Kind() + + tInfo.nonPtrType = t + tInfo.nonPtrKind = k + + if k == reflect.Interface && t.NumMethod() == 0 { + tInfo.spclType = specialTypeEmptyIface + } else if t == typeTag { + tInfo.spclType = specialTypeTag + } else if t == typeTime { + tInfo.spclType = specialTypeTime + } else if reflect.PtrTo(t).Implements(typeUnmarshaler) { + tInfo.spclType = specialTypeUnmarshalerIface + } + + switch k { + case reflect.Array, reflect.Slice: + tInfo.elemTypeInfo = getTypeInfo(t.Elem()) + case reflect.Map: + tInfo.keyTypeInfo = getTypeInfo(t.Key()) + tInfo.elemTypeInfo = getTypeInfo(t.Elem()) + } + + return &tInfo +} + +type decodingStructType struct { + fields fields + err error + toArray bool +} + +func getDecodingStructType(t reflect.Type) *decodingStructType { + if v, _ := decodingStructTypeCache.Load(t); v != nil { + return v.(*decodingStructType) + } + + flds, structOptions := getFields(t) + + toArray := hasToArrayOption(structOptions) + + var err error + for i := 0; i < len(flds); i++ { + if flds[i].keyAsInt { + nameAsInt, numErr := strconv.Atoi(flds[i].name) + if numErr != nil { + err = errors.New("cbor: failed to parse field name \"" + flds[i].name + "\" to int (" + numErr.Error() + ")") + break + } + flds[i].nameAsInt = int64(nameAsInt) + } + + flds[i].typInfo = getTypeInfo(flds[i].typ) + } + + structType := &decodingStructType{fields: flds, err: err, toArray: toArray} + decodingStructTypeCache.Store(t, structType) + return structType +} + +type encodingStructType struct { + fields fields + bytewiseFields fields + lengthFirstFields fields + err error + toArray bool + omitEmpty bool + hasAnonymousField bool +} + +func (st *encodingStructType) getFields(em *encMode) fields { + if em.sort == SortNone { + return st.fields + } + if em.sort == SortLengthFirst { + return st.lengthFirstFields + } + return st.bytewiseFields +} + +type bytewiseFieldSorter struct { + fields fields +} + +func (x *bytewiseFieldSorter) Len() int { + return len(x.fields) +} + +func (x *bytewiseFieldSorter) Swap(i, j int) { + x.fields[i], x.fields[j] = x.fields[j], x.fields[i] +} + +func (x *bytewiseFieldSorter) Less(i, j int) bool { + return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 +} + +type lengthFirstFieldSorter struct { + fields fields +} + +func (x *lengthFirstFieldSorter) Len() int { + return len(x.fields) +} + +func (x *lengthFirstFieldSorter) Swap(i, j int) { + x.fields[i], x.fields[j] = x.fields[j], x.fields[i] +} + +func (x *lengthFirstFieldSorter) Less(i, j int) bool { + if len(x.fields[i].cborName) != len(x.fields[j].cborName) { + return len(x.fields[i].cborName) < len(x.fields[j].cborName) + } + return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 +} + +func getEncodingStructType(t reflect.Type) *encodingStructType { + if v, _ := encodingStructTypeCache.Load(t); v != nil { + return v.(*encodingStructType) + } + + flds, structOptions := getFields(t) + + if hasToArrayOption(structOptions) { + return getEncodingStructToArrayType(t, flds) + } + + var err error + var omitEmpty bool + var hasAnonymousField bool + var hasKeyAsInt bool + var hasKeyAsStr bool + e := getEncodeState() + for i := 0; i < len(flds); i++ { + // Get field's encodeFunc + flds[i].ef = getEncodeFunc(flds[i].typ) + if flds[i].ef == nil { + err = &UnsupportedTypeError{t} + break + } + + // Encode field name + if flds[i].keyAsInt { + nameAsInt, numErr := strconv.Atoi(flds[i].name) + if numErr != nil { + err = errors.New("cbor: failed to parse field name \"" + flds[i].name + "\" to int (" + numErr.Error() + ")") + break + } + flds[i].nameAsInt = int64(nameAsInt) + if nameAsInt >= 0 { + encodeHead(e, byte(cborTypePositiveInt), uint64(nameAsInt)) + } else { + n := nameAsInt*(-1) - 1 + encodeHead(e, byte(cborTypeNegativeInt), uint64(n)) + } + flds[i].cborName = make([]byte, e.Len()) + copy(flds[i].cborName, e.Bytes()) + e.Reset() + + hasKeyAsInt = true + } else { + encodeHead(e, byte(cborTypeTextString), uint64(len(flds[i].name))) + flds[i].cborName = make([]byte, e.Len()+len(flds[i].name)) + n := copy(flds[i].cborName, e.Bytes()) + copy(flds[i].cborName[n:], flds[i].name) + e.Reset() + + hasKeyAsStr = true + } + + // Check if field is from embedded struct + if len(flds[i].idx) > 1 { + hasAnonymousField = true + } + + // Check if field can be omitted when empty + if flds[i].omitEmpty { + omitEmpty = true + } + } + putEncodeState(e) + + if err != nil { + structType := &encodingStructType{err: err} + encodingStructTypeCache.Store(t, structType) + return structType + } + + // Sort fields by canonical order + bytewiseFields := make(fields, len(flds)) + copy(bytewiseFields, flds) + sort.Sort(&bytewiseFieldSorter{bytewiseFields}) + + lengthFirstFields := bytewiseFields + if hasKeyAsInt && hasKeyAsStr { + lengthFirstFields = make(fields, len(flds)) + copy(lengthFirstFields, flds) + sort.Sort(&lengthFirstFieldSorter{lengthFirstFields}) + } + + structType := &encodingStructType{ + fields: flds, + bytewiseFields: bytewiseFields, + lengthFirstFields: lengthFirstFields, + omitEmpty: omitEmpty, + hasAnonymousField: hasAnonymousField, + } + encodingStructTypeCache.Store(t, structType) + return structType +} + +func getEncodingStructToArrayType(t reflect.Type, flds fields) *encodingStructType { + var hasAnonymousField bool + for i := 0; i < len(flds); i++ { + // Get field's encodeFunc + flds[i].ef = getEncodeFunc(flds[i].typ) + if flds[i].ef == nil { + structType := &encodingStructType{err: &UnsupportedTypeError{t}} + encodingStructTypeCache.Store(t, structType) + return structType + } + + // Check if field is from embedded struct + if len(flds[i].idx) > 1 { + hasAnonymousField = true + } + } + + structType := &encodingStructType{ + fields: flds, + toArray: true, + hasAnonymousField: hasAnonymousField, + } + encodingStructTypeCache.Store(t, structType) + return structType +} + +func getEncodeFunc(t reflect.Type) encodeFunc { + if v, _ := encodeFuncCache.Load(t); v != nil { + return v.(encodeFunc) + } + f := getEncodeFuncInternal(t) + encodeFuncCache.Store(t, f) + return f +} + +func getTypeInfo(t reflect.Type) *typeInfo { + if v, _ := typeInfoCache.Load(t); v != nil { + return v.(*typeInfo) + } + tInfo := newTypeInfo(t) + typeInfoCache.Store(t, tInfo) + return tInfo +} + +func hasToArrayOption(tag string) bool { + s := ",toarray" + idx := strings.Index(tag, s) + return idx >= 0 && (len(tag) == idx+len(s) || tag[idx+len(s)] == ',') +} diff --git a/vendor/github.com/fxamacker/cbor/v2/decode.go b/vendor/github.com/fxamacker/cbor/v2/decode.go new file mode 100644 index 0000000000..079e682131 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/decode.go @@ -0,0 +1,1642 @@ +// 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/binary" + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/x448/float16" +) + +// Unmarshal parses the CBOR-encoded data and stores the result in the value +// pointed to by v using the default decoding options. If v is nil or not a +// pointer, Unmarshal returns an error. +// +// Unmarshal uses the inverse of the encodings that Marshal uses, allocating +// maps, slices, and pointers as necessary, with the following additional rules: +// +// To unmarshal CBOR into a pointer, Unmarshal first handles the case of the +// CBOR being the CBOR literal null. In that case, Unmarshal sets the pointer +// to nil. Otherwise, Unmarshal unmarshals the CBOR into the value pointed at +// by the pointer. If the pointer is nil, Unmarshal allocates a new value for +// it to point to. +// +// To unmarshal CBOR into an interface value, Unmarshal stores one of these in +// the interface value: +// +// bool, for CBOR booleans +// uint64, for CBOR positive integers +// int64, for CBOR negative integers +// float64, for CBOR floating points +// []byte, for CBOR byte strings +// string, for CBOR text strings +// []interface{}, for CBOR arrays +// map[interface{}]interface{}, for CBOR maps +// nil, for CBOR null +// +// To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice only +// if the CBOR array is empty or slice capacity is less than CBOR array length. +// Otherwise Unmarshal reuses the existing slice, overwriting existing elements. +// Unmarshal sets the slice length to CBOR array length. +// +// To ummarshal a CBOR array into a Go array, Unmarshal decodes CBOR array +// elements into corresponding Go array elements. If the Go array is smaller +// than the CBOR array, the additional CBOR array elements are discarded. If +// the CBOR array is smaller than the Go array, the additional Go array elements +// are set to zero values. +// +// 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, keeping existing +// entries. Unmarshal stores key-value pairs from the CBOR map into Go map. +// +// 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 prefers an exact match but also accepts a case-insensitive match. +// Map keys which don't have a corresponding struct field are ignored. +// +// 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. +// +// To unmarshal CBOR into a value implementing the Unmarshaler interface, +// Unmarshal calls that value's UnmarshalCBOR method. +// +// Unmarshal decodes a CBOR byte string into a value implementing +// encoding.BinaryUnmarshaler. +// +// If a CBOR value is not appropriate for a given Go type, or if a CBOR number +// overflows the Go type, Unmarshal skips that field and completes the +// unmarshalling as best as it can. If no more serious errors are encountered, +// unmarshal returns an UnmarshalTypeError describing the earliest such error. +// In any case, it's not guaranteed that all the remaining fields following the +// problematic one will be unmarshaled into the target object. +// +// The CBOR null value unmarshals into a slice/map/pointer/interface by setting +// that Go value to nil. Because null is often used to mean "not present", +// unmarshalling a CBOR null into any other Go type has no effect on the value +// produces no error. +// +// Unmarshal ignores CBOR tag data and parses tagged data following CBOR tag. +func Unmarshal(data []byte, v interface{}) error { + return defaultDecMode.Unmarshal(data, v) +} + +// Unmarshaler is the interface implemented by types that can unmarshal a CBOR +// representation of themselves. The input can be assumed to be a valid encoding +// of a CBOR value. UnmarshalCBOR must copy the CBOR data if it wishes to retain +// the data after returning. +type Unmarshaler interface { + UnmarshalCBOR([]byte) error +} + +// InvalidUnmarshalError describes an invalid argument passed to Unmarshal. +type InvalidUnmarshalError struct { + Type reflect.Type +} + +func (e *InvalidUnmarshalError) Error() string { + if e.Type == nil { + return "cbor: Unmarshal(nil)" + } + if e.Type.Kind() != reflect.Ptr { + return "cbor: Unmarshal(non-pointer " + e.Type.String() + ")" + } + return "cbor: Unmarshal(nil " + e.Type.String() + ")" +} + +// UnmarshalTypeError describes a CBOR value that was not appropriate for a Go type. +type UnmarshalTypeError struct { + Value string // description of CBOR value + Type reflect.Type // type of Go value it could not be assigned to + Struct string // struct type containing the field + Field string // name of the field holding the Go value + errMsg string // additional error message (optional) +} + +func (e *UnmarshalTypeError) Error() string { + var s string + if e.Struct != "" || e.Field != "" { + s = "cbor: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String() + } else { + s = "cbor: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() + } + if e.errMsg != "" { + s += " (" + e.errMsg + ")" + } + return s +} + +// 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) +} + +// DupMapKeyMode specifies how to enforce duplicate map key. +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 < 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 < 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 < maxTagsMode +} + +// DecOptions specifies decoding options. +type DecOptions struct { + // DupMapKey specifies whether to enforce duplicate map key. + DupMapKey DupMapKeyMode + + // TimeTag specifies whether to check validity of time.Time (e.g. valid tag number and tag content type). + // For now, valid tag number means 0 or 1 as specified in RFC 7049 if the Go type is time.Time. + 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, 256]. + MaxNestedLevels int + + // MaxArrayElements specifies the max number of elements for CBOR arrays. + // Default is 128*1024=131072 and it can be set to [16, 134217728] + 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, 134217728] + 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 +} + +// DecMode returns DecMode with immutable options and no tags (safe for concurrency). +func (opts DecOptions) DecMode() (DecMode, error) { + return opts.decMode() +} + +// DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency). +func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error) { + if opts.TagsMd == TagsForbidden { + return nil, errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden") + } + if tags == nil { + return nil, errors.New("cbor: cannot create DecMode with nil value as TagSet") + } + + 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) { + if opts.TagsMd == TagsForbidden { + return nil, errors.New("cbor: cannot create DecMode with TagSet when TagsMd is TagsForbidden") + } + if tags == nil { + return nil, errors.New("cbor: cannot create DecMode with nil value as TagSet") + } + dm, err := opts.decMode() + if err != nil { + return nil, err + } + dm.tags = tags + return dm, nil +} + +const ( + defaultMaxArrayElements = 131072 + minMaxArrayElements = 16 + maxMaxArrayElements = 134217728 + + defaultMaxMapPairs = 131072 + minMaxMapPairs = 16 + maxMaxMapPairs = 134217728 +) + +func (opts DecOptions) decMode() (*decMode, error) { + 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.MaxNestedLevels == 0 { + opts.MaxNestedLevels = 32 + } else if opts.MaxNestedLevels < 4 || opts.MaxNestedLevels > 256 { + return nil, errors.New("cbor: invalid MaxNestedLevels " + strconv.Itoa(opts.MaxNestedLevels) + " (range is [4, 256])") + } + if opts.MaxArrayElements == 0 { + opts.MaxArrayElements = defaultMaxArrayElements + } else if opts.MaxArrayElements < minMaxArrayElements || opts.MaxArrayElements > maxMaxArrayElements { + return nil, errors.New("cbor: invalid MaxArrayElements " + strconv.Itoa(opts.MaxArrayElements) + " (range is [" + strconv.Itoa(minMaxArrayElements) + ", " + strconv.Itoa(maxMaxArrayElements) + "])") + } + if opts.MaxMapPairs == 0 { + opts.MaxMapPairs = defaultMaxMapPairs + } else if opts.MaxMapPairs < minMaxMapPairs || opts.MaxMapPairs > maxMaxMapPairs { + return nil, errors.New("cbor: invalid MaxMapPairs " + strconv.Itoa(opts.MaxMapPairs) + " (range is [" + strconv.Itoa(minMaxMapPairs) + ", " + strconv.Itoa(maxMaxMapPairs) + "])") + } + dm := decMode{ + dupMapKey: opts.DupMapKey, + timeTag: opts.TimeTag, + maxNestedLevels: opts.MaxNestedLevels, + maxArrayElements: opts.MaxArrayElements, + maxMapPairs: opts.MaxMapPairs, + indefLength: opts.IndefLength, + tagsMd: opts.TagsMd, + } + return &dm, nil +} + +// DecMode is the main interface for CBOR decoding. +type DecMode interface { + Unmarshal(data []byte, v interface{}) error + NewDecoder(r io.Reader) *Decoder + DecOptions() DecOptions +} + +type decMode struct { + tags tagProvider + dupMapKey DupMapKeyMode + timeTag DecTagMode + maxNestedLevels int + maxArrayElements int + maxMapPairs int + indefLength IndefLengthMode + tagsMd TagsMode +} + +var defaultDecMode, _ = DecOptions{}.decMode() + +// DecOptions returns user specified options used to create this DecMode. +func (dm *decMode) DecOptions() DecOptions { + return DecOptions{ + DupMapKey: dm.dupMapKey, + TimeTag: dm.timeTag, + MaxNestedLevels: dm.maxNestedLevels, + MaxArrayElements: dm.maxArrayElements, + MaxMapPairs: dm.maxMapPairs, + IndefLength: dm.indefLength, + TagsMd: dm.tagsMd, + } +} + +// Unmarshal parses the CBOR-encoded data and stores the result in the value +// pointed to by v using dm DecMode. If v is nil or not a pointer, Unmarshal +// returns an error. +// +// See the documentation for Unmarshal for details. +func (dm *decMode) Unmarshal(data []byte, v interface{}) error { + d := decodeState{data: data, dm: dm} + return d.value(v) +} + +// NewDecoder returns a new decoder that reads from r using dm DecMode. +func (dm *decMode) NewDecoder(r io.Reader) *Decoder { + return &Decoder{r: r, d: decodeState{dm: dm}} +} + +type decodeState struct { + data []byte + off int // next read offset in data + dm *decMode +} + +func (d *decodeState) value(v interface{}) error { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Ptr || rv.IsNil() { + return &InvalidUnmarshalError{reflect.TypeOf(v)} + } + + off := d.off // Save offset before data validation + err := d.valid() + d.off = off // Restore offset + if err != nil { + return err + } + + rv = rv.Elem() + + if rv.Kind() == reflect.Interface && rv.NumMethod() == 0 { + // Fast path to decode to empty interface without retrieving typeInfo. + iv, err := d.parse() + if iv != nil { + rv.Set(reflect.ValueOf(iv)) + } + return err + } + + return d.parseToValue(rv, getTypeInfo(rv.Type())) +} + +type cborType uint8 + +const ( + cborTypePositiveInt cborType = 0x00 + cborTypeNegativeInt cborType = 0x20 + cborTypeByteString cborType = 0x40 + cborTypeTextString cborType = 0x60 + cborTypeArray cborType = 0x80 + cborTypeMap cborType = 0xa0 + cborTypeTag cborType = 0xc0 + cborTypePrimitives cborType = 0xe0 +) + +func (t cborType) String() string { + switch t { + case cborTypePositiveInt: + return "positive integer" + case cborTypeNegativeInt: + return "negative integer" + case cborTypeByteString: + return "byte string" + case cborTypeTextString: + return "UTF-8 text string" + case cborTypeArray: + return "array" + case cborTypeMap: + return "map" + case cborTypeTag: + return "tag" + case cborTypePrimitives: + return "primitives" + default: + return "Invalid type " + strconv.Itoa(int(t)) + } +} + +// parseToValue assumes data is well-formed, and does not perform bounds checking. +// This function is complicated because it's the main function that decodes CBOR data to reflect.Value. +func (d *decodeState) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo + // Create new value for the pointer v to point to if CBOR value is not nil/undefined. + if !d.nextCBORNil() { + for v.Kind() == reflect.Ptr { + if v.IsNil() { + if !v.CanSet() { + d.skip() + return errors.New("cbor: cannot set new value for " + v.Type().String()) + } + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + } + } + + if tInfo.spclType != specialTypeNone { + switch tInfo.spclType { + case specialTypeEmptyIface: + iv, err := d.parse() + if iv != nil { + v.Set(reflect.ValueOf(iv)) + } + return err + case specialTypeTag: + return d.parseToTag(v) + case specialTypeTime: + return d.parseToTime(v) + case specialTypeUnmarshalerIface: + return d.parseToUnmarshaler(v) + } + } + + // Check registered tag number + if tagItem := d.getRegisteredTagItem(tInfo.nonPtrType); tagItem != nil { + t := d.nextCBORType() + if t != cborTypeTag { + if tagItem.opts.DecTag == DecTagRequired { + d.skip() // Required tag number is absent, skip entire tag + return &UnmarshalTypeError{Value: t.String(), Type: tInfo.typ, errMsg: "expect CBOR tag value"} + } + } else if err := d.validRegisteredTagNums(tInfo.nonPtrType, tagItem.num); err != nil { + d.skip() // Skip tag content + return err + } + } + + t := d.nextCBORType() + + // Skip tag number(s) here to avoid recursion + if t == cborTypeTag { + d.getHead() + t = d.nextCBORType() + for t == cborTypeTag { + d.getHead() + t = d.nextCBORType() + } + } + + switch t { + case cborTypePositiveInt: + _, _, val := d.getHead() + return fillPositiveInt(t, val, v) + case cborTypeNegativeInt: + _, _, val := d.getHead() + if val > math.MaxInt64 { + return &UnmarshalTypeError{ + Value: t.String(), + Type: tInfo.nonPtrType, + errMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64", + } + } + nValue := int64(-1) ^ int64(val) + return fillNegativeInt(t, nValue, v) + case cborTypeByteString: + b := d.parseByteString() + return fillByteString(t, b, v) + case cborTypeTextString: + b, err := d.parseTextString() + if err != nil { + return err + } + return fillTextString(t, b, v) + case cborTypePrimitives: + _, ai, val := d.getHead() + if ai < 20 || ai == 24 { + return fillPositiveInt(t, val, v) + } + switch ai { + case 20, 21: + return fillBool(t, ai == 21, v) + case 22, 23: + return fillNil(t, v) + case 25: + f := float64(float16.Frombits(uint16(val)).Float32()) + return fillFloat(t, f, v) + case 26: + f := float64(math.Float32frombits(uint32(val))) + return fillFloat(t, f, v) + case 27: + f := math.Float64frombits(val) + return fillFloat(t, f, v) + } + case cborTypeArray: + if tInfo.nonPtrKind == reflect.Slice { + return d.parseArrayToSlice(v, tInfo) + } else if tInfo.nonPtrKind == reflect.Array { + return d.parseArrayToArray(v, tInfo) + } else if tInfo.nonPtrKind == reflect.Struct { + return d.parseArrayToStruct(v, tInfo) + } + d.skip() + return &UnmarshalTypeError{Value: t.String(), Type: tInfo.nonPtrType} + case cborTypeMap: + if tInfo.nonPtrKind == reflect.Struct { + return d.parseMapToStruct(v, tInfo) + } else if tInfo.nonPtrKind == reflect.Map { + return d.parseMapToMap(v, tInfo) + } + d.skip() + return &UnmarshalTypeError{Value: t.String(), Type: tInfo.nonPtrType} + } + return nil +} + +func (d *decodeState) parseToTag(v reflect.Value) error { + t := d.nextCBORType() + if t != cborTypeTag { + d.skip() + return &UnmarshalTypeError{Value: t.String(), Type: typeTag} + } + + // Unmarshal tag number + _, _, num := d.getHead() + + // Unmarshal tag content + content, err := d.parse() + if err != nil { + return err + } + + v.Set(reflect.ValueOf(Tag{num, content})) + return nil +} + +func (d *decodeState) parseToTime(v reflect.Value) error { + t := d.nextCBORType() + + // Verify that tag number or absent of tag number is acceptable to specified timeTag. + if t == cborTypeTag { + if d.dm.timeTag == DecTagIgnored { + // Skip tag number + d.getHead() + t = d.nextCBORType() + for t == cborTypeTag { + d.getHead() + t = d.nextCBORType() + } + } else { + // Read tag number + _, _, tagNum := d.getHead() + + // Verify tag number (0 or 1) is followed by appropriate tag content type. + t = d.nextCBORType() + switch tagNum { + case 0: + // Tag content (date/time text string in RFC 3339 format) must be string type. + if t != cborTypeTextString { + d.skip() + return errors.New("cbor: tag number 0 must be followed by text string, got " + t.String()) + } + case 1: + // Tag content (epoch date/time) must be uint, int, or float type. + if t != cborTypePositiveInt && t != cborTypeNegativeInt && (d.data[d.off] < 0xf9 || d.data[d.off] > 0xfb) { + d.skip() + return errors.New("cbor: tag number 1 must be followed by integer or floating-point number, got " + t.String()) + } + default: + d.skip() + return errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1") + } + } + } else { + if d.dm.timeTag == DecTagRequired { + d.skip() + return &UnmarshalTypeError{Value: t.String(), Type: typeTime, errMsg: "expect CBOR tag value"} + } + } + + switch t { + case cborTypePositiveInt: + _, _, val := d.getHead() + tm := time.Unix(int64(val), 0) + v.Set(reflect.ValueOf(tm)) + return nil + case cborTypeNegativeInt: + _, _, val := d.getHead() + if val > math.MaxInt64 { + return &UnmarshalTypeError{ + Value: t.String(), + Type: typeTime, + errMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64", + } + } + nValue := int64(-1) ^ int64(val) + tm := time.Unix(nValue, 0) + v.Set(reflect.ValueOf(tm)) + return nil + case cborTypeTextString: + b, err := d.parseTextString() + if err != nil { + return err + } + tm, err := time.Parse(time.RFC3339, string(b)) + if err != nil { + return errors.New("cbor: cannot set " + string(b) + " for time.Time: " + err.Error()) + } + v.Set(reflect.ValueOf(tm)) + return nil + case cborTypePrimitives: + _, ai, val := d.getHead() + var f float64 + switch ai { + case 22, 23: + v.Set(reflect.ValueOf(time.Time{})) + return nil + case 25: + f = float64(float16.Frombits(uint16(val)).Float32()) + case 26: + f = float64(math.Float32frombits(uint32(val))) + case 27: + f = math.Float64frombits(val) + default: + return &UnmarshalTypeError{Value: t.String(), Type: typeTime} + } + if math.IsNaN(f) || math.IsInf(f, 0) { + v.Set(reflect.ValueOf(time.Time{})) + return nil + } + f1, f2 := math.Modf(f) + tm := time.Unix(int64(f1), int64(f2*1e9)) + v.Set(reflect.ValueOf(tm)) + return nil + } + d.skip() + return &UnmarshalTypeError{Value: t.String(), Type: typeTime} +} + +// parseToUnmarshaler assumes data is well-formed, and does not perform bounds checking. +func (d *decodeState) parseToUnmarshaler(v reflect.Value) error { + if d.nextCBORNil() && v.Kind() == reflect.Ptr && v.IsNil() { + d.skip() + return nil + } + + if v.Kind() != reflect.Ptr && v.CanAddr() { + v = v.Addr() + } + if u, ok := v.Interface().(Unmarshaler); ok { + start := d.off + d.skip() + return u.UnmarshalCBOR(d.data[start:d.off]) + } + d.skip() + return errors.New("cbor: failed to assert " + v.Type().String() + " as cbor.Unmarshaler") +} + +// parse assumes data is well-formed, and does not perform bounds checking. +func (d *decodeState) parse() (interface{}, error) { + t := d.nextCBORType() + switch t { + case cborTypePositiveInt: + _, _, val := d.getHead() + return val, nil + case cborTypeNegativeInt: + _, _, val := d.getHead() + if val > math.MaxInt64 { + return nil, &UnmarshalTypeError{ + Value: t.String(), + Type: reflect.TypeOf([]interface{}(nil)).Elem(), + errMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64", + } + } + nValue := int64(-1) ^ int64(val) + return nValue, nil + case cborTypeByteString: + return d.parseByteString(), nil + case cborTypeTextString: + b, err := d.parseTextString() + if err != nil { + return nil, err + } + return string(b), nil + case cborTypeTag: + _, _, tagNum := d.getHead() + nt := d.nextCBORType() + content, err := d.parse() + if err != nil { + return nil, err + } + switch tagNum { + case 0: + // Tag content should be date/time text string in RFC 3339 format. + s, ok := content.(string) + if !ok { + return nil, errors.New("cbor: tag number 0 must be followed by text string, got " + nt.String()) + } + tm, err := time.Parse(time.RFC3339, s) + if err != nil { + return nil, errors.New("cbor: cannot set " + s + " for time.Time: " + err.Error()) + } + return tm, nil + case 1: + // Tag content should be epoch date/time. + switch content := content.(type) { + case uint64: + return time.Unix(int64(content), 0), nil + case int64: + return time.Unix(content, 0), nil + case float64: + f1, f2 := math.Modf(content) + return time.Unix(int64(f1), int64(f2*1e9)), nil + default: + return nil, errors.New("cbor: tag number 1 must be followed by integer or floating-point number, got " + nt.String()) + } + } + return Tag{tagNum, content}, nil + case cborTypePrimitives: + _, ai, val := d.getHead() + if ai < 20 || ai == 24 { + return val, nil + } + switch ai { + case 20, 21: + return (ai == 21), nil + case 22, 23: + return nil, nil + case 25: + f := float64(float16.Frombits(uint16(val)).Float32()) + return f, nil + case 26: + f := float64(math.Float32frombits(uint32(val))) + return f, nil + case 27: + f := math.Float64frombits(val) + return f, nil + } + case cborTypeArray: + return d.parseArray() + case cborTypeMap: + return d.parseMap() + } + return nil, nil +} + +// parseByteString parses CBOR encoded byte string. It returns a byte slice +// pointing to a copy of parsed data. +func (d *decodeState) parseByteString() []byte { + _, ai, val := d.getHead() + if ai != 31 { + b := make([]byte, int(val)) + copy(b, d.data[d.off:d.off+int(val)]) + d.off += int(val) + return b + } + // Process indefinite length string chunks. + b := []byte{} + for !d.foundBreak() { + _, _, val = d.getHead() + b = append(b, d.data[d.off:d.off+int(val)]...) + d.off += int(val) + } + return b +} + +// parseTextString parses CBOR encoded text string. It does not return a string +// to prevent creating an extra copy of string. Caller should wrap returned +// byte slice as string when needed. +// +// parseStruct() uses parseTextString() to improve memory and performance, +// compared with using parse(reflect.Value). parse(reflect.Value) sets +// reflect.Value with parsed string, while parseTextString() returns zero-copy []byte. +func (d *decodeState) parseTextString() ([]byte, error) { + _, ai, val := d.getHead() + if ai != 31 { + b := d.data[d.off : d.off+int(val)] + d.off += int(val) + if !utf8.Valid(b) { + return nil, &SemanticError{"cbor: invalid UTF-8 string"} + } + return b, nil + } + // Process indefinite length string chunks. + b := []byte{} + for !d.foundBreak() { + _, _, val = d.getHead() + x := d.data[d.off : d.off+int(val)] + d.off += int(val) + if !utf8.Valid(x) { + for !d.foundBreak() { + d.skip() // Skip remaining chunk on error + } + return nil, &SemanticError{"cbor: invalid UTF-8 string"} + } + b = append(b, x...) + } + return b, nil +} + +func (d *decodeState) parseArray() ([]interface{}, error) { + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + if !hasSize { + count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance + } + v := make([]interface{}, count) + var e interface{} + var err, lastErr error + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + if e, lastErr = d.parse(); lastErr != nil { + if err == nil { + err = lastErr + } + continue + } + v[i] = e + } + return v, err +} + +func (d *decodeState) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error { + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + if !hasSize { + count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance + } + if count == 0 { + v.Set(reflect.MakeSlice(tInfo.nonPtrType, 0, 0)) + } + if v.IsNil() || v.Cap() < count { + v.Set(reflect.MakeSlice(tInfo.nonPtrType, count, count)) + } + v.SetLen(count) + var err error + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + if lastErr := d.parseToValue(v.Index(i), tInfo.elemTypeInfo); lastErr != nil { + if err == nil { + err = lastErr + } + } + } + return err +} + +func (d *decodeState) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error { + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + gi := 0 + vLen := v.Len() + var err error + for ci := 0; (hasSize && ci < count) || (!hasSize && !d.foundBreak()); ci++ { + if gi < vLen { + // Read CBOR array element and set array element + if lastErr := d.parseToValue(v.Index(gi), tInfo.elemTypeInfo); lastErr != nil { + if err == nil { + err = lastErr + } + } + gi++ + } else { + d.skip() // Skip remaining CBOR array element + } + } + // Set remaining Go array elements to zero values. + if gi < vLen { + zeroV := reflect.Zero(tInfo.elemTypeInfo.typ) + for ; gi < vLen; gi++ { + v.Index(gi).Set(zeroV) + } + } + return err +} + +func (d *decodeState) parseMap() (map[interface{}]interface{}, error) { + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + m := make(map[interface{}]interface{}) + var k, e interface{} + var err, lastErr error + keyCount := 0 + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + // Parse CBOR map key. + if k, lastErr = d.parse(); lastErr != nil { + if err == nil { + err = lastErr + } + d.skip() + continue + } + + // Detect if CBOR map key can be used as Go map key. + kkind := reflect.ValueOf(k).Kind() + if tag, ok := k.(Tag); ok { + kkind = tag.contentKind() + } + if !isHashableKind(kkind) { + if err == nil { + err = errors.New("cbor: invalid map key type: " + kkind.String()) + } + d.skip() + continue + } + + // Parse CBOR map value. + if e, lastErr = d.parse(); lastErr != nil { + if err == nil { + err = lastErr + } + continue + } + + // Add key-value pair to Go map. + m[k] = e + + // Detect duplicate map key. + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + newKeyCount := len(m) + if newKeyCount == keyCount { + m[k] = nil + err = &DupMapKeyError{k, i} + i++ + // skip the rest of the map + for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + d.skip() // Skip map key + d.skip() // Skip map value + } + return m, err + } + keyCount = newKeyCount + } + } + return m, err +} + +func (d *decodeState) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + if v.IsNil() { + mapsize := count + if !hasSize { + mapsize = 0 + } + v.Set(reflect.MakeMapWithSize(tInfo.nonPtrType, mapsize)) + } + keyType, eleType := tInfo.keyTypeInfo.typ, tInfo.elemTypeInfo.typ + reuseKey, reuseEle := isImmutableKind(tInfo.keyTypeInfo.kind), isImmutableKind(tInfo.elemTypeInfo.kind) + var keyValue, eleValue, zeroKeyValue, zeroEleValue reflect.Value + keyIsInterfaceType := keyType == typeIntf // If key type is interface{}, need to check if key value is hashable. + var err, lastErr error + keyCount := v.Len() + var existingKeys map[interface{}]bool // Store existing map keys, used for detecting duplicate map key. + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + existingKeys = make(map[interface{}]bool, keyCount) + if keyCount > 0 { + vKeys := v.MapKeys() + for i := 0; i < len(vKeys); i++ { + existingKeys[vKeys[i].Interface()] = true + } + } + } + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + // Parse CBOR map key. + if !keyValue.IsValid() { + keyValue = reflect.New(keyType).Elem() + } else if !reuseKey { + if !zeroKeyValue.IsValid() { + zeroKeyValue = reflect.Zero(keyType) + } + keyValue.Set(zeroKeyValue) + } + if lastErr = d.parseToValue(keyValue, tInfo.keyTypeInfo); lastErr != nil { + if err == nil { + err = lastErr + } + d.skip() + continue + } + + // Detect if CBOR map key can be used as Go map key. + if keyIsInterfaceType { + kkind := keyValue.Elem().Kind() + if keyValue.Elem().IsValid() { + if tag, ok := keyValue.Elem().Interface().(Tag); ok { + kkind = tag.contentKind() + } + } + if !isHashableKind(kkind) { + if err == nil { + err = errors.New("cbor: invalid map key type: " + kkind.String()) + } + d.skip() + continue + } + } + + // Parse CBOR map value. + if !eleValue.IsValid() { + eleValue = reflect.New(eleType).Elem() + } else if !reuseEle { + if !zeroEleValue.IsValid() { + zeroEleValue = reflect.Zero(eleType) + } + eleValue.Set(zeroEleValue) + } + if lastErr := d.parseToValue(eleValue, tInfo.elemTypeInfo); lastErr != nil { + if err == nil { + err = lastErr + } + continue + } + + // Add key-value pair to Go map. + v.SetMapIndex(keyValue, eleValue) + + // Detect duplicate map key. + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + newKeyCount := v.Len() + if newKeyCount == keyCount { + kvi := keyValue.Interface() + if !existingKeys[kvi] { + v.SetMapIndex(keyValue, reflect.New(eleType).Elem()) + err = &DupMapKeyError{kvi, i} + i++ + // skip the rest of the map + for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + d.skip() // skip map key + d.skip() // skip map value + } + return err + } + delete(existingKeys, kvi) + } + keyCount = newKeyCount + } + } + return err +} + +func (d *decodeState) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error { + structType := getDecodingStructType(tInfo.nonPtrType) + if structType.err != nil { + return structType.err + } + + if !structType.toArray { + t := d.nextCBORType() + d.skip() + return &UnmarshalTypeError{ + Value: t.String(), + Type: tInfo.nonPtrType, + errMsg: "cannot decode CBOR array to struct without toarray option", + } + } + + start := d.off + t, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + if !hasSize { + count = d.numOfItemsUntilBreak() // peek ahead to get array size + } + if count != len(structType.fields) { + d.off = start + d.skip() + return &UnmarshalTypeError{ + Value: t.String(), + Type: tInfo.typ, + errMsg: "cannot decode CBOR array to struct with different number of elements", + } + } + var err error + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + f := structType.fields[i] + fv, lastErr := fieldByIndex(v, f.idx) + if lastErr != nil { + if err == nil { + err = lastErr + } + d.skip() + continue + } + if lastErr := d.parseToValue(fv, f.typInfo); lastErr != nil { + if err == nil { + if typeError, ok := lastErr.(*UnmarshalTypeError); ok { + typeError.Struct = tInfo.typ.String() + typeError.Field = f.name + err = typeError + } else { + err = lastErr + } + } + } + } + return err +} + +// parseMapToStruct needs to be fast so gocyclo can be ignored for now. +func (d *decodeState) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo + structType := getDecodingStructType(tInfo.nonPtrType) + if structType.err != nil { + return structType.err + } + + if structType.toArray { + t := d.nextCBORType() + d.skip() + return &UnmarshalTypeError{ + Value: t.String(), + Type: tInfo.nonPtrType, + errMsg: "cannot decode CBOR map to struct with toarray option", + } + } + + foundFldIdx := make([]bool, len(structType.fields)) + _, ai, val := d.getHead() + hasSize := (ai != 31) + count := int(val) + var err, lastErr error + keyCount := 0 + var mapKeys map[interface{}]struct{} // Store map keys, used for detecting duplicate map key. + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + mapKeys = make(map[interface{}]struct{}, len(structType.fields)) + } + for j := 0; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { + var f *field + var k interface{} // Used by duplicate map key detection + + t := d.nextCBORType() + if t == cborTypeTextString { + var keyBytes []byte + keyBytes, lastErr = d.parseTextString() + if lastErr != nil { + if err == nil { + err = lastErr + } + d.skip() // skip value + continue + } + + keyLen := len(keyBytes) + // Find field with exact match + for i := 0; i < len(structType.fields); i++ { + fld := structType.fields[i] + if !foundFldIdx[i] && len(fld.name) == keyLen && fld.name == string(keyBytes) { + f = fld + foundFldIdx[i] = true + break + } + } + // Find field with case-insensitive match + if f == nil { + keyString := string(keyBytes) + for i := 0; i < len(structType.fields); i++ { + fld := structType.fields[i] + if !foundFldIdx[i] && len(fld.name) == keyLen && strings.EqualFold(fld.name, keyString) { + f = fld + foundFldIdx[i] = true + break + } + } + } + + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + k = string(keyBytes) + } + } else if t <= cborTypeNegativeInt { // uint/int + var nameAsInt int64 + + if t == cborTypePositiveInt { + _, _, val := d.getHead() + nameAsInt = int64(val) + } else { + _, _, val := d.getHead() + if val > math.MaxInt64 { + if err == nil { + err = &UnmarshalTypeError{ + Value: t.String(), + Type: reflect.TypeOf(int64(0)), + errMsg: "-1-" + strconv.FormatUint(val, 10) + " overflows Go's int64", + } + } + d.skip() // skip value + continue + } + nameAsInt = int64(-1) ^ int64(val) + } + + // Find field + for i := 0; i < len(structType.fields); i++ { + fld := structType.fields[i] + if !foundFldIdx[i] && fld.keyAsInt && fld.nameAsInt == nameAsInt { + f = fld + foundFldIdx[i] = true + break + } + } + + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + k = nameAsInt + } + } else { + if err == nil { + err = &UnmarshalTypeError{ + Value: t.String(), + Type: reflect.TypeOf(""), + errMsg: "map key is of type " + t.String() + " and cannot be used to match struct field name", + } + } + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + // parse key + k, lastErr = d.parse() + if lastErr != nil { + d.skip() // skip value + continue + } + // Detect if CBOR map key can be used as Go map key. + kkind := reflect.ValueOf(k).Kind() + if tag, ok := k.(Tag); ok { + kkind = tag.contentKind() + } + if !isHashableKind(kkind) { + d.skip() // skip value + continue + } + } else { + d.skip() // skip key + } + } + + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + mapKeys[k] = struct{}{} + newKeyCount := len(mapKeys) + if newKeyCount == keyCount { + err = &DupMapKeyError{k, j} + d.skip() // skip value + j++ + // skip the rest of the map + for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { + d.skip() + d.skip() + } + return err + } + keyCount = newKeyCount + } + + if f == nil { + d.skip() // Skip value + continue + } + // reflect.Value.FieldByIndex() panics at nil pointer to unexported + // anonymous field. fieldByIndex() returns error. + fv, lastErr := fieldByIndex(v, f.idx) + if lastErr != nil { + if err == nil { + err = lastErr + } + d.skip() + continue + } + if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil { + if err == nil { + if typeError, ok := lastErr.(*UnmarshalTypeError); ok { + typeError.Struct = tInfo.nonPtrType.String() + typeError.Field = f.name + err = typeError + } else { + err = lastErr + } + } + } + } + return err +} + +// validRegisteredTagNums verifies that tag numbers match registered tag numbers of type t. +// validRegisteredTagNums assumes next CBOR data type is tag. It scans all tag numbers, and stops at tag content. +func (d *decodeState) validRegisteredTagNums(t reflect.Type, registeredTagNums []uint64) error { + // Scan until next cbor data is tag content. + tagNums := make([]uint64, 0, 2) + for d.nextCBORType() == cborTypeTag { + _, _, val := d.getHead() + tagNums = append(tagNums, val) + } + + // Verify that tag numbers match registered tag numbers of type t + if len(tagNums) != len(registeredTagNums) { + return &WrongTagError{t, registeredTagNums, tagNums} + } + for i, n := range registeredTagNums { + if n != tagNums[i] { + return &WrongTagError{t, registeredTagNums, tagNums} + } + } + return nil +} + +func (d *decodeState) getRegisteredTagItem(vt reflect.Type) *tagItem { + if d.dm.tags != nil { + return d.dm.tags.get(vt) + } + return nil +} + +// skip moves data offset to the next item. skip assumes data is well-formed, +// and does not perform bounds checking. +func (d *decodeState) skip() { + t, ai, val := d.getHead() + + if ai == 31 { + switch t { + case cborTypeByteString, cborTypeTextString, cborTypeArray, cborTypeMap: + for { + if d.data[d.off] == 0xff { + d.off++ + return + } + d.skip() + } + } + } + + switch t { + case cborTypeByteString, cborTypeTextString: + d.off += int(val) + case cborTypeArray: + for i := 0; i < int(val); i++ { + d.skip() + } + case cborTypeMap: + for i := 0; i < int(val)*2; i++ { + d.skip() + } + case cborTypeTag: + d.skip() + } +} + +// getHead assumes data is well-formed, and does not perform bounds checking. +func (d *decodeState) getHead() (t cborType, ai byte, val uint64) { + t = cborType(d.data[d.off] & 0xe0) + ai = d.data[d.off] & 0x1f + val = uint64(ai) + d.off++ + + if ai < 24 { + return + } + if ai == 24 { + val = uint64(d.data[d.off]) + d.off++ + return + } + if ai == 25 { + val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+2])) + d.off += 2 + return + } + if ai == 26 { + val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+4])) + d.off += 4 + return + } + if ai == 27 { + val = binary.BigEndian.Uint64(d.data[d.off : d.off+8]) + d.off += 8 + return + } + return +} + +func (d *decodeState) numOfItemsUntilBreak() int { + savedOff := d.off + i := 0 + for !d.foundBreak() { + d.skip() + i++ + } + d.off = savedOff + return i +} + +// foundBreak assumes data is well-formed, and does not perform bounds checking. +func (d *decodeState) foundBreak() bool { + if d.data[d.off] == 0xff { + d.off++ + return true + } + return false +} + +func (d *decodeState) reset(data []byte) { + d.data = data + d.off = 0 +} + +func (d *decodeState) nextCBORType() cborType { + return cborType(d.data[d.off] & 0xe0) +} + +func (d *decodeState) nextCBORNil() bool { + return d.data[d.off] == 0xf6 || d.data[d.off] == 0xf7 +} + +var ( + typeIntf = reflect.TypeOf([]interface{}(nil)).Elem() + typeTime = reflect.TypeOf(time.Time{}) + typeUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem() + typeBinaryUnmarshaler = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() +) + +func fillNil(t cborType, v reflect.Value) error { + switch v.Kind() { + case reflect.Slice, reflect.Map, reflect.Interface, reflect.Ptr: + v.Set(reflect.Zero(v.Type())) + return nil + } + return nil +} + +func fillPositiveInt(t cborType, val uint64, v reflect.Value) error { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if val > math.MaxInt64 { + return &UnmarshalTypeError{Value: t.String(), Type: v.Type(), errMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String()} + } + if v.OverflowInt(int64(val)) { + return &UnmarshalTypeError{Value: t.String(), Type: v.Type(), errMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String()} + } + v.SetInt(int64(val)) + return nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if v.OverflowUint(val) { + return &UnmarshalTypeError{Value: t.String(), Type: v.Type(), errMsg: strconv.FormatUint(val, 10) + " overflows " + v.Type().String()} + } + v.SetUint(val) + return nil + case reflect.Float32, reflect.Float64: + f := float64(val) + v.SetFloat(f) + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func fillNegativeInt(t cborType, val int64, v reflect.Value) error { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if v.OverflowInt(val) { + return &UnmarshalTypeError{Value: t.String(), Type: v.Type(), errMsg: strconv.FormatInt(val, 10) + " overflows " + v.Type().String()} + } + v.SetInt(val) + return nil + case reflect.Float32, reflect.Float64: + f := float64(val) + v.SetFloat(f) + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func fillBool(t cborType, val bool, v reflect.Value) error { + if v.Kind() == reflect.Bool { + v.SetBool(val) + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func fillFloat(t cborType, val float64, v reflect.Value) error { + switch v.Kind() { + case reflect.Float32, reflect.Float64: + if v.OverflowFloat(val) { + return &UnmarshalTypeError{ + Value: t.String(), + Type: v.Type(), + errMsg: strconv.FormatFloat(val, 'E', -1, 64) + " overflows " + v.Type().String(), + } + } + v.SetFloat(val) + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func fillByteString(t cborType, val []byte, v reflect.Value) error { + if reflect.PtrTo(v.Type()).Implements(typeBinaryUnmarshaler) { + if v.CanAddr() { + v = v.Addr() + if u, ok := v.Interface().(encoding.BinaryUnmarshaler); ok { + return u.UnmarshalBinary(val) + } + } + return errors.New("cbor: cannot set new value for " + v.Type().String()) + } + if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 { + v.SetBytes(val) + return nil + } + if v.Kind() == reflect.Array && v.Type().Elem().Kind() == reflect.Uint8 { + vLen := v.Len() + i := 0 + for ; i < vLen && i < len(val); i++ { + v.Index(i).SetUint(uint64(val[i])) + } + // Set remaining Go array elements to zero values. + if i < vLen { + zeroV := reflect.Zero(reflect.TypeOf(byte(0))) + for ; i < vLen; i++ { + v.Index(i).Set(zeroV) + } + } + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func fillTextString(t cborType, val []byte, v reflect.Value) error { + if v.Kind() == reflect.String { + v.SetString(string(val)) + return nil + } + return &UnmarshalTypeError{Value: t.String(), Type: v.Type()} +} + +func isImmutableKind(k reflect.Kind) bool { + switch k { + case reflect.Bool, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, + reflect.String: + return true + default: + return false + } +} + +func isHashableKind(k reflect.Kind) bool { + switch k { + case reflect.Slice, reflect.Map, reflect.Func: + return false + default: + return true + } +} + +// fieldByIndex returns the nested field corresponding to the index. It +// allocates pointer to struct field if it is nil and settable. +// reflect.Value.FieldByIndex() panics at nil pointer to unexported anonymous +// field. This function returns error. +func fieldByIndex(v reflect.Value, index []int) (reflect.Value, error) { + for _, i := range index { + if v.Kind() == reflect.Ptr && v.Type().Elem().Kind() == reflect.Struct { + if v.IsNil() { + if !v.CanSet() { + return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String()) + } + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + } + v = v.Field(i) + } + return v, nil +} diff --git a/vendor/github.com/fxamacker/cbor/v2/doc.go b/vendor/github.com/fxamacker/cbor/v2/doc.go new file mode 100644 index 0000000000..fbb65a5aa9 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/doc.go @@ -0,0 +1,109 @@ +// Copyright (c) Faye Amacker. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +/* +Package cbor is a fast & safe CBOR encoder & decoder (RFC 7049) with a +standard API + toarray & keyasint struct tags, CBOR tags, float64->32->16, +CTAP2 & Canonical CBOR, duplicate map key options, and is customizable via +simple API. + +CBOR encoding options allow "preferred serialization" by encoding integers and floats +to their smallest forms (like float16) when values fit. + +Struct tags like "keyasint", "toarray" and "omitempty" makes CBOR data smaller. + +For example, "toarray" makes struct fields encode to array elements. And "keyasint" +makes struct fields encode to elements of CBOR map with int keys. + +Basics + +Function signatures identical to encoding/json include: + + Marshal, Unmarshal, NewEncoder, NewDecoder, encoder.Encode, decoder.Decode. + +Codec functions are available at package-level (using defaults) or by creating modes +from options at runtime. + +"Mode" in this API means definite way of encoding or decoding. Specifically, EncMode or DecMode. + +EncMode and DecMode interfaces are created from EncOptions or DecOptions structs. For example, + + em := cbor.EncOptions{...}.EncMode() + em := cbor.CanonicalEncOptions().EncMode() + em := cbor.CTAP2EncOptions().EncMode() + +Modes use immutable options to avoid side-effects and simplify concurrency. Behavior of modes +won't accidentally change at runtime after they're created. + +Modes are intended to be reused and are safe for concurrent use. + +EncMode and DecMode Interfaces + + // EncMode interface uses immutable options and is safe for concurrent use. + type EncMode interface { + Marshal(v interface{}) ([]byte, error) + NewEncoder(w io.Writer) *Encoder + EncOptions() EncOptions // returns copy of options + } + + // DecMode interface uses immutable options and is safe for concurrent use. + type DecMode interface { + Unmarshal(data []byte, v interface{}) error + NewDecoder(r io.Reader) *Decoder + DecOptions() DecOptions // returns copy of options + } + +Using Default Encoding Mode + + b, err := cbor.Marshal(v) + + encoder := cbor.NewEncoder(w) + err = encoder.Encode(v) + +Using Default Decoding Mode + + err := cbor.Unmarshal(b, &v) + + decoder := cbor.NewDecoder(r) + err = decoder.Decode(&v) + +Creating and Using Encoding Modes + + // Create EncOptions using either struct literal or a function. + opts := cbor.CanonicalEncOptions() + + // If needed, modify encoding options + opts.Time = cbor.TimeUnix + + // Create reusable EncMode interface with immutable options, safe for concurrent use. + em, err := opts.EncMode() + + // Use EncMode like encoding/json, with same function signatures. + b, err := em.Marshal(v) + // or + encoder := em.NewEncoder(w) + err := encoder.Encode(v) + +Default Options + +Default encoding options are listed at https://github.com/fxamacker/cbor#api + +Struct Tags + +Struct tags like `cbor:"name,omitempty"` and `json:"name,omitempty"` work as expected. +If both struct tags are specified then `cbor` is used. + +Struct tags like "keyasint", "toarray", and "omitempty" make it easy to use +very compact formats like COSE and CWT (CBOR Web Tokens) with structs. + +For example, "toarray" makes struct fields encode to array elements. And "keyasint" +makes struct fields encode to elements of CBOR map with int keys. + +https://raw.githubusercontent.com/fxamacker/images/master/cbor/v2.0.0/cbor_easy_api.png + +Tests and Fuzzing + +Over 375 tests are included in this package. Cover-guided fuzzing is handled by a separate package: +fxamacker/cbor-fuzz. +*/ +package cbor diff --git a/vendor/github.com/fxamacker/cbor/v2/encode.go b/vendor/github.com/fxamacker/cbor/v2/encode.go new file mode 100644 index 0000000000..de52b54598 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/encode.go @@ -0,0 +1,1292 @@ +// 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() ([]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 + + // TimeTag allows time.Time to be encoded with a tag number. + // RFC3339 format gets tag number 0, and numeric epoch time tag number 1. + TimeTag EncTagMode + + // IndefLength specifies whether to allow indefinite length CBOR items. + IndefLength IndefLengthMode + + // TagsMd specifies whether to allow CBOR tags (major type 6). + TagsMd TagsMode +} + +// 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, + IndefLength: IndefLengthForbidden, + } +} + +// 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, + IndefLength: IndefLengthForbidden, + TagsMd: TagsForbidden, + } +} + +// 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, + IndefLength: IndefLengthForbidden, + } +} + +// 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 EncMode with immutable options and no tags (safe for concurrency). +func (opts EncOptions) EncMode() (EncMode, error) { + return opts.encMode() +} + +// EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency). +func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error) { + if opts.TagsMd == TagsForbidden { + return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden") + } + if tags == nil { + return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet") + } + em, err := opts.encMode() + 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.EncTag != EncTagNone { + ts[contentType] = tag + } + } + syncTags.RUnlock() + if len(ts) > 0 { + em.tags = ts + } + return em, nil +} + +// EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency). +func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error) { + if opts.TagsMd == TagsForbidden { + return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden") + } + if tags == nil { + return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet") + } + em, err := opts.encMode() + if err != nil { + return nil, err + } + em.tags = tags + return em, nil +} + +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))) + } + 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.TagsMd == TagsForbidden && opts.TimeTag == EncTagRequired { + return nil, errors.New("cbor: cannot set TagsMd to TagsForbidden when TimeTag is EncTagRequired") + } + em := encMode{ + sort: opts.Sort, + shortestFloat: opts.ShortestFloat, + nanConvert: opts.NaNConvert, + infConvert: opts.InfConvert, + time: opts.Time, + timeTag: opts.TimeTag, + indefLength: opts.IndefLength, + tagsMd: opts.TagsMd, + } + 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 { + tags tagProvider + sort SortMode + shortestFloat ShortestFloatMode + nanConvert NaNConvertMode + infConvert InfConvertMode + time TimeMode + timeTag EncTagMode + indefLength IndefLengthMode + tagsMd TagsMode +} + +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, + TimeTag: em.timeTag, + IndefLength: em.indefLength, + TagsMd: em.tagsMd, + } +} + +func (em *encMode) encTagBytes(t reflect.Type) []byte { + if em.tags != nil { + if tagItem := em.tags.get(t); tagItem != nil { + return tagItem.cborTagNum + } + } + return nil +} + +// 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() + + if err := encode(e, em, reflect.ValueOf(v)); 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) 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) error { + if !v.IsValid() { + // v is zero value + e.Write(cborNil) + return nil + } + vt := v.Type() + f := getEncodeFunc(vt) + if f == nil { + return &UnsupportedTypeError{vt} + } + + return f(e, em, v) +} + +func encodeBool(e *encodeState, em *encMode, v reflect.Value) error { + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + b := cborFalse + if v.Bool() { + b = cborTrue + } + e.Write(b) + return nil +} + +func encodeInt(e *encodeState, em *encMode, v reflect.Value) error { + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + i := v.Int() + if i >= 0 { + encodeHead(e, byte(cborTypePositiveInt), uint64(i)) + return nil + } + i = i*(-1) - 1 + encodeHead(e, byte(cborTypeNegativeInt), uint64(i)) + return nil +} + +func encodeUint(e *encodeState, em *encMode, v reflect.Value) error { + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + encodeHead(e, byte(cborTypePositiveInt), v.Uint()) + return nil +} + +func encodeFloat(e *encodeState, em *encMode, v reflect.Value) error { + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + 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)) + e.Write(e.scratch[:9]) + return nil + } + + 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)) + e.Write(e.scratch[:3]) + return nil + } + } + + // 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)) + e.Write(e.scratch[:5]) + return nil +} + +func encodeInf(e *encodeState, em *encMode, v reflect.Value) error { + f64 := v.Float() + if em.infConvert == InfConvertFloat16 { + if f64 > 0 { + e.Write(cborPositiveInfinity) + } else { + e.Write(cborNegativeInfinity) + } + return nil + } + if v.Kind() == reflect.Float64 { + return encodeFloat64(e, f64) + } + return encodeFloat32(e, float32(f64)) +} + +func encodeNaN(e *encodeState, em *encMode, v reflect.Value) error { + switch em.nanConvert { + case NaNConvert7e00: + e.Write(cborNaN) + return nil + + 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) error { + e.scratch[0] = byte(cborTypePrimitives) | byte(25) + binary.BigEndian.PutUint16(e.scratch[1:], uint16(f16)) + e.Write(e.scratch[:3]) + return nil +} + +func encodeFloat32(e *encodeState, f32 float32) error { + e.scratch[0] = byte(cborTypePrimitives) | byte(26) + binary.BigEndian.PutUint32(e.scratch[1:], math.Float32bits(f32)) + e.Write(e.scratch[:5]) + return nil +} + +func encodeFloat64(e *encodeState, f64 float64) error { + e.scratch[0] = byte(cborTypePrimitives) | byte(27) + binary.BigEndian.PutUint64(e.scratch[1:], math.Float64bits(f64)) + e.Write(e.scratch[:9]) + return nil +} + +func encodeByteString(e *encodeState, em *encMode, v reflect.Value) error { + vk := v.Kind() + if vk == reflect.Slice && v.IsNil() { + e.Write(cborNil) + return nil + } + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + slen := v.Len() + if slen == 0 { + return e.WriteByte(byte(cborTypeByteString)) + } + encodeHead(e, byte(cborTypeByteString), uint64(slen)) + if vk == reflect.Array { + for i := 0; i < slen; i++ { + e.WriteByte(byte(v.Index(i).Uint())) + } + return nil + } + e.Write(v.Bytes()) + return nil +} + +func encodeString(e *encodeState, em *encMode, v reflect.Value) error { + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + s := v.String() + encodeHead(e, byte(cborTypeTextString), uint64(len(s))) + e.WriteString(s) + return nil +} + +// Assuming that arrayEncoder.f != nil +type arrayEncoder struct { + f encodeFunc +} + +func (ae arrayEncoder) encodeArray(e *encodeState, em *encMode, v reflect.Value) error { + if v.Kind() == reflect.Slice && v.IsNil() { + e.Write(cborNil) + return nil + } + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + alen := v.Len() + if alen == 0 { + return e.WriteByte(byte(cborTypeArray)) + } + encodeHead(e, byte(cborTypeArray), uint64(alen)) + for i := 0; i < alen; i++ { + if err := ae.f(e, em, v.Index(i)); err != nil { + return err + } + } + return nil +} + +// Assuming that arrayEncoder.kf and arrayEncoder.ef are not nil +type mapEncoder struct { + kf, ef encodeFunc +} + +func (me mapEncoder) encodeMap(e *encodeState, em *encMode, v reflect.Value) error { + if v.IsNil() { + e.Write(cborNil) + return nil + } + if b := em.encTagBytes(v.Type()); b != nil { + e.Write(b) + } + mlen := v.Len() + if mlen == 0 { + return e.WriteByte(byte(cborTypeMap)) + } + if em.sort != SortNone { + return me.encodeMapCanonical(e, em, v) + } + encodeHead(e, byte(cborTypeMap), uint64(mlen)) + iter := v.MapRange() + for iter.Next() { + if err := me.kf(e, em, iter.Key()); err != nil { + return err + } + if err := me.ef(e, em, iter.Value()); err != nil { + return err + } + } + return 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) error { + 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++ { + off := kve.Len() + if err := me.kf(kve, em, iter.Key()); err != nil { + putEncodeState(kve) + putKeyValues(kvsp) + return err + } + n1 := kve.Len() - off + if err := me.ef(kve, em, iter.Value()); err != nil { + putEncodeState(kve) + putKeyValues(kvsp) + return err + } + n2 := kve.Len() - off + // Save key and keyvalue length to create slice later. + kvs[i] = keyValue{keyLen: n1, keyValueLen: 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}) + } + + encodeHead(e, byte(cborTypeMap), uint64(len(kvs))) + for i := 0; i < len(kvs); i++ { + e.Write(kvs[i].keyValueCBORData) + } + + putEncodeState(kve) + putKeyValues(kvsp) + return nil +} + +func encodeStructToArray(e *encodeState, em *encMode, v reflect.Value, flds fields) error { + encodeHead(e, byte(cborTypeArray), uint64(len(flds))) +FieldLoop: + for i := 0; i < len(flds); i++ { + f := flds[i] + fv := v + for k, n := range f.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) + } + if err := f.ef(e, em, fv); err != nil { + return err + } + } + return nil +} + +func encodeFixedLengthStruct(e *encodeState, em *encMode, v reflect.Value, flds fields) error { + encodeHead(e, byte(cborTypeMap), uint64(len(flds))) + + for i := 0; i < len(flds); i++ { + f := flds[i] + e.Write(f.cborName) + + fv := v.Field(f.idx[0]) + if err := f.ef(e, em, fv); err != nil { + return err + } + } + + return nil +} + +func encodeStruct(e *encodeState, em *encMode, v reflect.Value) error { + vt := v.Type() + structType := getEncodingStructType(vt) + if structType.err != nil { + return structType.err + } + + if b := em.encTagBytes(vt); b != nil { + e.Write(b) + } + + 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++ { + f := flds[i] + fv := v + for k, n := range f.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 f.omitEmpty && isEmptyValue(fv) { + continue + } + + kve.Write(f.cborName) + + if err := f.ef(kve, em, fv); err != nil { + putEncodeState(kve) + return err + } + kvcount++ + } + + encodeHead(e, byte(cborTypeMap), uint64(kvcount)) + e.Write(kve.Bytes()) + + putEncodeState(kve) + return nil +} + +func encodeIntf(e *encodeState, em *encMode, v reflect.Value) error { + if v.IsNil() { + e.Write(cborNil) + return nil + } + return encode(e, em, v.Elem()) +} + +func encodeTime(e *encodeState, em *encMode, v reflect.Value) error { + t := v.Interface().(time.Time) + if t.IsZero() { + e.Write(cborNil) // Even if tag is required, encode as CBOR null. + return nil + } + if em.timeTag == EncTagRequired { + tagNumber := 1 + if em.time == TimeRFC3339 || em.time == TimeRFC3339Nano { + tagNumber = 0 + } + encodeHead(e, byte(cborTypeTag), uint64(tagNumber)) + } + 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) error { + vt := v.Type() + m, ok := v.Interface().(encoding.BinaryMarshaler) + if !ok { + pv := reflect.New(vt) + pv.Elem().Set(v) + m = pv.Interface().(encoding.BinaryMarshaler) + } + data, err := m.MarshalBinary() + if err != nil { + return err + } + if b := em.encTagBytes(vt); b != nil { + e.Write(b) + } + encodeHead(e, byte(cborTypeByteString), uint64(len(data))) + e.Write(data) + return nil +} + +func encodeMarshalerType(e *encodeState, em *encMode, v reflect.Value) error { + if em.tagsMd == TagsForbidden && v.Type() == typeRawTag { + return errors.New("cbor: cannot encode cbor.RawTag when TagsMd is TagsForbidden") + } + m, ok := v.Interface().(Marshaler) + if !ok { + pv := reflect.New(v.Type()) + pv.Elem().Set(v) + m = pv.Interface().(Marshaler) + } + data, err := m.MarshalCBOR() + if err != nil { + return err + } + e.Write(data) + return nil +} + +func encodeTag(e *encodeState, em *encMode, v reflect.Value) error { + if em.tagsMd == TagsForbidden { + return errors.New("cbor: cannot encode cbor.Tag when TagsMd is TagsForbidden") + } + + t := v.Interface().(Tag) + + // Marshal tag number + encodeHead(e, byte(cborTypeTag), t.Number) + + // Marshal tag content + if err := encode(e, em, reflect.ValueOf(t.Content)); err != nil { + return err + } + + return nil +} + +func encodeHead(e *encodeState, t byte, n uint64) { + if n <= 23 { + e.WriteByte(t | byte(n)) + return + } + if n <= math.MaxUint8 { + e.scratch[0] = t | byte(24) + e.scratch[1] = byte(n) + e.Write(e.scratch[:2]) + return + } + if n <= math.MaxUint16 { + e.scratch[0] = t | byte(25) + binary.BigEndian.PutUint16(e.scratch[1:], uint16(n)) + e.Write(e.scratch[:3]) + return + } + if n <= math.MaxUint32 { + e.scratch[0] = t | byte(26) + binary.BigEndian.PutUint32(e.scratch[1:], uint32(n)) + e.Write(e.scratch[:5]) + return + } + e.scratch[0] = t | byte(27) + binary.BigEndian.PutUint64(e.scratch[1:], n) + e.Write(e.scratch[:9]) +} + +var ( + typeMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem() + typeBinaryMarshaler = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() +) + +func getEncodeFuncInternal(t reflect.Type) encodeFunc { + k := t.Kind() + if k == reflect.Ptr { + return getEncodeIndirectValueFunc(t) + } + if t == typeTag { + return encodeTag + } + if t == typeTime { + return encodeTime + } + if reflect.PtrTo(t).Implements(typeMarshaler) { + return encodeMarshalerType + } + if reflect.PtrTo(t).Implements(typeBinaryMarshaler) { + return encodeBinaryMarshalerType + } + switch k { + case reflect.Bool: + return encodeBool + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return encodeInt + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return encodeUint + case reflect.Float32, reflect.Float64: + return encodeFloat + case reflect.String: + return encodeString + case reflect.Slice, reflect.Array: + if t.Elem().Kind() == reflect.Uint8 { + return encodeByteString + } + f := getEncodeFunc(t.Elem()) + if f == nil { + return nil + } + return arrayEncoder{f: f}.encodeArray + case reflect.Map: + kf, ef := getEncodeFunc(t.Key()), getEncodeFunc(t.Elem()) + if kf == nil || ef == nil { + return nil + } + return mapEncoder{kf: kf, ef: ef}.encodeMap + case reflect.Struct: + return encodeStruct + case reflect.Interface: + return encodeIntf + } + return nil +} + +func getEncodeIndirectValueFunc(t reflect.Type) encodeFunc { + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + f := getEncodeFunc(t) + if f == nil { + return nil + } + return func(e *encodeState, em *encMode, v reflect.Value) error { + for v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + if v.Kind() == reflect.Ptr && v.IsNil() { + e.Write(cborNil) + return nil + } + return f(e, em, v) + } +} + +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + +func cannotFitFloat32(f64 float64) bool { + f32 := float32(f64) + return float64(f32) != f64 +} + +// float32NaNFromReflectValue extracts float32 NaN from reflect.Value while preserving NaN's quiet bit. +func float32NaNFromReflectValue(v reflect.Value) float32 { + // Keith Randall's workaround for issue https://github.com/golang/go/issues/36400 + p := reflect.New(v.Type()) + p.Elem().Set(v) + f32 := p.Convert(reflect.TypeOf((*float32)(nil))).Elem().Interface().(float32) + return f32 +} diff --git a/vendor/github.com/fxamacker/cbor/v2/go.mod b/vendor/github.com/fxamacker/cbor/v2/go.mod new file mode 100644 index 0000000000..49d74dbd92 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/go.mod @@ -0,0 +1,5 @@ +module github.com/fxamacker/cbor/v2 + +go 1.12 + +require github.com/x448/float16 v0.8.4 diff --git a/vendor/github.com/fxamacker/cbor/v2/go.sum b/vendor/github.com/fxamacker/cbor/v2/go.sum new file mode 100644 index 0000000000..dad8c4259e --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/go.sum @@ -0,0 +1,2 @@ +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= diff --git a/vendor/github.com/fxamacker/cbor/v2/stream.go b/vendor/github.com/fxamacker/cbor/v2/stream.go new file mode 100644 index 0000000000..62319333cf --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/stream.go @@ -0,0 +1,196 @@ +// Copyright (c) Faye Amacker. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +package cbor + +import ( + "errors" + "io" + "reflect" +) + +// Decoder reads and decodes CBOR values from an input stream. +type Decoder struct { + r io.Reader + buf []byte + d decodeState + off int // start of unread data in buf + bytesRead int +} + +// NewDecoder returns a new decoder that reads from r using the default decoding options. +func NewDecoder(r io.Reader) *Decoder { + return defaultDecMode.NewDecoder(r) +} + +// Decode reads the next CBOR-encoded value from its input and stores it in +// the value pointed to by v. +func (dec *Decoder) Decode(v interface{}) error { + if len(dec.buf) == dec.off { + if n, err := dec.read(); n == 0 { + return err + } + } + + dec.d.reset(dec.buf[dec.off:]) + err := dec.d.value(v) + dec.off += dec.d.off + dec.bytesRead += dec.d.off + if err != nil { + if err != io.ErrUnexpectedEOF { + return err + } + // Need to read more data. + if n, e := dec.read(); n == 0 { + return e + } + return dec.Decode(v) + } + return nil +} + +// NumBytesRead returns the number of bytes read. +func (dec *Decoder) NumBytesRead() int { + return dec.bytesRead +} + +func (dec *Decoder) read() (int, error) { + // Copy unread data over read data and reset off to 0. + if dec.off > 0 { + n := copy(dec.buf, dec.buf[dec.off:]) + dec.buf = dec.buf[:n] + dec.off = 0 + } + + // Grow buf if needed. + const minRead = 512 + if cap(dec.buf)-len(dec.buf) < minRead { + newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead) + copy(newBuf, dec.buf) + dec.buf = newBuf + } + + // Read from reader and reslice buf. + n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)]) + dec.buf = dec.buf[0 : len(dec.buf)+n] + return n, err +} + +// Encoder writes CBOR values to an output stream. +type Encoder struct { + w io.Writer + em *encMode + e *encodeState + indefTypes []cborType +} + +// NewEncoder returns a new encoder that writes to w using the default encoding options. +func NewEncoder(w io.Writer) *Encoder { + return defaultEncMode.NewEncoder(w) +} + +// Encode writes the CBOR encoding of v to the stream. +func (enc *Encoder) Encode(v interface{}) error { + if len(enc.indefTypes) > 0 && v != nil { + indefType := enc.indefTypes[len(enc.indefTypes)-1] + if indefType == cborTypeTextString { + k := reflect.TypeOf(v).Kind() + if k != reflect.String { + return errors.New("cbor: cannot encode item type " + k.String() + " for indefinite-length text string") + } + } else if indefType == cborTypeByteString { + t := reflect.TypeOf(v) + k := t.Kind() + if (k != reflect.Array && k != reflect.Slice) || t.Elem().Kind() != reflect.Uint8 { + return errors.New("cbor: cannot encode item type " + k.String() + " for indefinite-length byte string") + } + } + } + + err := encode(enc.e, enc.em, reflect.ValueOf(v)) + if err == nil { + _, err = enc.e.WriteTo(enc.w) + } + enc.e.Reset() + return err +} + +// StartIndefiniteByteString starts byte string encoding of indefinite length. +// Subsequent calls of (*Encoder).Encode() encodes definite length byte strings +// ("chunks") as one continguous string until EndIndefinite is called. +func (enc *Encoder) StartIndefiniteByteString() error { + return enc.startIndefinite(cborTypeByteString) +} + +// StartIndefiniteTextString starts text string encoding of indefinite length. +// Subsequent calls of (*Encoder).Encode() encodes definite length text strings +// ("chunks") as one continguous string until EndIndefinite is called. +func (enc *Encoder) StartIndefiniteTextString() error { + return enc.startIndefinite(cborTypeTextString) +} + +// StartIndefiniteArray starts array encoding of indefinite length. +// Subsequent calls of (*Encoder).Encode() encodes elements of the array +// until EndIndefinite is called. +func (enc *Encoder) StartIndefiniteArray() error { + return enc.startIndefinite(cborTypeArray) +} + +// StartIndefiniteMap starts array encoding of indefinite length. +// Subsequent calls of (*Encoder).Encode() encodes elements of the map +// until EndIndefinite is called. +func (enc *Encoder) StartIndefiniteMap() error { + return enc.startIndefinite(cborTypeMap) +} + +// EndIndefinite closes last opened indefinite length value. +func (enc *Encoder) EndIndefinite() error { + if len(enc.indefTypes) == 0 { + return errors.New("cbor: cannot encode \"break\" code outside indefinite length values") + } + _, err := enc.w.Write([]byte{0xff}) + if err == nil { + enc.indefTypes = enc.indefTypes[:len(enc.indefTypes)-1] + } + return err +} + +var cborIndefHeader = map[cborType][]byte{ + cborTypeByteString: {0x5f}, + cborTypeTextString: {0x7f}, + cborTypeArray: {0x9f}, + cborTypeMap: {0xbf}, +} + +func (enc *Encoder) startIndefinite(typ cborType) error { + if enc.em.indefLength == IndefLengthForbidden { + return &IndefiniteLengthError{typ} + } + _, err := enc.w.Write(cborIndefHeader[typ]) + if err == nil { + enc.indefTypes = append(enc.indefTypes, typ) + } + return err +} + +// RawMessage is a raw encoded CBOR value. It implements Marshaler and +// Unmarshaler interfaces and can be used to delay CBOR decoding or +// precompute a CBOR encoding. +type RawMessage []byte + +// MarshalCBOR returns m as the CBOR encoding of m. +func (m RawMessage) MarshalCBOR() ([]byte, error) { + if len(m) == 0 { + return cborNil, nil + } + return m, nil +} + +// UnmarshalCBOR sets *m to a copy of data. +func (m *RawMessage) UnmarshalCBOR(data []byte) error { + if m == nil { + return errors.New("cbor.RawMessage: UnmarshalCBOR on nil pointer") + } + *m = append((*m)[0:0], data...) + return nil +} diff --git a/vendor/github.com/fxamacker/cbor/v2/structfields.go b/vendor/github.com/fxamacker/cbor/v2/structfields.go new file mode 100644 index 0000000000..d73b719462 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/structfields.go @@ -0,0 +1,210 @@ +// Copyright (c) Faye Amacker. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +package cbor + +import ( + "reflect" + "sort" + "strings" +) + +type field struct { + name string + nameAsInt int64 // used to decoder to match field name with CBOR int + cborName []byte + idx []int + typ reflect.Type + ef encodeFunc + typInfo *typeInfo // used to decoder to reuse type info + tagged bool // used to choose dominant field (at the same level tagged fields dominate untagged fields) + omitEmpty bool // used to skip empty field + keyAsInt bool // used to encode/decode field name as int +} + +type fields []*field + +// indexFieldSorter sorts fields by field idx at each level, breaking ties with idx depth. +type indexFieldSorter struct { + fields fields +} + +func (x *indexFieldSorter) Len() int { + return len(x.fields) +} + +func (x *indexFieldSorter) Swap(i, j int) { + x.fields[i], x.fields[j] = x.fields[j], x.fields[i] +} + +func (x *indexFieldSorter) Less(i, j int) bool { + iIdx := x.fields[i].idx + jIdx := x.fields[j].idx + for k, d := range iIdx { + if k >= len(jIdx) { + // fields[j].idx is a subset of fields[i].idx. + return false + } + if d != jIdx[k] { + // fields[i].idx and fields[j].idx are different. + return d < jIdx[k] + } + } + // fields[i].idx is either the same as, or a subset of fields[j].idx. + return true +} + +// nameLevelAndTagFieldSorter sorts fields by field name, idx depth, and presence of tag. +type nameLevelAndTagFieldSorter struct { + fields fields +} + +func (x *nameLevelAndTagFieldSorter) Len() int { + return len(x.fields) +} + +func (x *nameLevelAndTagFieldSorter) Swap(i, j int) { + x.fields[i], x.fields[j] = x.fields[j], x.fields[i] +} + +func (x *nameLevelAndTagFieldSorter) Less(i, j int) bool { + if x.fields[i].name != x.fields[j].name { + return x.fields[i].name < x.fields[j].name + } + if len(x.fields[i].idx) != len(x.fields[j].idx) { + return len(x.fields[i].idx) < len(x.fields[j].idx) + } + if x.fields[i].tagged != x.fields[j].tagged { + return x.fields[i].tagged + } + return i < j // Field i and j have the same name, depth, and tagged status. Nothing else matters. +} + +// getFields returns a list of visible fields of struct type typ following Go +// visibility rules for struct fields. +func getFields(typ reflect.Type) (flds fields, structOptions string) { + // Inspired by typeFields() in stdlib's encoding/json/encode.go. + + var current map[reflect.Type][][]int // key: struct type, value: field index of this struct type at the same level + next := map[reflect.Type][][]int{typ: nil} + visited := map[reflect.Type]bool{} // Inspected struct type at less nested levels. + + for len(next) > 0 { + current, next = next, map[reflect.Type][][]int{} + + for structType, structIdx := range current { + if len(structIdx) > 1 { + continue // Fields of the same embedded struct type at the same level are ignored. + } + + if visited[structType] { + continue + } + visited[structType] = true + + var fieldIdx []int + if len(structIdx) > 0 { + fieldIdx = structIdx[0] + } + + for i := 0; i < structType.NumField(); i++ { + f := structType.Field(i) + ft := f.Type + + if ft.Kind() == reflect.Ptr { + ft = ft.Elem() + } + + exportable := f.PkgPath == "" + if f.Anonymous { + if !exportable && ft.Kind() != reflect.Struct { + // Nonexportable anonymous fields of non-struct type are ignored. + continue + } + // Nonexportable anonymous field of struct type can contain exportable fields for serialization. + } else if !exportable { + // Get special field "_" struct options + if f.Name == "_" { + tag := f.Tag.Get("cbor") + if tag != "-" { + structOptions = tag + } + } + // Nonexportable fields are ignored. + continue + } + + tag := f.Tag.Get("cbor") + if tag == "" { + tag = f.Tag.Get("json") + } + if tag == "-" { + continue + } + + idx := make([]int, len(fieldIdx)+1) + copy(idx, fieldIdx) + idx[len(fieldIdx)] = i + + tagged := len(tag) > 0 + tagFieldName, omitempty, keyasint := getFieldNameAndOptionsFromTag(tag) + + fieldName := tagFieldName + if tagFieldName == "" { + fieldName = f.Name + } + + if !f.Anonymous || ft.Kind() != reflect.Struct || len(tagFieldName) > 0 { + flds = append(flds, &field{name: fieldName, idx: idx, typ: f.Type, tagged: tagged, omitEmpty: omitempty, keyAsInt: keyasint}) + continue + } + + // f is anonymous struct of type ft. + next[ft] = append(next[ft], idx) + } + } + } + + sort.Sort(&nameLevelAndTagFieldSorter{flds}) + + // Keep visible fields. + visibleFields := flds[:0] + for i, j := 0, 0; i < len(flds); i = j { + name := flds[i].name + for j = i + 1; j < len(flds) && flds[j].name == name; j++ { + } + if j-i == 1 || len(flds[i].idx) < len(flds[i+1].idx) || (flds[i].tagged && !flds[i+1].tagged) { + // Keep the field if the field name is unique, or if the first field + // is at a less nested level, or if the first field is tagged and + // the second field is not. + visibleFields = append(visibleFields, flds[i]) + } + } + + sort.Sort(&indexFieldSorter{visibleFields}) + + return visibleFields, structOptions +} + +func getFieldNameAndOptionsFromTag(tag string) (name string, omitEmpty bool, keyAsInt bool) { + if tag == "" { + return + } + idx := strings.Index(tag, ",") + if idx == -1 { + return tag, false, false + } + if idx > 0 { + name = tag[:idx] + tag = tag[idx:] + } + s := ",omitempty" + if idx = strings.Index(tag, s); idx >= 0 && (len(tag) == idx+len(s) || tag[idx+len(s)] == ',') { + omitEmpty = true + } + s = ",keyasint" + if idx = strings.Index(tag, s); idx >= 0 && (len(tag) == idx+len(s) || tag[idx+len(s)] == ',') { + keyAsInt = true + } + return +} diff --git a/vendor/github.com/fxamacker/cbor/v2/tag.go b/vendor/github.com/fxamacker/cbor/v2/tag.go new file mode 100644 index 0000000000..a8121824d3 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/tag.go @@ -0,0 +1,247 @@ +package cbor + +import ( + "errors" + "fmt" + "reflect" + "sync" +) + +// Tag represents CBOR tag data, including tag number and unmarshaled tag content. +type Tag struct { + Number uint64 + Content interface{} +} + +func (t Tag) contentKind() reflect.Kind { + c := t.Content + for { + t, ok := c.(Tag) + if !ok { + break + } + c = t.Content + } + return reflect.ValueOf(c).Kind() +} + +// RawTag represents CBOR tag data, including tag number and raw tag content. +// RawTag implements Unmarshaler and Marshaler interfaces. +type RawTag struct { + Number uint64 + Content RawMessage +} + +// UnmarshalCBOR sets *t with tag number and raw tag content copied from data. +func (t *RawTag) UnmarshalCBOR(data []byte) error { + if t == nil { + return errors.New("cbor.RawTag: UnmarshalCBOR on nil pointer") + } + + d := decodeState{data: data, dm: defaultDecMode} + + // Unmarshal tag number. + typ, _, num := d.getHead() + if typ != cborTypeTag { + return &UnmarshalTypeError{Value: typ.String(), Type: typeRawTag} + } + t.Number = num + + // Unmarshal tag content. + c := d.data[d.off:] + t.Content = make([]byte, len(c)) + copy(t.Content, c) + return nil +} + +// MarshalCBOR returns CBOR encoding of t. +func (t RawTag) MarshalCBOR() ([]byte, error) { + e := getEncodeState() + encodeHead(e, byte(cborTypeTag), t.Number) + + buf := make([]byte, len(e.Bytes())+len(t.Content)) + n := copy(buf, e.Bytes()) + copy(buf[n:], t.Content) + + putEncodeState(e) + return buf, nil +} + +// DecTagMode specifies how decoder handles tag number. +type DecTagMode int + +const ( + // DecTagIgnored makes decoder ignore tag number (skips if present). + DecTagIgnored DecTagMode = iota + + // DecTagOptional makes decoder verify tag number if it's present. + DecTagOptional + + // DecTagRequired makes decoder verify tag number and tag number must be present. + DecTagRequired + + maxDecTagMode +) + +func (dtm DecTagMode) valid() bool { + return dtm < maxDecTagMode +} + +// EncTagMode specifies how encoder handles tag number. +type EncTagMode int + +const ( + // EncTagNone makes encoder not encode tag number. + EncTagNone EncTagMode = iota + + // EncTagRequired makes encoder encode tag number. + EncTagRequired + + maxEncTagMode +) + +func (etm EncTagMode) valid() bool { + return etm < maxEncTagMode +} + +// TagOptions specifies how encoder and decoder handle tag number. +type TagOptions struct { + DecTag DecTagMode + EncTag EncTagMode +} + +// TagSet is an interface to add and remove tag info. It is used by EncMode and DecMode +// to provide CBOR tag support. +type TagSet interface { + // Add adds given tag number(s), content type, and tag options to TagSet. + Add(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) error + + // Remove removes given tag content type from TagSet. + Remove(contentType reflect.Type) + + tagProvider +} + +type tagProvider interface { + get(t reflect.Type) *tagItem +} + +type tagItem struct { + num []uint64 + cborTagNum []byte + contentType reflect.Type + opts TagOptions +} + +type ( + tagSet map[reflect.Type]*tagItem + + syncTagSet struct { + sync.RWMutex + t tagSet + } +) + +func (t tagSet) get(typ reflect.Type) *tagItem { + return t[typ] +} + +// NewTagSet returns TagSet (safe for concurrency). +func NewTagSet() TagSet { + return &syncTagSet{t: make(map[reflect.Type]*tagItem)} +} + +// Add adds given tag number(s), content type, and tag options to TagSet. +func (t *syncTagSet) Add(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) error { + if contentType == nil { + return errors.New("cbor: cannot add nil content type to TagSet") + } + for contentType.Kind() == reflect.Ptr { + contentType = contentType.Elem() + } + tag, err := newTagItem(opts, contentType, num, nestedNum...) + if err != nil { + return err + } + t.Lock() + defer t.Unlock() + if _, ok := t.t[contentType]; ok { + return errors.New("cbor: content type " + contentType.String() + " already exists in TagSet") + } + t.t[contentType] = tag + return nil +} + +// Remove removes given tag content type from TagSet. +func (t *syncTagSet) Remove(contentType reflect.Type) { + for contentType.Kind() == reflect.Ptr { + contentType = contentType.Elem() + } + t.Lock() + delete(t.t, contentType) + t.Unlock() +} + +func (t *syncTagSet) get(typ reflect.Type) *tagItem { + t.RLock() + ti := t.t[typ] + t.RUnlock() + return ti +} + +func newTagItem(opts TagOptions, contentType reflect.Type, num uint64, nestedNum ...uint64) (*tagItem, error) { + if opts.DecTag == DecTagIgnored && opts.EncTag == EncTagNone { + return nil, errors.New("cbor: cannot add tag with DecTagIgnored and EncTagNone options to TagSet") + } + if contentType.PkgPath() == "" || contentType.Kind() == reflect.Interface { + return nil, errors.New("cbor: can only add named types to TagSet, got " + contentType.String()) + } + if contentType == typeTime { + return nil, errors.New("cbor: cannot add time.Time to TagSet, use EncOptions.TimeTag and DecOptions.TimeTag instead") + } + if contentType == typeTag { + return nil, errors.New("cbor: cannot add cbor.Tag to TagSet") + } + if contentType == typeRawTag { + return nil, errors.New("cbor: cannot add cbor.RawTag to TagSet") + } + if num == 0 || num == 1 { + return nil, errors.New("cbor: cannot add tag number 0 or 1 to TagSet, use EncOptions.TimeTag and DecOptions.TimeTag instead") + } + if reflect.PtrTo(contentType).Implements(typeMarshaler) && opts.EncTag != EncTagNone { + return nil, errors.New("cbor: cannot add cbor.Marshaler to TagSet with EncTag != EncTagNone") + } + if reflect.PtrTo(contentType).Implements(typeUnmarshaler) && opts.DecTag != DecTagIgnored { + return nil, errors.New("cbor: cannot add cbor.Unmarshaler to TagSet with DecTag != DecTagIgnored") + } + + te := tagItem{num: []uint64{num}, opts: opts, contentType: contentType} + te.num = append(te.num, nestedNum...) + + // Cache encoded tag numbers + e := getEncodeState() + for _, n := range te.num { + encodeHead(e, byte(cborTypeTag), n) + } + te.cborTagNum = make([]byte, e.Len()) + copy(te.cborTagNum, e.Bytes()) + putEncodeState(e) + + return &te, nil +} + +var ( + typeTag = reflect.TypeOf(Tag{}) + typeRawTag = reflect.TypeOf(RawTag{}) +) + +// WrongTagError describes mismatch between CBOR tag and registered tag. +type WrongTagError struct { + RegisteredType reflect.Type + RegisteredTagNum []uint64 + TagNum []uint64 +} + +func (e *WrongTagError) Error() string { + return fmt.Sprintf("cbor: wrong tag number for %s, got %v, expected %v", e.RegisteredType.String(), e.TagNum, e.RegisteredTagNum) +} diff --git a/vendor/github.com/fxamacker/cbor/v2/valid.go b/vendor/github.com/fxamacker/cbor/v2/valid.go new file mode 100644 index 0000000000..0d243bb691 --- /dev/null +++ b/vendor/github.com/fxamacker/cbor/v2/valid.go @@ -0,0 +1,300 @@ +// 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/binary" + "errors" + "io" + "strconv" +) + +// SyntaxError is a description of a CBOR syntax error. +type SyntaxError struct { + msg string +} + +func (e *SyntaxError) Error() string { return e.msg } + +// SemanticError is a description of a CBOR semantic error. +type SemanticError struct { + msg string +} + +func (e *SemanticError) Error() string { return e.msg } + +// MaxNestedLevelError indicates exceeded max nested level of any combination of CBOR arrays/maps/tags. +type MaxNestedLevelError struct { + maxNestedLevels int +} + +func (e *MaxNestedLevelError) Error() string { + return "cbor: exceeded max nested level " + strconv.Itoa(e.maxNestedLevels) +} + +// MaxArrayElementsError indicates exceeded max number of elements for CBOR arrays. +type MaxArrayElementsError struct { + maxArrayElements int +} + +func (e *MaxArrayElementsError) Error() string { + return "cbor: exceeded max number of elements " + strconv.Itoa(e.maxArrayElements) + " for CBOR array" +} + +// MaxMapPairsError indicates exceeded max number of key-value pairs for CBOR maps. +type MaxMapPairsError struct { + maxMapPairs int +} + +func (e *MaxMapPairsError) Error() string { + return "cbor: exceeded max number of key-value pairs " + strconv.Itoa(e.maxMapPairs) + " for CBOR map" +} + +// IndefiniteLengthError indicates found disallowed indefinite length items. +type IndefiniteLengthError struct { + t cborType +} + +func (e *IndefiniteLengthError) Error() string { + return "cbor: indefinite-length " + e.t.String() + " isn't allowed" +} + +// TagsMdError indicates found disallowed CBOR tags. +type TagsMdError struct { +} + +func (e *TagsMdError) Error() string { + return "cbor: CBOR tag isn't allowed" +} + +// valid checks whether CBOR data is complete and well-formed. +func (d *decodeState) valid() error { + if len(d.data) == d.off { + return io.EOF + } + _, err := d.validInternal(0) + return err +} + +// validInternal checks data's well-formedness and returns max depth and error. +func (d *decodeState) validInternal(depth int) (int, error) { + t, ai, val, err := d.validHead() + if err != nil { + return 0, err + } + + switch t { + case cborTypeByteString, cborTypeTextString: + if ai == 31 { + if d.dm.indefLength == IndefLengthForbidden { + return 0, &IndefiniteLengthError{t} + } + return d.validIndefiniteString(t, depth) + } + valInt := int(val) + if valInt < 0 { + // Detect integer overflow + return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, causing integer overflow") + } + if len(d.data)-d.off < valInt { // valInt+off may overflow integer + return 0, io.ErrUnexpectedEOF + } + d.off += valInt + case cborTypeArray, cborTypeMap: + depth++ + if depth > d.dm.maxNestedLevels { + return 0, &MaxNestedLevelError{d.dm.maxNestedLevels} + } + + if ai == 31 { + if d.dm.indefLength == IndefLengthForbidden { + return 0, &IndefiniteLengthError{t} + } + return d.validIndefiniteArrayOrMap(t, depth) + } + + valInt := int(val) + if valInt < 0 { + // Detect integer overflow + return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, it would cause integer overflow") + } + + if t == cborTypeArray { + if valInt > d.dm.maxArrayElements { + return 0, &MaxArrayElementsError{d.dm.maxArrayElements} + } + } else { + if valInt > d.dm.maxMapPairs { + return 0, &MaxMapPairsError{d.dm.maxMapPairs} + } + } + + count := 1 + if t == cborTypeMap { + count = 2 + } + maxDepth := depth + for j := 0; j < count; j++ { + for i := 0; i < valInt; i++ { + var dpt int + if dpt, err = d.validInternal(depth); err != nil { + return 0, err + } + if dpt > maxDepth { + maxDepth = dpt // Save max depth + } + } + } + depth = maxDepth + case cborTypeTag: + if d.dm.tagsMd == TagsForbidden { + return 0, &TagsMdError{} + } + + // Scan nested tag numbers to avoid recursion. + for { + if len(d.data) == d.off { // Tag number must be followed by tag content. + return 0, io.ErrUnexpectedEOF + } + if cborType(d.data[d.off]&0xe0) != cborTypeTag { + break + } + if _, _, _, err = d.validHead(); err != nil { + return 0, err + } + depth++ + if depth > d.dm.maxNestedLevels { + return 0, &MaxNestedLevelError{d.dm.maxNestedLevels} + } + } + // Check tag content. + return d.validInternal(depth) + } + return depth, nil +} + +// validIndefiniteString checks indefinite length byte/text string's well-formedness and returns max depth and error. +func (d *decodeState) validIndefiniteString(t cborType, depth int) (int, error) { + var err error + for { + if len(d.data) == d.off { + return 0, io.ErrUnexpectedEOF + } + if d.data[d.off] == 0xff { + d.off++ + break + } + // Peek ahead to get next type and indefinite length status. + nt := cborType(d.data[d.off] & 0xe0) + if t != nt { + return 0, &SyntaxError{"cbor: wrong element type " + nt.String() + " for indefinite-length " + t.String()} + } + if (d.data[d.off] & 0x1f) == 31 { + return 0, &SyntaxError{"cbor: indefinite-length " + t.String() + " chunk is not definite-length"} + } + if depth, err = d.validInternal(depth); err != nil { + return 0, err + } + } + return depth, nil +} + +// validIndefiniteArrayOrMap checks indefinite length array/map's well-formedness and returns max depth and error. +func (d *decodeState) validIndefiniteArrayOrMap(t cborType, depth int) (int, error) { + var err error + maxDepth := depth + i := 0 + for { + if len(d.data) == d.off { + return 0, io.ErrUnexpectedEOF + } + if d.data[d.off] == 0xff { + d.off++ + break + } + var dpt int + if dpt, err = d.validInternal(depth); err != nil { + return 0, err + } + if dpt > maxDepth { + maxDepth = dpt + } + i++ + if t == cborTypeArray { + if i > d.dm.maxArrayElements { + return 0, &MaxArrayElementsError{d.dm.maxArrayElements} + } + } else { + if i%2 == 0 && i/2 > d.dm.maxMapPairs { + return 0, &MaxMapPairsError{d.dm.maxMapPairs} + } + } + } + if t == cborTypeMap && i%2 == 1 { + return 0, &SyntaxError{"cbor: unexpected \"break\" code"} + } + return maxDepth, nil +} + +func (d *decodeState) validHead() (t cborType, ai byte, val uint64, err error) { + dataLen := len(d.data) - d.off + if dataLen == 0 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + + t = cborType(d.data[d.off] & 0xe0) + ai = d.data[d.off] & 0x1f + val = uint64(ai) + d.off++ + + if ai < 24 { + return t, ai, val, nil + } + if ai == 24 { + if dataLen < 2 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + val = uint64(d.data[d.off]) + d.off++ + if t == cborTypePrimitives && val < 32 { + return 0, 0, 0, &SyntaxError{"cbor: invalid simple value " + strconv.Itoa(int(val)) + " for type " + t.String()} + } + return t, ai, val, nil + } + if ai == 25 { + if dataLen < 3 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+2])) + d.off += 2 + return t, ai, val, nil + } + if ai == 26 { + if dataLen < 5 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+4])) + d.off += 4 + return t, ai, val, nil + } + if ai == 27 { + if dataLen < 9 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + val = binary.BigEndian.Uint64(d.data[d.off : d.off+8]) + d.off += 8 + return t, ai, val, nil + } + if ai == 31 { + switch t { + case cborTypePositiveInt, cborTypeNegativeInt, cborTypeTag: + return 0, 0, 0, &SyntaxError{"cbor: invalid additional information " + strconv.Itoa(int(ai)) + " for type " + t.String()} + case cborTypePrimitives: // 0xff (break code) should not be outside validIndefinite(). + return 0, 0, 0, &SyntaxError{"cbor: unexpected \"break\" code"} + } + return t, ai, val, nil + } + // ai == 28, 29, 30 + return 0, 0, 0, &SyntaxError{"cbor: invalid additional information " + strconv.Itoa(int(ai)) + " for type " + t.String()} +} |