{"id":13413800,"url":"https://github.com/fxamacker/cbor","last_synced_at":"2025-05-14T07:10:00.847Z","repository":{"id":38319744,"uuid":"186904487","full_name":"fxamacker/cbor","owner":"fxamacker","description":"CBOR codec (RFC 8949, RFC 8742) with CBOR tags, Go struct tag options (toarray, keyasint, omitempty, omitzero), float64/32/16, big.Int, and fuzz tested. ","archived":false,"fork":false,"pushed_at":"2025-05-04T14:28:06.000Z","size":1693,"stargazers_count":858,"open_issues_count":21,"forks_count":67,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-05-04T15:30:21.621Z","etag":null,"topics":["cbor","cbor-library","codec","cose","cwt","go","golang","json-alternative","rfc-8742","rfc-8949","serialization","std-94","tinygo"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fxamacker.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-05-15T21:22:15.000Z","updated_at":"2025-05-04T14:28:04.000Z","dependencies_parsed_at":"2023-02-19T04:16:09.349Z","dependency_job_id":"d2f514a0-25ce-49f0-ad20-30b63ef36a40","html_url":"https://github.com/fxamacker/cbor","commit_stats":null,"previous_names":["fxamacker/go-cbor"],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fxamacker%2Fcbor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fxamacker%2Fcbor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fxamacker%2Fcbor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fxamacker%2Fcbor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fxamacker","download_url":"https://codeload.github.com/fxamacker/cbor/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254092789,"owners_count":22013290,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cbor","cbor-library","codec","cose","cwt","go","golang","json-alternative","rfc-8742","rfc-8949","serialization","std-94","tinygo"],"created_at":"2024-07-30T20:01:49.642Z","updated_at":"2025-05-14T07:09:55.838Z","avatar_url":"https://github.com/fxamacker.png","language":"Go","readme":"\u003ch1\u003eCBOR Codec \u003ca href=\"https://pkg.go.dev/github.com/fxamacker/cbor/v2\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/fxamacker/images/refs/heads/master/cbor/go-logo-blue.svg\" alt=\"Go logo\" style=\"height: 1em;\" align=\"right\"\u003e\u003c/a\u003e\u003c/h1\u003e\n\n[fxamacker/cbor](https://github.com/fxamacker/cbor) is a library for encoding and decoding [CBOR](https://www.rfc-editor.org/info/std94) and [CBOR Sequences](https://www.rfc-editor.org/rfc/rfc8742.html).\n\nCBOR is a [trusted alternative](https://www.rfc-editor.org/rfc/rfc8949.html#name-comparison-of-other-binary-) to JSON, MessagePack, Protocol Buffers, etc.\u0026nbsp; CBOR is an Internet\u0026nbsp;Standard defined by [IETF\u0026nbsp;STD\u0026nbsp;94 (RFC\u0026nbsp;8949)](https://www.rfc-editor.org/info/std94) and is designed to be relevant for decades.\n\n`fxamacker/cbor` is used in projects by Arm Ltd., Cisco, EdgeX\u0026nbsp;Foundry, Flow Foundation, Fraunhofer\u0026#8209;AISEC, Kubernetes, Let's\u0026nbsp;Encrypt (ISRG), Linux\u0026nbsp;Foundation, Microsoft, Mozilla, Oasis\u0026nbsp;Protocol, Tailscale, Teleport, [etc](https://github.com/fxamacker/cbor#who-uses-fxamackercbor).\n\nSee [Quick\u0026nbsp;Start](#quick-start) and [Releases](https://github.com/fxamacker/cbor/releases/).  🆕 `UnmarshalFirst` and `DiagnoseFirst` can decode CBOR Sequences.  `MarshalToBuffer` and `UserBufferEncMode` accepts user-specified buffer.\n\n## fxamacker/cbor\n\n[![](https://github.com/fxamacker/cbor/workflows/ci/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3Aci)\n[![](https://github.com/fxamacker/cbor/workflows/cover%20%E2%89%A597%25/badge.svg)](https://github.com/fxamacker/cbor/actions?query=workflow%3A%22cover+%E2%89%A597%25%22)\n[![CodeQL](https://github.com/fxamacker/cbor/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/fxamacker/cbor/actions/workflows/codeql-analysis.yml)\n[![](https://img.shields.io/badge/fuzzing-passing-44c010)](#fuzzing-and-code-coverage)\n[![Go Report Card](https://goreportcard.com/badge/github.com/fxamacker/cbor)](https://goreportcard.com/report/github.com/fxamacker/cbor)\n[![](https://img.shields.io/ossf-scorecard/github.com/fxamacker/cbor?label=openssf%20scorecard)](https://github.com/fxamacker/cbor#fuzzing-and-code-coverage)\n\n`fxamacker/cbor` is a CBOR codec in full conformance with [IETF STD\u0026nbsp;94 (RFC\u0026nbsp;8949)](https://www.rfc-editor.org/info/std94). It also supports CBOR Sequences ([RFC\u0026nbsp;8742](https://www.rfc-editor.org/rfc/rfc8742.html)) and Extended Diagnostic Notation ([Appendix G of RFC\u0026nbsp;8610](https://www.rfc-editor.org/rfc/rfc8610.html#appendix-G)).\n\nFeatures include full support for CBOR tags, [Core Deterministic Encoding](https://www.rfc-editor.org/rfc/rfc8949.html#name-core-deterministic-encoding), duplicate map key detection, etc.\n\nAPI is mostly same as `encoding/json`, plus interfaces that simplify concurrency and CBOR options.\n\nDesign balances trade-offs between security, speed, concurrency, encoded data size, usability, etc.\n\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Highlights\u003c/summary\u003e\u003cp/\u003e\n\n__🚀\u0026nbsp; Speed__\n\nEncoding and decoding is fast without using Go's `unsafe` package.  Slower settings are opt-in.  Default limits allow very fast and memory efficient rejection of malformed CBOR data.\n\n__🔒\u0026nbsp; Security__\n\nDecoder has configurable limits that defend against malicious inputs.  Duplicate map key detection is supported.  By contrast, `encoding/gob` is [not designed to be hardened against adversarial inputs](https://pkg.go.dev/encoding/gob#hdr-Security).\n\nCodec passed multiple confidential security assessments in 2022.  No vulnerabilities found in subset of codec in a [nonconfidential security assessment](https://github.com/veraison/go-cose/blob/v1.0.0-rc.1/reports/NCC_Microsoft-go-cose-Report_2022-05-26_v1.0.pdf) prepared by NCC\u0026nbsp;Group for Microsoft\u0026nbsp;Corporation.\n\n__🗜️\u0026nbsp; Data Size__\n\nStruct tag options (`toarray`, `keyasint`, `omitempty`, `omitzero`) automatically reduce size of encoded structs. Encoding optionally shrinks float64→32→16 when values fit.\n\n__:jigsaw:\u0026nbsp; Usability__\n\nAPI is mostly same as `encoding/json` plus interfaces that simplify concurrency for CBOR options.  Encoding and decoding modes can be created at startup and reused by any goroutines.\n\nPresets include Core Deterministic Encoding, Preferred Serialization, CTAP2 Canonical CBOR, etc.\n\n__📆\u0026nbsp;  Extensibility__\n\nFeatures include CBOR [extension points](https://www.rfc-editor.org/rfc/rfc8949.html#section-7.1) (e.g. CBOR tags) and extensive settings.  API has interfaces that allow users to create custom encoding and decoding without modifying this library.\n\n\u003chr/\u003e\n\n\u003c/details\u003e\n\n### Secure Decoding with Configurable Settings\n\n`fxamacker/cbor` has configurable limits, etc. that defend against malicious CBOR data.\n\nNotably, `fxamacker/cbor` is fast at rejecting malformed CBOR data.\n\n\u003e [!NOTE]  \n\u003e Benchmarks rejecting 10 bytes of malicious CBOR data decoding to `[]byte`:\n\u003e \n\u003e | Codec | Speed (ns/op) | Memory | Allocs |\n\u003e | :---- | ------------: | -----: | -----: |\n\u003e | fxamacker/cbor 2.7.0 | 47 ± 7% | 32 B/op | 2 allocs/op |\n\u003e | ugorji/go 1.2.12 | 5878187 ± 3% | 67111556 B/op |  13 allocs/op |\n\u003e\n\u003e Faster hardware (overclocked DDR4 or DDR5) can reduce speed difference.\n\u003e \n\u003e \u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Benchmark details \u003c/summary\u003e\u003cp/\u003e\n\u003e \n\u003e Latest comparison for decoding CBOR data to Go `[]byte`:\n\u003e - Input: `[]byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}`\n\u003e - go1.22.7, linux/amd64, i5-13600K (DDR4-2933, disabled e-cores)\n\u003e - go test -bench=. -benchmem -count=20\n\u003e \n\u003e #### Prior comparisons\n\u003e \n\u003e | Codec | Speed (ns/op) | Memory | Allocs |\n\u003e | :---- | ------------: | -----: | -----: |\n\u003e | fxamacker/cbor 2.5.0-beta2 | 44.33 ± 2% | 32 B/op | 2 allocs/op |\n\u003e | fxamacker/cbor 0.1.0 - 2.4.0 | ~44.68 ± 6% | 32 B/op |  2 allocs/op |\n\u003e | ugorji/go 1.2.10 | 5524792.50 ± 3% | 67110491 B/op |  12 allocs/op |\n\u003e | ugorji/go 1.1.0 - 1.2.6 | 💥 runtime: | out of memory: | cannot allocate |\n\u003e \n\u003e - Input: `[]byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}`\n\u003e - go1.19.6, linux/amd64, i5-13600K (DDR4)\n\u003e - go test -bench=. -benchmem -count=20\n\u003e \n\u003e \u003c/details\u003e\n\nIn contrast, some codecs can crash or use excessive resources while decoding bad data.\n\n\u003e [!WARNING]  \n\u003e Go's `encoding/gob` is [not designed to be hardened against adversarial inputs](https://pkg.go.dev/encoding/gob#hdr-Security).\n\u003e \n\u003e \u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; gob fatal error (out of memory) 💥 decoding 181 bytes\u003c/summary\u003e\u003cp/\u003e\n\u003e\n\u003e ```Go\n\u003e // Example of encoding/gob having \"fatal error: runtime: out of memory\"\n\u003e // while decoding 181 bytes (all Go versions as of Dec. 8, 2024).\n\u003e package main\n\u003e import (\n\u003e \t\"bytes\"\n\u003e \t\"encoding/gob\"\n\u003e \t\"encoding/hex\"\n\u003e \t\"fmt\"\n\u003e )\n\u003e \n\u003e // Example data is from https://github.com/golang/go/issues/24446\n\u003e // (shortened to 181 bytes).\n\u003e const data = \"4dffb503010102303001ff30000109010130010800010130010800010130\" +\n\u003e \t\"01ffb80001014a01ffb60001014b01ff860001013001ff860001013001ff\" +\n\u003e \t\"860001013001ff860001013001ffb80000001eff850401010e3030303030\" +\n\u003e \t\"30303030303030303001ff3000010c0104000016ffb70201010830303030\" +\n\u003e \t\"3030303001ff3000010c000030ffb6040405fcff00303030303030303030\" +\n\u003e \t\"303030303030303030303030303030303030303030303030303030303030\" +\n\u003e \t\"30\"\n\u003e \n\u003e type X struct {\n\u003e \tJ *X\n\u003e \tK map[string]int\n\u003e }\n\u003e \n\u003e func main() {\n\u003e \traw, _ := hex.DecodeString(data)\n\u003e \tdecoder := gob.NewDecoder(bytes.NewReader(raw))\n\u003e \n\u003e \tvar x X\n\u003e \tdecoder.Decode(\u0026x) // fatal error: runtime: out of memory\n\u003e \tfmt.Println(\"Decoding finished.\")\n\u003e }\n\u003e ```\n\u003e\n\u003e\n\u003e \u003c/details\u003e\n\n### Smaller Encodings with Struct Tag Options\n\nStruct tags automatically reduce encoded size of structs and improve speed.\n\nWe can write less code by using struct tag options:\n- `toarray`: encode without field names (decode back to original struct)\n- `keyasint`: encode field names as integers (decode back to original struct)\n- `omitempty`: omit empty fields when encoding\n- `omitzero`: omit zero-value fields when encoding\n\n![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.3.0/cbor_struct_tags_api.svg?sanitize=1 \"CBOR API and Go Struct Tags\")\n\n\u003e [!NOTE]  \n\u003e  `fxamacker/cbor` can encode a 3-level nested Go struct to 1 byte!\n\u003e - `encoding/json`:  18 bytes of JSON\n\u003e - `fxamacker/cbor`:  1 byte of CBOR  \n\u003e\n\u003e \u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Encoding 3-level nested Go struct with omitempty\u003c/summary\u003e\u003cp/\u003e\n\u003e\n\u003e https://go.dev/play/p/YxwvfPdFQG2\n\u003e \n\u003e ```Go\n\u003e // Example encoding nested struct (with omitempty tag)\n\u003e // - encoding/json:  18 byte JSON\n\u003e // - fxamacker/cbor:  1 byte CBOR\n\u003e \n\u003e package main\n\u003e \n\u003e import (\n\u003e \t\"encoding/hex\"\n\u003e \t\"encoding/json\"\n\u003e \t\"fmt\"\n\u003e \n\u003e \t\"github.com/fxamacker/cbor/v2\"\n\u003e )\n\u003e \n\u003e type GrandChild struct {\n\u003e \tQuux int `json:\",omitempty\"`\n\u003e }\n\u003e \n\u003e type Child struct {\n\u003e \tBaz int        `json:\",omitempty\"`\n\u003e \tQux GrandChild `json:\",omitempty\"`\n\u003e }\n\u003e \n\u003e type Parent struct {\n\u003e \tFoo Child `json:\",omitempty\"`\n\u003e \tBar int   `json:\",omitempty\"`\n\u003e }\n\u003e \n\u003e func cb() {\n\u003e \tresults, _ := cbor.Marshal(Parent{})\n\u003e \tfmt.Println(\"hex(CBOR): \" + hex.EncodeToString(results))\n\u003e \n\u003e \ttext, _ := cbor.Diagnose(results) // Diagnostic Notation\n\u003e \tfmt.Println(\"DN: \" + text)\n\u003e }\n\u003e \n\u003e func js() {\n\u003e \tresults, _ := json.Marshal(Parent{})\n\u003e \tfmt.Println(\"hex(JSON): \" + hex.EncodeToString(results))\n\u003e \n\u003e \ttext := string(results) // JSON\n\u003e \tfmt.Println(\"JSON: \" + text)\n\u003e }\n\u003e \n\u003e func main() {\n\u003e \tcb()\n\u003e \tfmt.Println(\"-------------\")\n\u003e \tjs()\n\u003e }\n\u003e ```\n\u003e \n\u003e Output (DN is Diagnostic Notation):\n\u003e ```\n\u003e hex(CBOR): a0\n\u003e DN: {}\n\u003e -------------\n\u003e hex(JSON): 7b22466f6f223a7b22517578223a7b7d7d7d\n\u003e JSON: {\"Foo\":{\"Qux\":{}}}\n\u003e ```\n\u003e \n\u003e \u003c/details\u003e\n\n\n## Quick Start\n\n__Install__: `go get github.com/fxamacker/cbor/v2` and `import \"github.com/fxamacker/cbor/v2\"`.\n\n\u003e [!TIP]  \n\u003e\n\u003e Tinygo users can try beta/experimental branch [feature/cbor-tinygo-beta](https://github.com/fxamacker/cbor/tree/feature/cbor-tinygo-beta).\n\u003e\n\u003e \u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; More about tinygo feature branch\u003c/summary\u003e\n\u003e\n\u003e ### Tinygo\n\u003e\n\u003e Branch [feature/cbor-tinygo-beta](https://github.com/fxamacker/cbor/tree/feature/cbor-tinygo-beta) is based on fxamacker/cbor v2.7.0 and it can be compiled using tinygo v0.33 (also compiles with golang/go).\n\u003e\n\u003e It passes unit tests (with both go1.22 and tinygo v0.33) and is considered beta/experimental for tinygo.\n\u003e\n\u003e :warning: The `feature/cbor-tinygo-beta` branch does not get fuzz tested yet.\n\u003e\n\u003e Changes in this feature branch only affect tinygo compiled software.  Summary of changes:\n\u003e - default `DecOptions.MaxNestedLevels` is reduced to 16 (was 32).  User can specify higher limit but 24+ crashes tests when compiled with tinygo v0.33.\n\u003e - disabled decoding CBOR tag data to Go interface because tinygo v0.33 is missing needed feature.\n\u003e - encoding error message can be different when encoding function type.\n\u003e\n\u003e Related tinygo issues:\n\u003e - https://github.com/tinygo-org/tinygo/issues/4277\n\u003e - https://github.com/tinygo-org/tinygo/issues/4458\n\u003e\n\u003e \u003c/details\u003e\n\n\n### Key Points\n\nThis library can encode and decode CBOR (RFC 8949) and CBOR Sequences (RFC 8742).\n\n- __CBOR data item__ is a single piece of CBOR data and its structure may contain 0 or more nested data items.\n- __CBOR sequence__ is a concatenation of 0 or more encoded CBOR data items.\n\nConfigurable limits and options can be used to balance trade-offs.\n\n- Encoding and decoding modes are created from options (settings).\n- Modes can be created at startup and reused.\n- Modes are safe for concurrent use.\n\n### Default Mode\n\nPackage level functions only use this library's default settings.  \nThey provide the \"default mode\" of encoding and decoding.\n\n```go\n// API matches encoding/json for Marshal, Unmarshal, Encode, Decode, etc.\nb, err = cbor.Marshal(v)        // encode v to []byte b\nerr = cbor.Unmarshal(b, \u0026v)     // decode []byte b to v\ndecoder = cbor.NewDecoder(r)    // create decoder with io.Reader r\nerr = decoder.Decode(\u0026v)        // decode a CBOR data item to v\n\n// v2.7.0 added MarshalToBuffer() and UserBufferEncMode interface.\nerr = cbor.MarshalToBuffer(v, b) // encode v to b instead of using built-in buf pool.\n\n// v2.5.0 added new functions that return remaining bytes.\n\n// UnmarshalFirst decodes first CBOR data item and returns remaining bytes.\nrest, err = cbor.UnmarshalFirst(b, \u0026v)   // decode []byte b to v\n\n// DiagnoseFirst translates first CBOR data item to text and returns remaining bytes.\ntext, rest, err = cbor.DiagnoseFirst(b)  // decode []byte b to Diagnostic Notation text\n\n// NOTE: Unmarshal() returns ExtraneousDataError if there are remaining bytes, but\n// UnmarshalFirst() and DiagnoseFirst() allow trailing bytes.\n```\n\n\u003e [!IMPORTANT]  \n\u003e CBOR settings allow trade-offs between speed, security, encoding size, etc.\n\u003e\n\u003e - Different CBOR libraries may use different default settings.\n\u003e - CBOR-based formats or protocols usually require specific settings.\n\u003e\n\u003e For example, WebAuthn uses \"CTAP2 Canonical CBOR\" which is available as a preset.\n\n### Presets\n\nPresets can be used as-is or as a starting point for custom settings.\n\n```go\n// EncOptions is a struct of encoder settings.\nfunc CoreDetEncOptions() EncOptions              // RFC 8949 Core Deterministic Encoding\nfunc PreferredUnsortedEncOptions() EncOptions    // RFC 8949 Preferred Serialization\nfunc CanonicalEncOptions() EncOptions            // RFC 7049 Canonical CBOR\nfunc CTAP2EncOptions() EncOptions                // FIDO2 CTAP2 Canonical CBOR\n```\n\nPresets are used to create custom modes.\n\n### Custom Modes\n\nModes are created from settings. Once created, modes have immutable settings.\n\n💡 Create the mode at startup and reuse it. It is safe for concurrent use.\n\n```Go\n// Create encoding mode.\nopts := cbor.CoreDetEncOptions()   // use preset options as a starting point\nopts.Time = cbor.TimeUnix          // change any settings if needed\nem, err := opts.EncMode()          // create an immutable encoding mode\n\n// Reuse the encoding mode. It is safe for concurrent use.\n\n// API matches encoding/json.\nb, err := em.Marshal(v)            // encode v to []byte b\nencoder := em.NewEncoder(w)        // create encoder with io.Writer w\nerr := encoder.Encode(v)           // encode v to io.Writer w\n```\n\nDefault mode and custom modes automatically apply struct tags.\n\n### User Specified Buffer for Encoding (v2.7.0)\n\n`UserBufferEncMode` interface extends `EncMode` interface to add `MarshalToBuffer()`. It accepts a user-specified buffer instead of using built-in buffer pool.\n\n```Go\nem, err := myEncOptions.UserBufferEncMode() // create UserBufferEncMode mode\n\nvar buf bytes.Buffer\nerr = em.MarshalToBuffer(v, \u0026buf) // encode v to provided buf\n```\n\n### Struct Tags\n\nStruct tag options (`toarray`, `keyasint`, `omitempty`, `omitzero`) reduce encoded size of structs.\n\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Example encoding 3-level nested Go struct to 1 byte CBOR\u003c/summary\u003e\u003cp/\u003e\n\nhttps://go.dev/play/p/YxwvfPdFQG2\n\n```Go\n// Example encoding nested struct (with omitempty tag)\n// - encoding/json:  18 byte JSON\n// - fxamacker/cbor:  1 byte CBOR\npackage main\n\nimport (\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"github.com/fxamacker/cbor/v2\"\n)\n\ntype GrandChild struct {\n\tQuux int `json:\",omitempty\"`\n}\n\ntype Child struct {\n\tBaz int        `json:\",omitempty\"`\n\tQux GrandChild `json:\",omitempty\"`\n}\n\ntype Parent struct {\n\tFoo Child `json:\",omitempty\"`\n\tBar int   `json:\",omitempty\"`\n}\n\nfunc cb() {\n\tresults, _ := cbor.Marshal(Parent{})\n\tfmt.Println(\"hex(CBOR): \" + hex.EncodeToString(results))\n\n\ttext, _ := cbor.Diagnose(results) // Diagnostic Notation\n\tfmt.Println(\"DN: \" + text)\n}\n\nfunc js() {\n\tresults, _ := json.Marshal(Parent{})\n\tfmt.Println(\"hex(JSON): \" + hex.EncodeToString(results))\n\n\ttext := string(results) // JSON\n\tfmt.Println(\"JSON: \" + text)\n}\n\nfunc main() {\n\tcb()\n\tfmt.Println(\"-------------\")\n\tjs()\n}\n```\n\nOutput (DN is Diagnostic Notation):\n```\nhex(CBOR): a0\nDN: {}\n-------------\nhex(JSON): 7b22466f6f223a7b22517578223a7b7d7d7d\nJSON: {\"Foo\":{\"Qux\":{}}}\n```\n\n\u003chr/\u003e\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Example using struct tag options\u003c/summary\u003e\u003cp/\u003e\n\t\n![alt text](https://github.com/fxamacker/images/raw/master/cbor/v2.3.0/cbor_struct_tags_api.svg?sanitize=1 \"CBOR API and Go Struct Tags\")\n\n\u003c/details\u003e\n\nStruct tag options simplify use of CBOR-based protocols that require CBOR arrays or maps with integer keys.\n\n### CBOR Tags\n\nCBOR tags are specified in a `TagSet`.\n\nCustom modes can be created with a `TagSet` to handle CBOR tags.\n \n```go\nem, err := opts.EncMode()                  // no CBOR tags\nem, err := opts.EncModeWithTags(ts)        // immutable CBOR tags\nem, err := opts.EncModeWithSharedTags(ts)  // mutable shared CBOR tags\n```\n\n`TagSet` and modes using it are safe for concurrent use.  Equivalent API is available for `DecMode`.\n\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Example using TagSet and TagOptions\u003c/summary\u003e\u003cp/\u003e\n\n```go\n// Use signedCWT struct defined in \"Decoding CWT\" example.\n\n// Create TagSet (safe for concurrency).\ntags := cbor.NewTagSet()\n// Register tag COSE_Sign1 18 with signedCWT type.\ntags.Add(\t\n\tcbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, \n\treflect.TypeOf(signedCWT{}), \n\t18)\n\n// Create DecMode with immutable tags.\ndm, _ := cbor.DecOptions{}.DecModeWithTags(tags)\n\n// Unmarshal to signedCWT with tag support.\nvar v signedCWT\nif err := dm.Unmarshal(data, \u0026v); err != nil {\n\treturn err\n}\n\n// Create EncMode with immutable tags.\nem, _ := cbor.EncOptions{}.EncModeWithTags(tags)\n\n// Marshal signedCWT with tag number.\nif data, err := em.Marshal(v); err != nil {\n\treturn err\n}\n```\n\n\u003c/details\u003e\n\n### Functions and Interfaces\n\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Functions and interfaces at a glance\u003c/summary\u003e\u003cp/\u003e\n\nCommon functions with same API as `encoding/json`:  \n- `Marshal`, `Unmarshal`\n- `NewEncoder`, `(*Encoder).Encode`\n- `NewDecoder`, `(*Decoder).Decode`\n\nNOTE: `Unmarshal` will return `ExtraneousDataError` if there are remaining bytes\nbecause RFC 8949 treats CBOR data item with remaining bytes as malformed.\n- 💡 Use `UnmarshalFirst` to decode first CBOR data item and return any remaining bytes.\n\nOther useful functions: \n- `Diagnose`, `DiagnoseFirst` produce human-readable [Extended Diagnostic Notation](https://www.rfc-editor.org/rfc/rfc8610.html#appendix-G) from CBOR data.\n- `UnmarshalFirst` decodes first CBOR data item and return any remaining bytes.\n- `Wellformed` returns true if the the CBOR data item is well-formed.\n\nInterfaces identical or comparable to Go `encoding` packages include:  \n`Marshaler`, `Unmarshaler`, `BinaryMarshaler`, and `BinaryUnmarshaler`.\n\nThe `RawMessage` type can be used to delay CBOR decoding or precompute CBOR encoding.\n\n\u003c/details\u003e\n\n### Security Tips\n\n🔒 Use Go's `io.LimitReader` to limit size when decoding very large or indefinite size data.\n\nDefault limits may need to be increased for systems handling very large data (e.g. blockchains).\n\n`DecOptions` can be used to modify default limits for `MaxArrayElements`, `MaxMapPairs`, and `MaxNestedLevels`.\n\n## Status\n\nv2.8.0 (March 30, 2025) is a small release primarily to add `omitzero` option to struct field tags and fix bugs.   It passed fuzz tests (billions of executions) and is production quality.\n\nv2.8.0 and v2.7.1 fixes these 3 functions (when called directly by user apps) to use same error handling on bad inputs as `cbor.Unmarshal()`:\n- `ByteString.UnmarshalCBOR()`\n- `RawTag.UnmarshalCBOR()`\n- `SimpleValue.UnmarshalCBOR()`\n\nThe above 3 `UnmarshalCBOR()` functions were initially created for internal use and are deprecated now, so please use `Unmarshal()` or `UnmarshalFirst()` instead.  To preserve backward compatibility, these deprecated functions were added to fuzz tests and will not be removed in v2.\n\nThe minimum version of Go required to build:\n- v2.8.0 requires go 1.20.\n- v2.7.1 and older releases require go 1.17.\n\nFor more details, see [release notes](https://github.com/fxamacker/cbor/releases).\n\n### Prior Releases\n\nv2.7.0 (June 23, 2024) adds features and improvements that help large projects (e.g. Kubernetes) use CBOR as an alternative to JSON and Protocol Buffers. Other improvements include speedups, improved memory use, bug fixes, new serialization options, etc.   It passed fuzz tests (5+ billion executions) and is production quality.\n\n[v2.6.0](https://github.com/fxamacker/cbor/releases/tag/v2.6.0) (February 2024) adds important new features, optimizations, and bug fixes. It is especially useful to systems that need to convert data between CBOR and JSON.  New options and optimizations improve handling of bignum, integers, maps, and strings.\n\nv2.5.0 was released on Sunday, August 13, 2023 with new features and important bug fixes.  It is fuzz tested and production quality after extended beta [v2.5.0-beta](https://github.com/fxamacker/cbor/releases/tag/v2.5.0-beta) (Dec 2022) -\u003e [v2.5.0](https://github.com/fxamacker/cbor/releases/tag/v2.5.0) (Aug 2023).\n\n__IMPORTANT__:  👉 Before upgrading from v2.4 or older release, please read the notable changes highlighted in the release notes.  v2.5.0 is a large release with bug fixes to error handling for extraneous data in `Unmarshal`, etc. that should be reviewed before upgrading.\n\nSee [v2.5.0 release notes](https://github.com/fxamacker/cbor/releases/tag/v2.5.0) for list of new features, improvements, and bug fixes.\n\nSee [\"Version and API Changes\"](https://github.com/fxamacker/cbor#versions-and-api-changes) section for more info about version numbering, etc.\n\n\u003c!--\n\u003cdetails\u003e\u003csummary\u003e 🔎\u0026nbsp; Benchmark Comparison: v2.4.0 vs v2.5.0\u003c/summary\u003e\u003cp/\u003e\n\nTODO: Update to v2.4.0 vs 2.5.0 (not beta2).\n\nComparison of v2.4.0 vs v2.5.0-beta2 provided by @448 (edited to fit width).\n\nPR [#382](https://github.com/fxamacker/cbor/pull/382) returns buffer to pool in `Encode()`. It adds a bit of overhead to `Encode()` but `NewEncoder().Encode()` is a lot faster and uses less memory as shown here:\n\n```\n$ benchstat bench-v2.4.0.log bench-f9e6291.log \ngoos: linux\ngoarch: amd64\npkg: github.com/fxamacker/cbor/v2\ncpu: 12th Gen Intel(R) Core(TM) i7-12700H\n                                                     │ bench-v2.4.0.log │  bench-f9e6291.log                  │\n                                                     │      sec/op      │   sec/op     vs base                │\nNewEncoderEncode/Go_bool_to_CBOR_bool-20                   236.70n ± 2%   58.04n ± 1%  -75.48% (p=0.000 n=10)\nNewEncoderEncode/Go_uint64_to_CBOR_positive_int-20         238.00n ± 2%   63.93n ± 1%  -73.14% (p=0.000 n=10)\nNewEncoderEncode/Go_int64_to_CBOR_negative_int-20          238.65n ± 2%   64.88n ± 1%  -72.81% (p=0.000 n=10)\nNewEncoderEncode/Go_float64_to_CBOR_float-20               242.00n ± 2%   63.00n ± 1%  -73.97% (p=0.000 n=10)\nNewEncoderEncode/Go_[]uint8_to_CBOR_bytes-20               245.60n ± 1%   68.55n ± 1%  -72.09% (p=0.000 n=10)\nNewEncoderEncode/Go_string_to_CBOR_text-20                 243.20n ± 3%   68.39n ± 1%  -71.88% (p=0.000 n=10)\nNewEncoderEncode/Go_[]int_to_CBOR_array-20                 563.0n ± 2%    378.3n ± 0%  -32.81% (p=0.000 n=10)\nNewEncoderEncode/Go_map[string]string_to_CBOR_map-20       2.043µ ± 2%    1.906µ ± 2%   -6.75% (p=0.000 n=10)\ngeomean                                                    349.7n         122.7n       -64.92%\n\n                                                     │ bench-v2.4.0.log │    bench-f9e6291.log                │\n                                                     │       B/op       │    B/op     vs base                 │\nNewEncoderEncode/Go_bool_to_CBOR_bool-20                     128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_uint64_to_CBOR_positive_int-20           128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_int64_to_CBOR_negative_int-20            128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_float64_to_CBOR_float-20                 128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_[]uint8_to_CBOR_bytes-20                 128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_string_to_CBOR_text-20                   128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_[]int_to_CBOR_array-20                   128.0 ± 0%     0.0 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_map[string]string_to_CBOR_map-20         544.0 ± 0%   416.0 ± 0%   -23.53% (p=0.000 n=10)\ngeomean                                                      153.4                    ?                       ¹ ²\n¹ summaries must be \u003e0 to compute geomean\n² ratios must be \u003e0 to compute geomean\n\n                                                     │ bench-v2.4.0.log │    bench-f9e6291.log                │\n                                                     │    allocs/op     │ allocs/op   vs base                 │\nNewEncoderEncode/Go_bool_to_CBOR_bool-20                     2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_uint64_to_CBOR_positive_int-20           2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_int64_to_CBOR_negative_int-20            2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_float64_to_CBOR_float-20                 2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_[]uint8_to_CBOR_bytes-20                 2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_string_to_CBOR_text-20                   2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_[]int_to_CBOR_array-20                   2.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=10)\nNewEncoderEncode/Go_map[string]string_to_CBOR_map-20         28.00 ± 0%   26.00 ± 0%    -7.14% (p=0.000 n=10)\ngeomean                                                      2.782                    ?                       ¹ ²\n¹ summaries must be \u003e0 to compute geomean\n² ratios must be \u003e0 to compute geomean\n```\n\n\u003c/details\u003e\n--\u003e\n\n## Who uses fxamacker/cbor\n\n`fxamacker/cbor` is used in projects by Arm Ltd., Berlin Institute of Health at Charité, Chainlink, Cisco, Confidential\u0026nbsp;Computing\u0026nbsp;Consortium, ConsenSys, EdgeX\u0026nbsp;Foundry, F5, Flow\u0026nbsp;Foundation, Fraunhofer\u0026#8209;AISEC, IBM, Kubernetes, Let's\u0026nbsp;Encrypt\u0026nbsp;(ISRG), Linux\u0026nbsp;Foundation, Matrix.org, Microsoft, Mozilla, National\u0026nbsp;Cybersecurity\u0026nbsp;Agency\u0026nbsp;of\u0026nbsp;France\u0026nbsp;(govt), Netherlands\u0026nbsp;(govt), Oasis\u0026nbsp;Protocol, Smallstep, Tailscale, Taurus SA, Teleport, TIBCO, and others.\n\n`fxamacker/cbor` passed multiple confidential security assessments.  A [nonconfidential security assessment](https://github.com/veraison/go-cose/blob/v1.0.0-rc.1/reports/NCC_Microsoft-go-cose-Report_2022-05-26_v1.0.pdf) (prepared by NCC Group for Microsoft Corporation) includes a subset of fxamacker/cbor v2.4.0 in its scope.\n\n## Standards\n\n`fxamacker/cbor` is a CBOR codec in full conformance with [IETF STD\u0026nbsp;94 (RFC\u0026nbsp;8949)](https://www.rfc-editor.org/info/std94). It also supports CBOR Sequences ([RFC\u0026nbsp;8742](https://www.rfc-editor.org/rfc/rfc8742.html)) and Extended Diagnostic Notation ([Appendix G of RFC\u0026nbsp;8610](https://www.rfc-editor.org/rfc/rfc8610.html#appendix-G)).\n\nNotable CBOR features include:\n\n| CBOR Feature  | Description  |\n| :--- | :--- |\n| CBOR tags | API supports built-in and user-defined tags.  |\n| Preferred serialization | Integers encode to fewest bytes. Optional float64 → float32 → float16. |\n| Map key sorting | Unsorted, length-first (Canonical CBOR), and bytewise-lexicographic (CTAP2). |\n| Duplicate map keys | Always forbid for encoding and option to allow/forbid for decoding.   |\n| Indefinite length data | Option to allow/forbid for encoding and decoding. |\n| Well-formedness | Always checked and enforced. |\n| Basic validity checks | Optionally check UTF-8 validity and duplicate map keys. |\n| Security considerations | Prevent integer overflow and resource exhaustion (RFC 8949 Section 10). |\n\nKnown limitations are noted in the [Limitations section](#limitations). \n\nGo nil values for slices, maps, pointers, etc. are encoded as CBOR null.  Empty slices, maps, etc. are encoded as empty CBOR arrays and maps.\n\nDecoder checks for all required well-formedness errors, including all \"subkinds\" of syntax errors and too little data.\n\nAfter well-formedness is verified, basic validity errors are handled as follows:\n\n* Invalid UTF-8 string: Decoder has option to check and return invalid UTF-8 string error. This check is enabled by default.\n* Duplicate keys in a map: Decoder has options to ignore or enforce rejection of duplicate map keys.\n\nWhen 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.\n\nBy default, decoder treats time values of floating-point NaN and Infinity as if they are CBOR Null or CBOR Undefined.\n\n__Click to expand topic:__\n\n\u003cdetails\u003e\n \u003csummary\u003e 🔎\u0026nbsp; Duplicate Map Keys\u003c/summary\u003e\u003cp\u003e\n\nThis 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. \n\n`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.\n\n`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. \n\nAPF 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.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n \u003csummary\u003e 🔎\u0026nbsp; Tag Validity\u003c/summary\u003e\u003cp\u003e\n\nThis library checks tag validity for built-in tags (currently tag numbers 0, 1, 2, 3, and 55799):\n\n* Inadmissible type for tag content \n* Inadmissible value for tag content\n\nUnknown tag data items (not tag number 0, 1, 2, 3, or 55799) are handled in two ways:\n\n* When decoding into an empty interface, unknown tag data item will be decoded into `cbor.Tag` data type, which contains tag number and tag content.  The tag content will be decoded into the default Go data type for the CBOR data type.\n* When decoding into other Go types, unknown tag data item is decoded into the specified Go type.  If Go type is registered with a tag number, the tag number can optionally be verified.\n\nDecoder also has an option to forbid tag data items (treat any tag data item as error) which is specified by protocols such as CTAP2 Canonical CBOR.  \n\nFor more information, see [decoding options](#decoding-options-1) and [tag options](#tag-options).\n\n\u003c/details\u003e\n\n## Limitations\n\nIf any of these limitations prevent you from using this library, please open an issue along with a link to your project.\n\n* CBOR `Undefined` (0xf7) value decodes to Go's `nil` value.  CBOR `Null` (0xf6) more closely matches Go's `nil`.\n* 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.  \n* When decoding registered CBOR tag data to interface type, decoder creates a pointer to registered Go type matching CBOR tag number.  Requiring a pointer for this is a Go limitation. \n\n## Fuzzing and Code Coverage\n\n__Code coverage__ is always 95% or higher (with `go test -cover`) when tagging a release.\n\n__Coverage-guided fuzzing__ must pass billions of execs using before tagging a release.  Fuzzing is done using nonpublic code which may eventually get merged into this project.  Until then, reports like OpenSSF\u0026nbsp;Scorecard can't detect fuzz tests being used by this project.\n\n\u003chr\u003e\n\n## Versions and API Changes\nThis project uses [Semantic Versioning](https://semver.org), so the API is always backwards compatible unless the major version number changes.  \n\nThese functions have signatures identical to encoding/json and their API will continue to match `encoding/json` even after major new releases:  \n`Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder`, `(*Encoder).Encode`, and `(*Decoder).Decode`.\n\nExclusions from SemVer:\n- Newly added API documented as \"subject to change\".\n- Newly added API in the master branch that has never been tagged in non-beta release.\n- If function parameters are unchanged, bug fixes that change behavior (e.g. return error for edge case was missed in prior version).  We try to highlight these in the release notes and add extended beta period.  E.g. [v2.5.0-beta](https://github.com/fxamacker/cbor/releases/tag/v2.5.0-beta) (Dec 2022) -\u003e [v2.5.0](https://github.com/fxamacker/cbor/releases/tag/v2.5.0) (Aug 2023).\n\nThis project avoids breaking changes to behavior of encoding and decoding functions unless required to improve conformance with supported RFCs (e.g. RFC 8949, RFC 8742, etc.)  Visible changes that don't improve conformance to standards are typically made available as new opt-in settings or new functions.\n\n## Code of Conduct \n\nThis 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.\n\n## Contributing\n\nPlease open an issue before beginning work on a PR.  The improvement may have already been considered, etc.\n\nFor more info, see [How to Contribute](CONTRIBUTING.md).\n\n## Security Policy\n\nSecurity fixes are provided for the latest released version of fxamacker/cbor.\n\nFor the full text of the Security Policy, see [SECURITY.md](SECURITY.md).\n\n## Acknowledgements\n\nMany thanks to all the contributors on this project!\n\nI'm especially grateful to Bastian Müller and Dieter Shirley for suggesting and collaborating on CBOR stream mode, and much more.\n\nI'm very grateful to Stefan Tatschner, Yawning Angel, Jernej Kos, x448, ZenGround0, and Jakob Borg for their contributions or support in the very early days.\n\nBig thanks to Ben Luddy for his contributions in v2.6.0 and v2.7.0.\n\nThis library clearly wouldn't be possible without Carsten Bormann authoring CBOR RFCs.\n\nSpecial thanks to Laurence Lundblade and Jeffrey Yasskin for their help on IETF mailing list or at [7049bis](https://github.com/cbor-wg/CBORbis).\n\nHuge thanks to The Go Authors for creating a fun and practical programming language with batteries included!\n\nThis library uses `x448/float16` which used to be included.  As a standalone package, `x448/float16` is useful to other projects as well.\n\n## License\n\nCopyright © 2019-2024 [Faye Amacker](https://github.com/fxamacker).\n\nfxamacker/cbor is licensed under the MIT License.  See [LICENSE](LICENSE) for the full license text.\n\n\u003chr\u003e\n","funding_links":[],"categories":["序列化","Go","Serialization","安全领域相关库","Relational Databases","Wireless Communication"],"sub_categories":["HTTP客户端","HTTP Clients","查询语","WASI and WASM Unknown"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffxamacker%2Fcbor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffxamacker%2Fcbor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffxamacker%2Fcbor/lists"}