cbor

package module
v2.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2024 License: MIT Imports: 21 Imported by: 965

README

CBOR Codec in Go

fxamacker/cbor is a library for encoding and decoding CBOR and CBOR Sequences.

CBOR is a trusted alternative to JSON, MessagePack, Protocol Buffers, etc.  CBOR is an Internet Standard defined by IETF STD 94 (RFC 8949) and is designed to be relevant for decades.

fxamacker/cbor is used in projects by Arm Ltd., Cisco, EdgeX Foundry, Flow Foundation, Fraunhofer‑AISEC, Kubernetes, Let's Encrypt (ISRG), Linux Foundation, Microsoft, Mozilla, Oasis Protocol, Tailscale, Teleport, etc.

See Quick Start and Releases. 🆕 UnmarshalFirst and DiagnoseFirst can decode CBOR Sequences. cbor.MarshalToBuffer() and UserBufferEncMode accepts user-specified buffer.

fxamacker/cbor

CodeQL Go Report Card

fxamacker/cbor is a CBOR codec in full conformance with IETF STD 94 (RFC 8949). It also supports CBOR Sequences (RFC 8742) and Extended Diagnostic Notation (Appendix G of RFC 8610).

Features include full support for CBOR tags, Core Deterministic Encoding, duplicate map key detection, etc.

Design balances trade-offs between security, speed, concurrency, encoded data size, usability, etc.

Highlights

🚀  Speed

Encoding 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.

🔒  Security

Decoder 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.

Codec passed multiple confidential security assessments in 2022. No vulnerabilities found in subset of codec in a nonconfidential security assessment prepared by NCC Group for Microsoft Corporation.

🗜️  Data Size

Struct tags (toarray, keyasint, omitempty) automatically reduce size of encoded structs. Encoding optionally shrinks float64→32→16 when values fit.

🧩  Usability

API 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.

Presets include Core Deterministic Encoding, Preferred Serialization, CTAP2 Canonical CBOR, etc.

📆  Extensibility

Features include CBOR extension points (e.g. CBOR tags) and extensive settings. API has interfaces that allow users to create custom encoding and decoding without modifying this library.


Secure Decoding with Configurable Settings

fxamacker/cbor has configurable limits, etc. that defend against malicious CBOR data.

By contrast, encoding/gob is not designed to be hardened against adversarial inputs.

Example decoding with encoding/gob 💥 fatal error (out of memory)

// Example of encoding/gob having "fatal error: runtime: out of memory"
// while decoding 181 bytes.
package main
import (
	"bytes"
	"encoding/gob"
	"encoding/hex"
	"fmt"
)

// Example data is from https://github.com/golang/go/issues/24446
// (shortened to 181 bytes).
const data = "4dffb503010102303001ff30000109010130010800010130010800010130" +
	"01ffb80001014a01ffb60001014b01ff860001013001ff860001013001ff" +
	"860001013001ff860001013001ffb80000001eff850401010e3030303030" +
	"30303030303030303001ff3000010c0104000016ffb70201010830303030" +
	"3030303001ff3000010c000030ffb6040405fcff00303030303030303030" +
	"303030303030303030303030303030303030303030303030303030303030" +
	"30"

type X struct {
	J *X
	K map[string]int
}

func main() {
	raw, _ := hex.DecodeString(data)
	decoder := gob.NewDecoder(bytes.NewReader(raw))

	var x X
	decoder.Decode(&x) // fatal error: runtime: out of memory
	fmt.Println("Decoding finished.")
}

fxamacker/cbor is fast at rejecting malformed CBOR data. E.g. attempts to
decode 10 bytes of malicious CBOR data to []byte (with default settings):

Codec Speed (ns/op) Memory Allocs
fxamacker/cbor 2.5.0 44 ± 5% 32 B/op 2 allocs/op
ugorji/go 1.2.11 5353261 ± 4% 67111321 B/op 13 allocs/op
Benchmark details

Latest comparison used:

  • Input: []byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}
  • go1.19.10, linux/amd64, i5-13600K (disabled all e-cores, DDR4 @2933)
  • go test -bench=. -benchmem -count=20
Prior comparisons
Codec Speed (ns/op) Memory Allocs
fxamacker/cbor 2.5.0-beta2 44.33 ± 2% 32 B/op 2 allocs/op
fxamacker/cbor 0.1.0 - 2.4.0 ~44.68 ± 6% 32 B/op 2 allocs/op
ugorji/go 1.2.10 5524792.50 ± 3% 67110491 B/op 12 allocs/op
ugorji/go 1.1.0 - 1.2.6 💥 runtime: out of memory: cannot allocate
  • Input: []byte{0x9B, 0x00, 0x00, 0x42, 0xFA, 0x42, 0xFA, 0x42, 0xFA, 0x42}
  • go1.19.6, linux/amd64, i5-13600K (DDR4)
  • go test -bench=. -benchmem -count=20

Smaller Encodings with Struct Tags

Struct tags (toarray, keyasint, omitempty) reduce encoded size of structs.

Example encoding 3-level nested Go struct to 1 byte CBOR

https://go.dev/play/p/YxwvfPdFQG2

// Example encoding nested struct (with omitempty tag)
// - encoding/json:  18 byte JSON
// - fxamacker/cbor:  1 byte CBOR
package main

import (
	"encoding/hex"
	"encoding/json"
	"fmt"

	"github.com/fxamacker/cbor/v2"
)

type GrandChild struct {
	Quux int `json:",omitempty"`
}

type Child struct {
	Baz int        `json:",omitempty"`
	Qux GrandChild `json:",omitempty"`
}

type Parent struct {
	Foo Child `json:",omitempty"`
	Bar int   `json:",omitempty"`
}

func cb() {
	results, _ := cbor.Marshal(Parent{})
	fmt.Println("hex(CBOR): " + hex.EncodeToString(results))

	text, _ := cbor.Diagnose(results) // Diagnostic Notation
	fmt.Println("DN: " + text)
}

func js() {
	results, _ := json.Marshal(Parent{})
	fmt.Println("hex(JSON): " + hex.EncodeToString(results))

	text := string(results) // JSON
	fmt.Println("JSON: " + text)
}

func main() {
	cb()
	fmt.Println("-------------")
	js()
}

Output (DN is Diagnostic Notation):

hex(CBOR): a0
DN: {}
-------------
hex(JSON): 7b22466f6f223a7b22517578223a7b7d7d7d
JSON: {"Foo":{"Qux":{}}}

Example using different struct tags together:

alt text

API is mostly same as encoding/json, plus interfaces that simplify concurrency for CBOR options.

Quick Start

Install: go get github.com/fxamacker/cbor/v2 and import "github.com/fxamacker/cbor/v2".

Key Points

This library can encode and decode CBOR (RFC 8949) and CBOR Sequences (RFC 8742).

  • CBOR data item is a single piece of CBOR data and its structure may contain 0 or more nested data items.
  • CBOR sequence is a concatenation of 0 or more encoded CBOR data items.

Configurable limits and options can be used to balance trade-offs.

  • Encoding and decoding modes are created from options (settings).
  • Modes can be created at startup and reused.
  • Modes are safe for concurrent use.
Default Mode

Package level functions only use this library's default settings.
They provide the "default mode" of encoding and decoding.

// API matches encoding/json for Marshal, Unmarshal, Encode, Decode, etc.
b, err = cbor.Marshal(v)        // encode v to []byte b
err = cbor.Unmarshal(b, &v)     // decode []byte b to v
decoder = cbor.NewDecoder(r)    // create decoder with io.Reader r
err = decoder.Decode(&v)        // decode a CBOR data item to v

// v2.7.0 added MarshalToBuffer() and UserBufferEncMode interface.
err = cbor.MarshalToBuffer(v, b) // encode v to b instead of using built-in buf pool.

// v2.5.0 added new functions that return remaining bytes.

// UnmarshalFirst decodes first CBOR data item and returns remaining bytes.
rest, err = cbor.UnmarshalFirst(b, &v)   // decode []byte b to v

// DiagnoseFirst translates first CBOR data item to text and returns remaining bytes.
text, rest, err = cbor.DiagnoseFirst(b)  // decode []byte b to Diagnostic Notation text

// NOTE: Unmarshal returns ExtraneousDataError if there are remaining bytes,
// but new funcs UnmarshalFirst and DiagnoseFirst do not.

IMPORTANT: 👉 CBOR settings allow trade-offs between speed, security, encoding size, etc.

  • Different CBOR libraries may use different default settings.
  • CBOR-based formats or protocols usually require specific settings.

For example, WebAuthn uses "CTAP2 Canonical CBOR" which is available as a preset.

Presets

Presets can be used as-is or as a starting point for custom settings.

// EncOptions is a struct of encoder settings.
func CoreDetEncOptions() EncOptions              // RFC 8949 Core Deterministic Encoding
func PreferredUnsortedEncOptions() EncOptions    // RFC 8949 Preferred Serialization
func CanonicalEncOptions() EncOptions            // RFC 7049 Canonical CBOR
func CTAP2EncOptions() EncOptions                // FIDO2 CTAP2 Canonical CBOR

Presets are used to create custom modes.

Custom Modes

Modes are created from settings. Once created, modes have immutable settings.

💡 Create the mode at startup and reuse it. It is safe for concurrent use.

// Create encoding mode.
opts := cbor.CoreDetEncOptions()   // use preset options as a starting point
opts.Time = cbor.TimeUnix          // change any settings if needed
em, err := opts.EncMode()          // create an immutable encoding mode

// Reuse the encoding mode. It is safe for concurrent use.

// API matches encoding/json.
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

Default mode and custom modes automatically apply struct tags.

User Specified Buffer for Encoding (v2.7.0)

UserBufferEncMode interface extends EncMode interface to add MarshalToBuffer(). It accepts a user-specified buffer instead of using built-in buffer pool.

em, err := myEncOptions.UserBufferEncMode() // create UserBufferEncMode mode

var buf bytes.Buffer
err = em.MarshalToBuffer(v, &buf) // encode v to provided buf
Struct Tags

Struct tags (toarray, keyasint, omitempty) reduce encoded size of structs.

Example encoding 3-level nested Go struct to 1 byte CBOR

https://go.dev/play/p/YxwvfPdFQG2

// Example encoding nested struct (with omitempty tag)
// - encoding/json:  18 byte JSON
// - fxamacker/cbor:  1 byte CBOR
package main

import (
	"encoding/hex"
	"encoding/json"
	"fmt"

	"github.com/fxamacker/cbor/v2"
)

type GrandChild struct {
	Quux int `json:",omitempty"`
}

type Child struct {
	Baz int        `json:",omitempty"`
	Qux GrandChild `json:",omitempty"`
}

type Parent struct {
	Foo Child `json:",omitempty"`
	Bar int   `json:",omitempty"`
}

func cb() {
	results, _ := cbor.Marshal(Parent{})
	fmt.Println("hex(CBOR): " + hex.EncodeToString(results))

	text, _ := cbor.Diagnose(results) // Diagnostic Notation
	fmt.Println("DN: " + text)
}

func js() {
	results, _ := json.Marshal(Parent{})
	fmt.Println("hex(JSON): " + hex.EncodeToString(results))

	text := string(results) // JSON
	fmt.Println("JSON: " + text)
}

func main() {
	cb()
	fmt.Println("-------------")
	js()
}

Output (DN is Diagnostic Notation):

hex(CBOR): a0
DN: {}
-------------
hex(JSON): 7b22466f6f223a7b22517578223a7b7d7d7d
JSON: {"Foo":{"Qux":{}}}

Example using several struct tags

alt text

Struct tags simplify use of CBOR-based protocols that require CBOR arrays or maps with integer keys.

CBOR Tags

CBOR tags are specified in a TagSet.

Custom modes can be created with a TagSet to handle CBOR tags.

em, err := opts.EncMode()                  // no CBOR tags
em, err := opts.EncModeWithTags(ts)        // immutable CBOR tags
em, err := opts.EncModeWithSharedTags(ts)  // mutable shared CBOR tags

TagSet and modes using it are safe for concurrent use. Equivalent API is available for DecMode.

Example using TagSet and TagOptions

// 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
}
Functions and Interfaces
Functions and interfaces at a glance

Common functions with same API as encoding/json:

  • Marshal, Unmarshal
  • NewEncoder, (*Encoder).Encode
  • NewDecoder, (*Decoder).Decode

NOTE: Unmarshal will return ExtraneousDataError if there are remaining bytes because RFC 8949 treats CBOR data item with remaining bytes as malformed.

  • 💡 Use UnmarshalFirst to decode first CBOR data item and return any remaining bytes.

Other useful functions:

  • Diagnose, DiagnoseFirst produce human-readable Extended Diagnostic Notation from CBOR data.
  • UnmarshalFirst decodes first CBOR data item and return any remaining bytes.
  • Wellformed returns true if the the CBOR data item is well-formed.

Interfaces identical or comparable to Go encoding packages include:
Marshaler, Unmarshaler, BinaryMarshaler, and BinaryUnmarshaler.

The RawMessage type can be used to delay CBOR decoding or precompute CBOR encoding.

Security Tips

🔒 Use Go's io.LimitReader to limit size when decoding very large or indefinite size data.

Default limits may need to be increased for systems handling very large data (e.g. blockchains).

DecOptions can be used to modify default limits for MaxArrayElements, MaxMapPairs, and MaxNestedLevels.

Status

v2.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.

For more details, see release notes.

Prior Release

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.

v2.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 (Dec 2022) -> v2.5.0 (Aug 2023).

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.

See v2.5.0 release notes for list of new features, improvements, and bug fixes.

See "Version and API Changes" section for more info about version numbering, etc.

Who uses fxamacker/cbor

fxamacker/cbor is used in projects by Arm Ltd., Berlin Institute of Health at Charité, Chainlink, Cisco, Confidential Computing Consortium, ConsenSys, Dapper Labs, EdgeX Foundry, F5, FIDO Alliance, Fraunhofer‑AISEC, Kubernetes, Let's Encrypt (ISRG), Linux Foundation, Matrix.org, Microsoft, Mozilla, National Cybersecurity Agency of France (govt), Netherlands (govt), Oasis Protocol, Smallstep, Tailscale, Taurus SA, Teleport, TIBCO, and others.

fxamacker/cbor passed multiple confidential security assessments. A nonconfidential security assessment (prepared by NCC Group for Microsoft Corporation) includes a subset of fxamacker/cbor v2.4.0 in its scope.

Standards

fxamacker/cbor is a CBOR codec in full conformance with IETF STD 94 (RFC 8949). It also supports CBOR Sequences (RFC 8742) and Extended Diagnostic Notation (Appendix G of RFC 8610).

Notable CBOR features include:

CBOR Feature Description
CBOR tags API supports built-in and user-defined tags.
Preferred serialization Integers encode to fewest bytes. Optional float64 → float32 → float16.
Map key sorting Unsorted, length-first (Canonical CBOR), and bytewise-lexicographic (CTAP2).
Duplicate map keys Always forbid for encoding and option to allow/forbid for decoding.
Indefinite length data Option to allow/forbid for encoding and decoding.
Well-formedness Always checked and enforced.
Basic validity checks Optionally check UTF-8 validity and duplicate map keys.
Security considerations Prevent integer overflow and resource exhaustion (RFC 8949 Section 10).

Known limitations are noted in the Limitations section.

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 has option to check and return invalid UTF-8 string error. This check is enabled by default.
  • 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.

By default, decoder treats time values of floating-point NaN and Infinity as if they are CBOR Null or CBOR Undefined.

Click to expand topic:

Duplicate Map Keys

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.

Tag Validity

This library checks tag validity for built-in tags (currently tag numbers 0, 1, 2, 3, and 55799):

  • Inadmissible type for tag content
  • Inadmissible value for tag content

Unknown tag data items (not tag number 0, 1, 2, 3, or 55799) are handled in two ways:

  • 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.
  • 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.

Decoder 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.

For more information, see decoding options and tag options.

Limitations

If any of these limitations prevent you from using this library, please open an issue along with a link to your project.

  • 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 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.

Fuzzing and Code Coverage

Code coverage is always 95% or higher (with go test -cover) when tagging a release.

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 Scorecard can't detect fuzz tests being used by this project.


Versions and API Changes

This project uses Semantic Versioning, so the API is always backwards compatible unless the major version number changes.

These functions have signatures identical to encoding/json and their API will continue to match encoding/json even after major new releases:
Marshal, Unmarshal, NewEncoder, NewDecoder, (*Encoder).Encode, and (*Decoder).Decode.

Exclusions from SemVer:

  • Newly added API documented as "subject to change".
  • Newly added API in the master branch that has never been tagged in non-beta release.
  • 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 (Dec 2022) -> v2.5.0 (Aug 2023).

This 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.

Code of Conduct

This project has adopted the Contributor Covenant Code of Conduct. Contact faye.github@gmail.com with any questions or comments.

Contributing

Please open an issue before beginning work on a PR. The improvement may have already been considered, etc.

For more info, see How to Contribute.

Security Policy

Security fixes are provided for the latest released version of fxamacker/cbor.

For the full text of the Security Policy, see SECURITY.md.

Acknowledgements

Many thanks to all the contributors on this project!

I'm especially grateful to Bastian Müller and Dieter Shirley for suggesting and collaborating on CBOR stream mode, and much more.

I'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.

Big thanks to Ben Luddy for his contributions in v2.6.0 and v2.7.0.

This library clearly wouldn't be possible without Carsten Bormann authoring CBOR RFCs.

Special thanks to Laurence Lundblade and Jeffrey Yasskin for their help on IETF mailing list or at 7049bis.

Huge thanks to The Go Authors for creating a fun and practical programming language with batteries included!

This library uses x448/float16 which used to be included. As a standalone package, x448/float16 is useful to other projects as well.

License

Copyright © 2019-2024 Faye Amacker.

fxamacker/cbor is licensed under the MIT License. See LICENSE for the full license text.


Documentation

Overview

Package cbor is a modern CBOR codec (RFC 8949 & RFC 7049) with CBOR tags, Go struct tags (toarray/keyasint/omitempty), Core Deterministic Encoding, CTAP2, Canonical CBOR, float64->32->16, and duplicate map key detection.

Encoding options allow "preferred serialization" by encoding integers and floats to their smallest forms (e.g. float16) when values fit.

Struct tags like "keyasint", "toarray" and "omitempty" make CBOR data smaller and easier to use with structs.

For example, "toarray" tag makes struct fields encode to CBOR array elements. And "keyasint" makes a field encode to an element of CBOR map with specified int key.

Latest docs can be viewed at https://github.com/fxamacker/cbor#cbor-library-in-go

Basics

The Quick Start guide is at https://github.com/fxamacker/cbor#quick-start

Function signatures identical to encoding/json include:

Marshal, Unmarshal, NewEncoder, NewDecoder, (*Encoder).Encode, (*Decoder).Decode.

Standard interfaces include:

BinaryMarshaler, BinaryUnmarshaler, Marshaler, and Unmarshaler.

Custom encoding and decoding is possible by implementing standard interfaces for user-defined Go types.

Codec functions are available at package-level (using defaults options) or by creating modes from options at runtime.

"Mode" in this API means definite way of encoding (EncMode) or decoding (DecMode).

EncMode and DecMode interfaces are created from EncOptions or DecOptions structs.

em, err := cbor.EncOptions{...}.EncMode()
em, err := cbor.CanonicalEncOptions().EncMode()
em, err := 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)

// NOTE: Both em.Marshal(v) and encoder.Encode(v) use encoding options
// specified during creation of em (encoding mode).

CBOR Options

Predefined Encoding Options: https://github.com/fxamacker/cbor#predefined-encoding-options

Encoding Options: https://github.com/fxamacker/cbor#encoding-options

Decoding Options: https://github.com/fxamacker/cbor#decoding-options

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

Struct tags are listed at https://github.com/fxamacker/cbor#struct-tags-1

Tests and Fuzzing

Over 375 tests are included in this package. Cover-guided fuzzing is handled by a private fuzzer that replaced fxamacker/cbor-fuzz years ago.

Example (COSE)
// Use "keyasint" struct tag to encode/decode struct to/from CBOR map.
// Use cbor.RawMessage to delay unmarshaling (CrvOrNOrK's data type depends on Kty's value).
type coseKey struct {
	Kty       int             `cbor:"1,keyasint,omitempty"`
	Kid       []byte          `cbor:"2,keyasint,omitempty"`
	Alg       int             `cbor:"3,keyasint,omitempty"`
	KeyOpts   int             `cbor:"4,keyasint,omitempty"`
	IV        []byte          `cbor:"5,keyasint,omitempty"`
	CrvOrNOrK cbor.RawMessage `cbor:"-1,keyasint,omitempty"` // K for symmetric keys, Crv for elliptic curve keys, N for RSA modulus
	XOrE      cbor.RawMessage `cbor:"-2,keyasint,omitempty"` // X for curve x-coordinate, E for RSA public exponent
	Y         cbor.RawMessage `cbor:"-3,keyasint,omitempty"` // Y for curve y-cooridate
	D         []byte          `cbor:"-4,keyasint,omitempty"`
}
// Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.2
// 128-Bit Symmetric Key
data, _ := hex.DecodeString("a42050231f4c4d4d3051fdc2ec0a3851d5b3830104024c53796d6d6574726963313238030a")
var v coseKey
if err := cbor.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
if _, err := cbor.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

{Kty:4 Kid:[83 121 109 109 101 116 114 105 99 49 50 56] Alg:10 KeyOpts:0 IV:[] CrvOrNOrK:[80 35 31 76 77 77 48 81 253 194 236 10 56 81 213 179 131] XOrE:[] Y:[] D:[]}
Example (CWT)
// Use "keyasint" struct tag to encode/decode struct to/from CBOR map.
type claims struct {
	Iss string `cbor:"1,keyasint"`
	Sub string `cbor:"2,keyasint"`
	Aud string `cbor:"3,keyasint"`
	Exp int    `cbor:"4,keyasint"`
	Nbf int    `cbor:"5,keyasint"`
	Iat int    `cbor:"6,keyasint"`
	Cti []byte `cbor:"7,keyasint"`
}
// Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.1
data, _ := hex.DecodeString("a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b71")
var v claims
if err := cbor.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
if _, err := cbor.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

{Iss:coap://as.example.com Sub:erikw Aud:coap://light.example.com Exp:1444064944 Nbf:1443944944 Iat:1443944944 Cti:[11 113]}
Example (CWTWithDupMapKeyOption)
type claims struct {
	Iss string `cbor:"1,keyasint"`
	Sub string `cbor:"2,keyasint"`
	Aud string `cbor:"3,keyasint"`
	Exp int    `cbor:"4,keyasint"`
	Nbf int    `cbor:"5,keyasint"`
	Iat int    `cbor:"6,keyasint"`
	Cti []byte `cbor:"7,keyasint"`
}

// Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.1
data, _ := hex.DecodeString("a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b71")

dm, _ := cbor.DecOptions{DupMapKey: cbor.DupMapKeyEnforcedAPF}.DecMode()

var v claims
if err := dm.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

{Iss:coap://as.example.com Sub:erikw Aud:coap://light.example.com Exp:1444064944 Nbf:1443944944 Iat:1443944944 Cti:[11 113]}
Example (SenML)
// Use "keyasint" struct tag to encode/decode struct to/from CBOR map.
type SenMLRecord struct {
	BaseName    string  `cbor:"-2,keyasint,omitempty"`
	BaseTime    float64 `cbor:"-3,keyasint,omitempty"`
	BaseUnit    string  `cbor:"-4,keyasint,omitempty"`
	BaseValue   float64 `cbor:"-5,keyasint,omitempty"`
	BaseSum     float64 `cbor:"-6,keyasint,omitempty"`
	BaseVersion int     `cbor:"-1,keyasint,omitempty"`
	Name        string  `cbor:"0,keyasint,omitempty"`
	Unit        string  `cbor:"1,keyasint,omitempty"`
	Time        float64 `cbor:"6,keyasint,omitempty"`
	UpdateTime  float64 `cbor:"7,keyasint,omitempty"`
	Value       float64 `cbor:"2,keyasint,omitempty"`
	ValueS      string  `cbor:"3,keyasint,omitempty"`
	ValueB      bool    `cbor:"4,keyasint,omitempty"`
	ValueD      string  `cbor:"8,keyasint,omitempty"`
	Sum         float64 `cbor:"5,keyasint,omitempty"`
}
// Data from https://tools.ietf.org/html/rfc8428#section-6
data, _ := hex.DecodeString("87a721781b75726e3a6465763a6f773a3130653230373361303130383030363a22fb41d303a15b00106223614120050067766f6c7461676501615602fb405e066666666666a3006763757272656e74062402fb3ff3333333333333a3006763757272656e74062302fb3ff4cccccccccccda3006763757272656e74062202fb3ff6666666666666a3006763757272656e74062102f93e00a3006763757272656e74062002fb3ff999999999999aa3006763757272656e74060002fb3ffb333333333333")
var v []*SenMLRecord
if err := cbor.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
// Encoder uses ShortestFloat16 option to use float16 as the shortest form that preserves floating-point value.
em, err := cbor.EncOptions{ShortestFloat: cbor.ShortestFloat16}.EncMode()
if err != nil {
	fmt.Println("error:", err)
}
if _, err := em.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
for _, rec := range v {
	fmt.Printf("%+v\n", *rec)
}
Output:

{BaseName:urn:dev:ow:10e2073a0108006: BaseTime:1.276020076001e+09 BaseUnit:A BaseValue:0 BaseSum:0 BaseVersion:5 Name:voltage Unit:V Time:0 UpdateTime:0 Value:120.1 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-5 UpdateTime:0 Value:1.2 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-4 UpdateTime:0 Value:1.3 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-3 UpdateTime:0 Value:1.4 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-2 UpdateTime:0 Value:1.5 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-1 UpdateTime:0 Value:1.6 ValueS: ValueB:false ValueD: Sum:0}
{BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:0 UpdateTime:0 Value:1.7 ValueS: ValueB:false ValueD: Sum:0}
Example (SignedCWT)
// Use "keyasint" struct tag to encode/decode struct to/from CBOR map.
// Partial COSE header definition
type coseHeader struct {
	Alg int    `cbor:"1,keyasint,omitempty"`
	Kid []byte `cbor:"4,keyasint,omitempty"`
	IV  []byte `cbor:"5,keyasint,omitempty"`
}
// Use "toarray" struct tag to encode/decode struct to/from CBOR array.
type signedCWT struct {
	_           struct{} `cbor:",toarray"`
	Protected   []byte
	Unprotected coseHeader
	Payload     []byte
	Signature   []byte
}
// Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.3
data, _ := hex.DecodeString("d28443a10126a104524173796d6d657472696345434453413235365850a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b7158405427c1ff28d23fbad1f29c4c7c6a555e601d6fa29f9179bc3d7438bacaca5acd08c8d4d4f96131680c429a01f85951ecee743a52b9b63632c57209120e1c9e30")
var v signedCWT
if err := cbor.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
if _, err := cbor.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

{_:{} Protected:[161 1 38] Unprotected:{Alg:0 Kid:[65 115 121 109 109 101 116 114 105 99 69 67 68 83 65 50 53 54] IV:[]} Payload:[167 1 117 99 111 97 112 58 47 47 97 115 46 101 120 97 109 112 108 101 46 99 111 109 2 101 101 114 105 107 119 3 120 24 99 111 97 112 58 47 47 108 105 103 104 116 46 101 120 97 109 112 108 101 46 99 111 109 4 26 86 18 174 176 5 26 86 16 217 240 6 26 86 16 217 240 7 66 11 113] Signature:[84 39 193 255 40 210 63 186 209 242 156 76 124 106 85 94 96 29 111 162 159 145 121 188 61 116 56 186 202 202 90 205 8 200 212 212 249 97 49 104 12 66 154 1 248 89 81 236 238 116 58 82 185 182 54 50 197 114 9 18 14 28 158 48]}
Example (SignedCWTWithTag)
// Use "keyasint" struct tag to encode/decode struct to/from CBOR map.
// Partial COSE header definition
type coseHeader struct {
	Alg int    `cbor:"1,keyasint,omitempty"`
	Kid []byte `cbor:"4,keyasint,omitempty"`
	IV  []byte `cbor:"5,keyasint,omitempty"`
}
// Use "toarray" struct tag to encode/decode struct to/from CBOR array.
type signedCWT struct {
	_           struct{} `cbor:",toarray"`
	Protected   []byte
	Unprotected coseHeader
	Payload     []byte
	Signature   []byte
}

// Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.3
data, _ := hex.DecodeString("d28443a10126a104524173796d6d657472696345434453413235365850a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b7158405427c1ff28d23fbad1f29c4c7c6a555e601d6fa29f9179bc3d7438bacaca5acd08c8d4d4f96131680c429a01f85951ecee743a52b9b63632c57209120e1c9e30")

// Register tag COSE_Sign1 18 with signedCWT type.
tags := cbor.NewTagSet()
if err := tags.Add(
	cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired},
	reflect.TypeOf(signedCWT{}),
	18); err != nil {
	fmt.Println("error:", err)
}

dm, _ := cbor.DecOptions{}.DecModeWithTags(tags)
em, _ := cbor.EncOptions{}.EncModeWithTags(tags)

var v signedCWT
if err := dm.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}

if _, err := em.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

{_:{} Protected:[161 1 38] Unprotected:{Alg:0 Kid:[65 115 121 109 109 101 116 114 105 99 69 67 68 83 65 50 53 54] IV:[]} Payload:[167 1 117 99 111 97 112 58 47 47 97 115 46 101 120 97 109 112 108 101 46 99 111 109 2 101 101 114 105 107 119 3 120 24 99 111 97 112 58 47 47 108 105 103 104 116 46 101 120 97 109 112 108 101 46 99 111 109 4 26 86 18 174 176 5 26 86 16 217 240 6 26 86 16 217 240 7 66 11 113] Signature:[84 39 193 255 40 210 63 186 209 242 156 76 124 106 85 94 96 29 111 162 159 145 121 188 61 116 56 186 202 202 90 205 8 200 212 212 249 97 49 104 12 66 154 1 248 89 81 236 238 116 58 82 185 182 54 50 197 114 9 18 14 28 158 48]}
Example (WebAuthn)
// Use cbor.RawMessage to delay unmarshaling (AttStmt's data type depends on Fmt's value).
type attestationObject struct {
	AuthnData []byte          `cbor:"authData"`
	Fmt       string          `cbor:"fmt"`
	AttStmt   cbor.RawMessage `cbor:"attStmt"`
}
data, _ := hex.DecodeString("a363666d74686669646f2d7532666761747453746d74a26373696758483046022100e7ab373cfbd99fcd55fd59b0f6f17fef5b77a20ddec3db7f7e4d55174e366236022100828336b4822125fb56541fb14a8a273876acd339395ec2dad95cf41c1dd2a9ae637835638159024e3082024a30820132a0030201020204124a72fe300d06092a864886f70d01010b0500302e312c302a0603550403132359756269636f2055324620526f6f742043412053657269616c203435373230303633313020170d3134303830313030303030305a180f32303530303930343030303030305a302c312a302806035504030c2159756269636f205532462045452053657269616c203234393431343937323135383059301306072a8648ce3d020106082a8648ce3d030107034200043d8b1bbd2fcbf6086e107471601468484153c1c6d3b4b68a5e855e6e40757ee22bcd8988bf3befd7cdf21cb0bf5d7a150d844afe98103c6c6607d9faae287c02a33b3039302206092b0601040182c40a020415312e332e362e312e342e312e34313438322e312e313013060b2b0601040182e51c020101040403020520300d06092a864886f70d01010b05000382010100a14f1eea0076f6b8476a10a2be72e60d0271bb465b2dfbfc7c1bd12d351989917032631d795d097fa30a26a325634e85721bc2d01a86303f6bc075e5997319e122148b0496eec8d1f4f94cf4110de626c289443d1f0f5bbb239ca13e81d1d5aa9df5af8e36126475bfc23af06283157252762ff68879bcf0ef578d55d67f951b4f32b63c8aea5b0f99c67d7d814a7ff5a6f52df83e894a3a5d9c8b82e7f8bc8daf4c80175ff8972fda79333ec465d806eacc948f1bab22045a95558a48c20226dac003d41fbc9e05ea28a6bb5e10a49de060a0a4f6a2676a34d68c4abe8c61874355b9027e828ca9e064b002d62e8d8cf0744921753d35e3c87c5d5779453e7768617574684461746158c449960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d976341000000000000000000000000000000000000000000408903fd7dfd2c9770e98cae0123b13a2c27828a106349bc6277140e7290b7e9eb7976aa3c04ed347027caf7da3a2fa76304751c02208acfc4e7fc6c7ebbc375c8a5010203262001215820ad7f7992c335b90d882b2802061b97a4fabca7e2ee3e7a51e728b8055e4eb9c7225820e0966ba7005987fece6f0e0e13447aa98cec248e4000a594b01b74c1cb1d40b3")
var v attestationObject
if err := cbor.Unmarshal(data, &v); err != nil {
	fmt.Println("error:", err)
}
if _, err := cbor.Marshal(v); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", v)
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Diagnose added in v2.5.0

func Diagnose(data []byte) (string, error)

Diagnose returns extended diagnostic notation (EDN) of CBOR data items using the default diagnostic mode.

Refer to https://www.rfc-editor.org/rfc/rfc8949.html#name-diagnostic-notation.

func DiagnoseFirst added in v2.5.0

func DiagnoseFirst(data []byte) (diagNotation string, rest []byte, err error)

Diagnose returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest.

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal returns the CBOR encoding of v using default encoding options. See EncOptions for encoding options.

Marshal uses the following encoding rules:

If value implements the Marshaler interface, Marshal calls its MarshalCBOR method.

If value implements encoding.BinaryMarshaler, Marhsal calls its MarshalBinary method and encode it as CBOR byte string.

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. See struct tag option "keyasint" to encode field name as CBOR integer (type 0 and 1). Also see struct tag option "toarray" for special field "_" to encode struct values as CBOR array (type 4).

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 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.

time.Time values encode as text strings specified in RFC3339 or numerical representation of seconds since January 1, 1970 UTC depending on EncOptions.Time setting. Also See EncOptions.TimeTag to encode time.Time as CBOR tag with tag number 0 or 1.

big.Int values encode as CBOR integers (type 0 and 1) if values fit. Otherwise, big.Int values encode as CBOR bignums (tag 2 and 3). See EncOptions.BigIntConvert to always encode big.Int values as CBOR bignums.

Pointer values encode as the value pointed to.

Interface values encode as the value stored in the interface.

Nil slice/map/pointer/interface values encode as CBOR nulls (type 7).

Values of other types cannot be encoded in CBOR. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

Example
type Animal struct {
	Age    int
	Name   string
	Owners []string
	Male   bool
}
animal := Animal{Age: 4, Name: "Candy", Owners: []string{"Mary", "Joe"}}
b, err := cbor.Marshal(animal)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)
Output:

a46341676504644e616d656543616e6479664f776e65727382644d617279634a6f65644d616c65f4
Example (Canonical)

This example uses Marshal to encode struct and map in canonical form.

type Animal struct {
	Age      int
	Name     string
	Contacts map[string]string
	Male     bool
}
animal := Animal{Age: 4, Name: "Candy", Contacts: map[string]string{"Mary": "111-111-1111", "Joe": "222-222-2222"}}
em, err := cbor.CanonicalEncOptions().EncMode()
if err != nil {
	fmt.Println("error:", err)
}
b, err := em.Marshal(animal)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)
Output:

a46341676504644d616c65f4644e616d656543616e647968436f6e7461637473a2634a6f656c3232322d3232322d32323232644d6172796c3131312d3131312d31313131
Example (Keyasint)

This example uses "keyasint" struct tag to encode struct's fiele names as integer. This feautre is very useful in handling COSE, CWT, SenML data.

type Record struct {
	Name        string `cbor:"1,keyasint"`
	Unit        string `cbor:"2,keyasint"`
	Measurement int    `cbor:"3,keyasint"`
}
rec := Record{Name: "current", Unit: "V", Measurement: 1}
b, err := cbor.Marshal(rec)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)
Output:

a3016763757272656e740261560301
Example (Time)
tm, _ := time.Parse(time.RFC3339, "2013-03-21T20:04:00Z")

// Encode time as string in RFC3339 format with second precision.
em, err := cbor.EncOptions{Time: cbor.TimeRFC3339}.EncMode()
if err != nil {
	fmt.Println("error:", err)
}
b, err := em.Marshal(tm)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)

// Encode time as numerical representation of seconds since January 1, 1970 UTC.
em, err = cbor.EncOptions{Time: cbor.TimeUnix}.EncMode()
if err != nil {
	fmt.Println("error:", err)
}
b, err = em.Marshal(tm)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)
Output:

74323031332d30332d32315432303a30343a30305a
1a514b67b0
Example (Toarray)

This example uses "toarray" struct tag to encode struct as CBOR array.

type Record struct {
	_           struct{} `cbor:",toarray"`
	Name        string
	Unit        string
	Measurement int
}
rec := Record{Name: "current", Unit: "V", Measurement: 1}
b, err := cbor.Marshal(rec)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", b)
Output:

836763757272656e74615601

func MarshalToBuffer added in v2.7.0

func MarshalToBuffer(v interface{}, buf *bytes.Buffer) error

MarshalToBuffer encodes v into provided buffer (instead of using built-in buffer pool) and uses default encoding options.

NOTE: Unlike Marshal, the buffer provided to MarshalToBuffer can contain partially encoded data if error is returned.

See Marshal for more details.

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the CBOR-encoded data into the value pointed to by v using default decoding options. If v is nil, not a pointer, or a nil pointer, Unmarshal returns an error.

To unmarshal CBOR into a value implementing the Unmarshaler interface, Unmarshal calls that value's UnmarshalCBOR method with a valid CBOR value.

To unmarshal CBOR byte string into a value implementing the encoding.BinaryUnmarshaler interface, Unmarshal calls that value's UnmarshalBinary method with decoded CBOR byte string.

To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal unmarshals CBOR into the value pointed to by the pointer. If the pointer is nil, Unmarshal creates a new value for it to point to.

To unmarshal CBOR into an empty interface value, Unmarshal uses the following rules:

CBOR booleans decode to bool.
CBOR positive integers decode to uint64.
CBOR negative integers decode to int64 (big.Int if value overflows).
CBOR floating points decode to float64.
CBOR byte strings decode to []byte.
CBOR text strings decode to string.
CBOR arrays decode to []interface{}.
CBOR maps decode to map[interface{}]interface{}.
CBOR null and undefined values decode to nil.
CBOR times (tag 0 and 1) decode to time.Time.
CBOR bignums (tag 2 and 3) decode to big.Int.
CBOR tags with an unrecognized number decode to cbor.Tag

To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice if the CBOR array is empty or slice capacity is less than CBOR array length. Otherwise Unmarshal overwrites existing elements, and sets slice length to CBOR array length.

To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array elements into Go array elements. If the Go array is smaller than the CBOR array, the extra CBOR array elements are discarded. If the CBOR array is smaller than the Go array, the extra Go array elements are set to zero values.

To unmarshal a CBOR array into a struct, struct must have a special field "_" with struct tag `cbor:",toarray"`. Go array elements are decoded into struct fields. Any "omitempty" struct field tag option is ignored in this case.

To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the map is nil. Otherwise Unmarshal reuses the existing map and keeps existing entries. Unmarshal stores key-value pairs from the CBOR map into Go map. See DecOptions.DupMapKey to enable duplicate map key detection.

To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the keys in the following priority:

  1. "cbor" key in struct field tag,
  2. "json" key in struct field tag,
  3. struct field name.

Unmarshal tries an exact match for field name, then a case-insensitive match. Map key-value pairs without corresponding struct fields are ignored. See DecOptions.ExtraReturnErrors to return error at unknown field.

To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text string formatted in RFC3339. To unmarshal a CBOR integer/float into a time.Time value, Unmarshal creates an unix time with integer/float as seconds and fractional seconds since January 1, 1970 UTC. As a special case, Infinite and NaN float values decode to time.Time's zero value.

To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a slice/map/pointer, Unmarshal sets Go value to nil. Because null is often used to mean "not present", unmarshalling CBOR null and undefined value into any other Go type has no effect and returns no error.

Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time), and tag 2 and 3 (bignum).

Unmarshal returns ExtraneousDataError error (without decoding into v) if there are any remaining bytes following the first valid CBOR data item. See UnmarshalFirst, if you want to unmarshal only the first CBOR data item without ExtraneousDataError caused by remaining bytes.

Example
type Animal struct {
	Age    int
	Name   string
	Owners []string
	Male   bool
}
data, _ := hex.DecodeString("a46341676504644e616d656543616e6479664f776e65727382644d617279634a6f65644d616c65f4")
var animal Animal
err := cbor.Unmarshal(data, &animal)
if err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v", animal)
Output:

{Age:4 Name:Candy Owners:[Mary Joe] Male:false}
Example (Time)
cborRFC3339Time, _ := hex.DecodeString("74323031332d30332d32315432303a30343a30305a")
tm := time.Time{}
if err := cbor.Unmarshal(cborRFC3339Time, &tm); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v\n", tm.UTC().Format(time.RFC3339Nano))
cborUnixTime, _ := hex.DecodeString("1a514b67b0")
tm = time.Time{}
if err := cbor.Unmarshal(cborUnixTime, &tm); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%+v\n", tm.UTC().Format(time.RFC3339Nano))
Output:

2013-03-21T20:04:00Z
2013-03-21T20:04:00Z

func UnmarshalFirst added in v2.5.0

func UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error)

UnmarshalFirst parses the first CBOR data item into the value pointed to by v using default decoding options. Any remaining bytes are returned in rest.

If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.

See the documentation for Unmarshal for details.

func Valid deprecated added in v2.3.0

func Valid(data []byte) error

Valid checks whether data is a well-formed encoded CBOR data item and that it complies with default restrictions such as MaxNestedLevels, MaxArrayElements, MaxMapPairs, etc.

If there are any remaining bytes after the CBOR data item, an ExtraneousDataError is returned.

WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity) and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".

Deprecated: Valid is kept for compatibility and should not be used. Use Wellformed instead because it has a more appropriate name.

func Wellformed added in v2.5.0

func Wellformed(data []byte) error

Wellformed checks whether data is a well-formed encoded CBOR data item and that it complies with default restrictions such as MaxNestedLevels, MaxArrayElements, MaxMapPairs, etc.

If there are any remaining bytes after the CBOR data item, an ExtraneousDataError is returned.

func WithRejectedSimpleValue added in v2.7.0

func WithRejectedSimpleValue(sv SimpleValue) func(*SimpleValueRegistry) error

WithRejectedSimpleValue registers the given simple value as rejected. If the simple value is encountered in a CBOR input during unmarshaling, an UnacceptableDataItemError is returned.

Types

type BigIntConvertMode added in v2.3.0

type BigIntConvertMode int

BigIntConvertMode specifies how to encode big.Int values.

const (
	// BigIntConvertShortest makes big.Int encode to CBOR integer if value fits.
	// E.g. if big.Int value can be converted to CBOR integer while preserving
	// value, encoder will encode it to CBOR integer (major type 0 or 1).
	BigIntConvertShortest BigIntConvertMode = iota

	// BigIntConvertNone makes big.Int encode to CBOR bignum (tag 2 or 3) without
	// converting it to another CBOR type.
	BigIntConvertNone

	// BigIntConvertReject returns an UnsupportedTypeError instead of marshaling a big.Int.
	BigIntConvertReject
)

type BigIntDecMode added in v2.6.0

type BigIntDecMode int

BigIntDecMode specifies how to decode CBOR bignum to Go interface{}.

const (
	// BigIntDecodeValue makes CBOR bignum decode to big.Int (instead of *big.Int)
	// when unmarshalling into a Go interface{}.
	BigIntDecodeValue BigIntDecMode = iota

	// BigIntDecodePointer makes CBOR bignum decode to *big.Int when
	// unmarshalling into a Go interface{}.
	BigIntDecodePointer
)

type BignumTagMode added in v2.7.0

type BignumTagMode int

BignumTagMode specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can be decoded.

const (
	// BignumTagAllowed allows bignum tags to be decoded.
	BignumTagAllowed BignumTagMode = iota

	// BignumTagForbidden produces an UnacceptableDataItemError during Unmarshal if a bignum tag
	// is encountered in the input.
	BignumTagForbidden
)

type BinaryMarshalerMode added in v2.7.0

type BinaryMarshalerMode int

BinaryMarshalerMode specifies how to encode types that implement encoding.BinaryMarshaler.

const (
	// BinaryMarshalerByteString encodes the output of MarshalBinary to a CBOR byte string.
	BinaryMarshalerByteString BinaryMarshalerMode = iota

	// BinaryMarshalerNone does not recognize BinaryMarshaler implementations during encode.
	BinaryMarshalerNone
)

type BinaryUnmarshalerMode added in v2.7.0

type BinaryUnmarshalerMode int

BinaryUnmarshalerMode specifies how to decode into types that implement encoding.BinaryUnmarshaler.

const (
	// BinaryUnmarshalerByteString will invoke UnmarshalBinary on the contents of a CBOR byte
	// string when decoding into a value that implements BinaryUnmarshaler.
	BinaryUnmarshalerByteString BinaryUnmarshalerMode = iota

	// BinaryUnmarshalerNone does not recognize BinaryUnmarshaler implementations during decode.
	BinaryUnmarshalerNone
)

type ByteArrayMode added in v2.7.0

type ByteArrayMode int

ByteArrayMode specifies how to encode byte arrays.

const (
	// ByteArrayToByteSlice encodes byte arrays the same way that a byte slice with identical
	// length and contents is encoded.
	ByteArrayToByteSlice ByteArrayMode = iota

	// ByteArrayToArray encodes byte arrays to the CBOR array type with one unsigned integer
	// item for each byte in the array.
	ByteArrayToArray
)

type ByteSliceLaterFormatMode added in v2.7.0

type ByteSliceLaterFormatMode int

ByteSliceLaterFormatMode specifies which later format conversion hint (CBOR tag 21-23) to include (if any) when encoding Go byte slice to CBOR byte string. The encoder will always encode unmodified bytes from the byte slice and just wrap it within CBOR tag 21, 22, or 23 if specified. See "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.

const (
	// ByteSliceLaterFormatNone encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
	// without adding CBOR tag 21, 22, or 23.
	ByteSliceLaterFormatNone ByteSliceLaterFormatMode = iota

	// ByteSliceLaterFormatBase64URL encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
	// inside CBOR tag 21 (expected later conversion to base64url encoding, see RFC 8949 Section 3.4.5.2).
	ByteSliceLaterFormatBase64URL

	// ByteSliceLaterFormatBase64 encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
	// inside CBOR tag 22 (expected later conversion to base64 encoding, see RFC 8949 Section 3.4.5.2).
	ByteSliceLaterFormatBase64

	// ByteSliceLaterFormatBase16 encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
	// inside CBOR tag 23 (expected later conversion to base16 encoding, see RFC 8949 Section 3.4.5.2).
	ByteSliceLaterFormatBase16
)

type ByteString added in v2.5.0

type ByteString string

ByteString represents CBOR byte string (major type 2). ByteString can be used when using a Go []byte is not possible or convenient. For example, Go doesn't allow []byte as map key, so ByteString can be used to support data formats having CBOR map with byte string keys. ByteString can also be used to encode invalid UTF-8 string as CBOR byte string. See DecOption.MapKeyByteStringMode for more details.

func (ByteString) Bytes added in v2.5.0

func (bs ByteString) Bytes() []byte

Bytes returns bytes representing ByteString.

func (ByteString) MarshalCBOR added in v2.5.0

func (bs ByteString) MarshalCBOR() ([]byte, error)

MarshalCBOR encodes ByteString as CBOR byte string (major type 2).

func (*ByteString) UnmarshalCBOR added in v2.5.0

func (bs *ByteString) UnmarshalCBOR(data []byte) error

UnmarshalCBOR decodes CBOR byte string (major type 2) to ByteString. Decoding CBOR null and CBOR undefined sets ByteString to be empty.

type ByteStringEncoding added in v2.5.0

type ByteStringEncoding uint8

ByteStringEncoding specifies the base encoding that byte strings are notated.

const (
	// ByteStringBase16Encoding encodes byte strings in base16, without padding.
	ByteStringBase16Encoding ByteStringEncoding = iota

	// ByteStringBase32Encoding encodes byte strings in base32, without padding.
	ByteStringBase32Encoding

	// ByteStringBase32HexEncoding encodes byte strings in base32hex, without padding.
	ByteStringBase32HexEncoding

	// ByteStringBase64Encoding encodes byte strings in base64url, without padding.
	ByteStringBase64Encoding
)

type ByteStringExpectedFormatError added in v2.7.0

type ByteStringExpectedFormatError struct {
	// contains filtered or unexported fields
}

ByteStringExpectedFormatError is returned when unmarshaling CBOR byte string fails when using non-default ByteStringExpectedFormat decoding option that makes decoder expect a specified format such as base64, hex, etc.

func (*ByteStringExpectedFormatError) Error added in v2.7.0

func (*ByteStringExpectedFormatError) Unwrap added in v2.7.0

type ByteStringExpectedFormatMode added in v2.7.0

type ByteStringExpectedFormatMode int

ByteStringExpectedFormatMode specifies how to decode CBOR byte string into Go byte slice when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if the CBOR byte string does not contain the expected format (e.g. base64) specified. For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.

const (
	// ByteStringExpectedFormatNone copies the unmodified CBOR byte string into Go byte slice
	// if the byte string is not tagged by CBOR tag 21-23.
	ByteStringExpectedFormatNone ByteStringExpectedFormatMode = iota

	// ByteStringExpectedBase64URL expects CBOR byte strings to contain base64url-encoded bytes
	// if the byte string is not tagged by CBOR tag 21-23.  The decoder will attempt to decode
	// the base64url-encoded bytes into Go slice.
	ByteStringExpectedBase64URL

	// ByteStringExpectedBase64 expects CBOR byte strings to contain base64-encoded bytes
	// if the byte string is not tagged by CBOR tag 21-23.  The decoder will attempt to decode
	// the base64-encoded bytes into Go slice.
	ByteStringExpectedBase64

	// ByteStringExpectedBase16 expects CBOR byte strings to contain base16-encoded bytes
	// if the byte string is not tagged by CBOR tag 21-23.  The decoder will attempt to decode
	// the base16-encoded bytes into Go slice.
	ByteStringExpectedBase16
)

type ByteStringToStringMode added in v2.6.0

type ByteStringToStringMode int

ByteStringToStringMode specifies the behavior when decoding a CBOR byte string into a Go string.

const (
	// ByteStringToStringForbidden generates an error on an attempt to decode a CBOR byte string into a Go string.
	ByteStringToStringForbidden ByteStringToStringMode = iota

	// ByteStringToStringAllowed permits decoding a CBOR byte string into a Go string.
	ByteStringToStringAllowed

	// ByteStringToStringAllowedWithExpectedLaterEncoding permits decoding a CBOR byte string
	// into a Go string. Also, if the byte string is enclosed (directly or indirectly) by one of
	// the "expected later encoding" tags (numbers 21 through 23), the destination string will
	// be populated by applying the designated text encoding to the contents of the input byte
	// string.
	ByteStringToStringAllowedWithExpectedLaterEncoding
)

type ByteStringToTimeMode added in v2.7.0

type ByteStringToTimeMode int

ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.

const (
	// ByteStringToTimeForbidden generates an error on an attempt to decode a CBOR byte string into a Go time.Time.
	ByteStringToTimeForbidden ByteStringToTimeMode = iota

	// ByteStringToTimeAllowed permits decoding a CBOR byte string into a Go time.Time.
	ByteStringToTimeAllowed
)

type DecMode

type DecMode interface {
	// Unmarshal parses the CBOR-encoded data into the value pointed to by v
	// using the decoding mode.  If v is nil, not a pointer, or a nil pointer,
	// Unmarshal returns an error.
	//
	// See the documentation for Unmarshal for details.
	Unmarshal(data []byte, v interface{}) error

	// UnmarshalFirst parses the first CBOR data item into the value pointed to by v
	// using the decoding mode.  Any remaining bytes are returned in rest.
	//
	// If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
	//
	// See the documentation for Unmarshal for details.
	UnmarshalFirst(data []byte, v interface{}) (rest []byte, err error)

	// Valid checks whether data is a well-formed encoded CBOR data item and
	// that it complies with configurable restrictions such as MaxNestedLevels,
	// MaxArrayElements, MaxMapPairs, etc.
	//
	// If there are any remaining bytes after the CBOR data item,
	// an ExtraneousDataError is returned.
	//
	// WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity)
	// and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
	//
	// Deprecated: Valid is kept for compatibility and should not be used.
	// Use Wellformed instead because it has a more appropriate name.
	Valid(data []byte) error

	// Wellformed checks whether data is a well-formed encoded CBOR data item and
	// that it complies with configurable restrictions such as MaxNestedLevels,
	// MaxArrayElements, MaxMapPairs, etc.
	//
	// If there are any remaining bytes after the CBOR data item,
	// an ExtraneousDataError is returned.
	Wellformed(data []byte) error

	// NewDecoder returns a new decoder that reads from r using dm DecMode.
	NewDecoder(r io.Reader) *Decoder

	// DecOptions returns user specified options used to create this DecMode.
	DecOptions() DecOptions
}

DecMode is the main interface for CBOR decoding.

type DecOptions

type DecOptions struct {
	// DupMapKey specifies whether to enforce duplicate map key.
	DupMapKey DupMapKeyMode

	// TimeTag specifies whether or not untagged data items, or tags other
	// than tag 0 and tag 1, can be decoded to time.Time. If tag 0 or tag 1
	// appears in an input, the type of its content is always validated as
	// specified in RFC 8949. That behavior is not controlled by this
	// option. The behavior of the supported modes are:
	//
	//   DecTagIgnored (default): Untagged text strings and text strings
	//   enclosed in tags other than 0 and 1 are decoded as though enclosed
	//   in tag 0. Untagged unsigned integers, negative integers, and
	//   floating-point numbers (or those enclosed in tags other than 0 and
	//   1) are decoded as though enclosed in tag 1. Decoding a tag other
	//   than 0 or 1 enclosing simple values null or undefined into a
	//   time.Time does not modify the destination value.
	//
	//   DecTagOptional: Untagged text strings are decoded as though
	//   enclosed in tag 0. Untagged unsigned integers, negative integers,
	//   and floating-point numbers are decoded as though enclosed in tag
	//   1. Tags other than 0 and 1 will produce an error on attempts to
	//   decode them into a time.Time.
	//
	//   DecTagRequired: Only tags 0 and 1 can be decoded to time.Time. Any
	//   other input will produce an error.
	TimeTag DecTagMode

	// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
	// Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
	// require larger amounts of stack to deserialize. Don't increase this higher than you require.
	MaxNestedLevels int

	// MaxArrayElements specifies the max number of elements for CBOR arrays.
	// Default is 128*1024=131072 and it can be set to [16, 2147483647]
	MaxArrayElements int

	// MaxMapPairs specifies the max number of key-value pairs for CBOR maps.
	// Default is 128*1024=131072 and it can be set to [16, 2147483647]
	MaxMapPairs int

	// IndefLength specifies whether to allow indefinite length CBOR items.
	IndefLength IndefLengthMode

	// TagsMd specifies whether to allow CBOR tags (major type 6).
	TagsMd TagsMode

	// IntDec specifies which Go integer type (int64 or uint64) to use
	// when decoding CBOR int (major type 0 and 1) to Go interface{}.
	IntDec IntDecMode

	// MapKeyByteString specifies how to decode CBOR byte string as map key
	// when decoding CBOR map with byte string key into an empty interface value.
	// By default, an error is returned when attempting to decode CBOR byte string
	// as map key because Go doesn't allow []byte as map key.
	MapKeyByteString MapKeyByteStringMode

	// ExtraReturnErrors specifies extra conditions that should be treated as errors.
	ExtraReturnErrors ExtraDecErrorCond

	// DefaultMapType specifies Go map type to create and decode to
	// when unmarshalling CBOR into an empty interface value.
	// By default, unmarshal uses map[interface{}]interface{}.
	DefaultMapType reflect.Type

	// UTF8 specifies if decoder should decode CBOR Text containing invalid UTF-8.
	// By default, unmarshal rejects CBOR text containing invalid UTF-8.
	UTF8 UTF8Mode

	// FieldNameMatching specifies how string keys in CBOR maps are matched to Go struct field names.
	FieldNameMatching FieldNameMatchingMode

	// BigIntDec specifies how to decode CBOR bignum to Go interface{}.
	BigIntDec BigIntDecMode

	// DefaultByteStringType is the Go type that should be produced when decoding a CBOR byte
	// string into an empty interface value. Types to which a []byte is convertible are valid
	// for this option, except for array and pointer-to-array types. If nil, the default is
	// []byte.
	DefaultByteStringType reflect.Type

	// ByteStringToString specifies the behavior when decoding a CBOR byte string into a Go string.
	ByteStringToString ByteStringToStringMode

	// FieldNameByteString specifies the behavior when decoding a CBOR byte string map key as a
	// Go struct field name.
	FieldNameByteString FieldNameByteStringMode

	// UnrecognizedTagToAny specifies how to decode unrecognized CBOR tag into an empty interface.
	// Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
	UnrecognizedTagToAny UnrecognizedTagToAnyMode

	// TimeTagToAny specifies how to decode CBOR tag 0 and 1 into an empty interface (any).
	// Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
	TimeTagToAny TimeTagToAnyMode

	// SimpleValues is an immutable mapping from each CBOR simple value to a corresponding
	// unmarshal behavior. If nil, the simple values false, true, null, and undefined are mapped
	// to the Go analog values false, true, nil, and nil, respectively, and all other simple
	// values N (except the reserved simple values 24 through 31) are mapped to
	// cbor.SimpleValue(N). In other words, all well-formed simple values can be decoded.
	//
	// Users may provide a custom SimpleValueRegistry constructed via
	// NewSimpleValueRegistryFromDefaults.
	SimpleValues *SimpleValueRegistry

	// NaN specifies how to decode floating-point values (major type 7, additional information
	// 25 through 27) representing NaN (not-a-number).
	NaN NaNMode

	// Inf specifies how to decode floating-point values (major type 7, additional information
	// 25 through 27) representing positive or negative infinity.
	Inf InfMode

	// ByteStringToTime specifies how to decode CBOR byte string into Go time.Time.
	ByteStringToTime ByteStringToTimeMode

	// ByteStringExpectedFormat specifies how to decode CBOR byte string into Go byte slice
	// when the byte string is NOT enclosed in CBOR tag 21, 22, or 23.  An error is returned if
	// the CBOR byte string does not contain the expected format (e.g. base64) specified.
	// For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters"
	// in RFC 8949 Section 3.4.5.2.
	ByteStringExpectedFormat ByteStringExpectedFormatMode

	// BignumTag specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can
	// be decoded. Unlike BigIntDec, this option applies to all bignum tags encountered in a
	// CBOR input, independent of the type of the destination value of a particular Unmarshal
	// operation.
	BignumTag BignumTagMode

	// BinaryUnmarshaler specifies how to decode into types that implement
	// encoding.BinaryUnmarshaler.
	BinaryUnmarshaler BinaryUnmarshalerMode
}

DecOptions specifies decoding options.

func (DecOptions) DecMode

func (opts DecOptions) DecMode() (DecMode, error)

DecMode returns DecMode with immutable options and no tags (safe for concurrency).

func (DecOptions) DecModeWithSharedTags added in v2.1.0

func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error)

DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).

func (DecOptions) DecModeWithTags added in v2.1.0

func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error)

DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).

type DecTagMode added in v2.1.0

type DecTagMode int

DecTagMode specifies how decoder handles tag number.

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
)

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder reads and decodes CBOR values from io.Reader.

Example
type Animal struct {
	Age    int
	Name   string
	Owners []string
	Male   bool
}
data, _ := hex.DecodeString("a46341676504644d616c65f4644e616d656543616e6479664f776e65727382644d617279634a6f65a46341676506644d616c65f5644e616d656452756479664f776e657273816543696e6479a46341676502644d616c65f5644e616d656444756b65664f776e65727381664e6f72746f6e")
dec := cbor.NewDecoder(bytes.NewReader(data))
for {
	var animal Animal
	if err := dec.Decode(&animal); err != nil {
		if err != io.EOF {
			fmt.Println("error:", err)
		}
		break
	}
	fmt.Printf("%+v\n", animal)
}
Output:

{Age:4 Name:Candy Owners:[Mary Joe] Male:false}
{Age:6 Name:Rudy Owners:[Cindy] Male:true}
{Age:2 Name:Duke Owners:[Norton] Male:true}

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads and decodes from r using the default decoding options.

func (*Decoder) Buffered added in v2.5.0

func (dec *Decoder) Buffered() io.Reader

Buffered returns a reader for data remaining in Decoder's buffer. Returned reader is valid until the next call to Decode or Skip.

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode reads CBOR value and decodes it into the value pointed to by v.

func (*Decoder) NumBytesRead

func (dec *Decoder) NumBytesRead() int

NumBytesRead returns the number of bytes read.

func (*Decoder) Skip added in v2.5.0

func (dec *Decoder) Skip() error

Skip skips to the next CBOR data item (if there is any), otherwise it returns error such as io.EOF, io.UnexpectedEOF, etc.

type DiagMode added in v2.5.0

type DiagMode interface {
	// Diagnose returns extended diagnostic notation (EDN) of CBOR data items using this DiagMode.
	Diagnose([]byte) (string, error)

	// DiagnoseFirst returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest.
	DiagnoseFirst([]byte) (string, []byte, error)

	// DiagOptions returns user specified options used to create this DiagMode.
	DiagOptions() DiagOptions
}

DiagMode is the main interface for CBOR diagnostic notation.

type DiagOptions added in v2.5.0

type DiagOptions struct {
	// ByteStringEncoding specifies the base encoding that byte strings are notated.
	// Default is ByteStringBase16Encoding.
	ByteStringEncoding ByteStringEncoding

	// ByteStringHexWhitespace specifies notating with whitespace in byte string
	// when ByteStringEncoding is ByteStringBase16Encoding.
	ByteStringHexWhitespace bool

	// ByteStringText specifies notating with text in byte string
	// if it is a valid UTF-8 text.
	ByteStringText bool

	// ByteStringEmbeddedCBOR specifies notating embedded CBOR in byte string
	// if it is a valid CBOR bytes.
	ByteStringEmbeddedCBOR bool

	// CBORSequence specifies notating CBOR sequences.
	// otherwise, it returns an error if there are more bytes after the first CBOR.
	CBORSequence bool

	// FloatPrecisionIndicator specifies appending a suffix to indicate float precision.
	// Refer to https://www.rfc-editor.org/rfc/rfc8949.html#name-encoding-indicators.
	FloatPrecisionIndicator bool

	// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
	// Default is 32 levels and it can be set to [4, 65535]. Note that higher maximum levels of nesting can
	// require larger amounts of stack to deserialize. Don't increase this higher than you require.
	MaxNestedLevels int

	// MaxArrayElements specifies the max number of elements for CBOR arrays.
	// Default is 128*1024=131072 and it can be set to [16, 2147483647]
	MaxArrayElements int

	// MaxMapPairs specifies the max number of key-value pairs for CBOR maps.
	// Default is 128*1024=131072 and it can be set to [16, 2147483647]
	MaxMapPairs int
}

DiagOptions specifies Diag options.

func (DiagOptions) DiagMode added in v2.5.0

func (opts DiagOptions) DiagMode() (DiagMode, error)

DiagMode returns a DiagMode with immutable options.

type DupMapKeyError added in v2.1.0

type DupMapKeyError struct {
	Key   interface{}
	Index int
}

DupMapKeyError describes detected duplicate map key in CBOR map.

func (*DupMapKeyError) Error added in v2.1.0

func (e *DupMapKeyError) Error() string

type DupMapKeyMode added in v2.1.0

type DupMapKeyMode int

DupMapKeyMode specifies how to enforce duplicate map key. Two map keys are considered duplicates if:

  1. When decoding into a struct, both keys match the same struct field. The keys are also considered duplicates if neither matches any field and decoding to interface{} would produce equal (==) values for both keys.
  2. When decoding into a map, both keys are equal (==) when decoded into values of the destination map's key type.
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
)

type EncMode

type EncMode interface {
	Marshal(v interface{}) ([]byte, error)
	NewEncoder(w io.Writer) *Encoder
	EncOptions() EncOptions
}

EncMode is the main interface for CBOR encoding.

type EncOptions

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

	// BigIntConvert specifies how to encode big.Int values.
	BigIntConvert BigIntConvertMode

	// 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

	// NilContainers specifies how to encode nil slices and maps.
	NilContainers NilContainersMode

	// TagsMd specifies whether to allow CBOR tags (major type 6).
	TagsMd TagsMode

	// OmitEmptyMode specifies how to encode struct fields with omitempty tag.
	OmitEmpty OmitEmptyMode

	// String specifies which CBOR type to use when encoding Go strings.
	// - CBOR text string (major type 3) is default
	// - CBOR byte string (major type 2)
	String StringMode

	// FieldName specifies the CBOR type to use when encoding struct field names.
	FieldName FieldNameMode

	// ByteSliceLaterFormat specifies which later format conversion hint (CBOR tag 21-23)
	// to include (if any) when encoding Go byte slice to CBOR byte string. The encoder will
	// always encode unmodified bytes from the byte slice and just wrap it within
	// CBOR tag 21, 22, or 23 if specified.
	// See "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.
	ByteSliceLaterFormat ByteSliceLaterFormatMode

	// ByteArray specifies how to encode byte arrays.
	ByteArray ByteArrayMode

	// BinaryMarshaler specifies how to encode types that implement encoding.BinaryMarshaler.
	BinaryMarshaler BinaryMarshalerMode
}

EncOptions specifies encoding options.

func CTAP2EncOptions

func CTAP2EncOptions() EncOptions

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 CanonicalEncOptions

func CanonicalEncOptions() EncOptions

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 CoreDetEncOptions

func CoreDetEncOptions() EncOptions

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 PreferredUnsortedEncOptions

func PreferredUnsortedEncOptions() EncOptions

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 (EncOptions) EncMode

func (opts EncOptions) EncMode() (EncMode, error)

EncMode returns EncMode with immutable options and no tags (safe for concurrency).

func (EncOptions) EncModeWithSharedTags added in v2.1.0

func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error)

EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency).

func (EncOptions) EncModeWithTags added in v2.1.0

func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error)

EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency).

func (EncOptions) UserBufferEncMode added in v2.7.0

func (opts EncOptions) UserBufferEncMode() (UserBufferEncMode, error)

UserBufferEncMode returns UserBufferEncMode with immutable options and no tags (safe for concurrency).

func (EncOptions) UserBufferEncModeWithSharedTags added in v2.7.0

func (opts EncOptions) UserBufferEncModeWithSharedTags(tags TagSet) (UserBufferEncMode, error)

UserBufferEncModeWithSharedTags returns UserBufferEncMode with immutable options and mutable shared tags (safe for concurrency).

func (EncOptions) UserBufferEncModeWithTags added in v2.7.0

func (opts EncOptions) UserBufferEncModeWithTags(tags TagSet) (UserBufferEncMode, error)

UserBufferEncModeWithTags returns UserBufferEncMode with options and tags that are both immutable (safe for concurrency).

type EncTagMode added in v2.1.0

type EncTagMode int

EncTagMode specifies how encoder handles tag number.

const (
	// EncTagNone makes encoder not encode tag number.
	EncTagNone EncTagMode = iota

	// EncTagRequired makes encoder encode tag number.
	EncTagRequired
)

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder writes CBOR values to io.Writer.

Example
type Animal struct {
	Age    int
	Name   string
	Owners []string
	Male   bool
}
animals := []Animal{
	{Age: 4, Name: "Candy", Owners: []string{"Mary", "Joe"}, Male: false},
	{Age: 6, Name: "Rudy", Owners: []string{"Cindy"}, Male: true},
	{Age: 2, Name: "Duke", Owners: []string{"Norton"}, Male: true},
}
var buf bytes.Buffer
em, err := cbor.CanonicalEncOptions().EncMode()
if err != nil {
	fmt.Println("error:", err)
}
enc := em.NewEncoder(&buf)
for _, animal := range animals {
	err := enc.Encode(animal)
	if err != nil {
		fmt.Println("error:", err)
	}
}
fmt.Printf("%x\n", buf.Bytes())
Output:

a46341676504644d616c65f4644e616d656543616e6479664f776e65727382644d617279634a6f65a46341676506644d616c65f5644e616d656452756479664f776e657273816543696e6479a46341676502644d616c65f5644e616d656444756b65664f776e65727381664e6f72746f6e
Example (IndefiniteLengthArray)

ExampleEncoder_indefiniteLengthArray encodes a stream of elements as an indefinite length array. Encoder supports nested indefinite length values.

var buf bytes.Buffer
enc := cbor.NewEncoder(&buf)
// Start indefinite length array encoding.
if err := enc.StartIndefiniteArray(); err != nil {
	fmt.Println("error:", err)
}
// Encode array element.
if err := enc.Encode(1); err != nil {
	fmt.Println("error:", err)
}
// Encode array element.
if err := enc.Encode([]int{2, 3}); err != nil {
	fmt.Println("error:", err)
}
// Start a nested indefinite length array as array element.
if err := enc.StartIndefiniteArray(); err != nil {
	fmt.Println("error:", err)
}
// Encode nested array element.
if err := enc.Encode(4); err != nil {
	fmt.Println("error:", err)
}
// Encode nested array element.
if err := enc.Encode(5); err != nil {
	fmt.Println("error:", err)
}
// Close nested indefinite length array.
if err := enc.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
// Close outer indefinite length array.
if err := enc.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", buf.Bytes())
Output:

9f018202039f0405ffff
Example (IndefiniteLengthByteString)

ExampleEncoder_indefiniteLengthByteString encodes a stream of definite length byte string ("chunks") as an indefinite length byte string.

var buf bytes.Buffer
encoder := cbor.NewEncoder(&buf)
// Start indefinite length byte string encoding.
if err := encoder.StartIndefiniteByteString(); err != nil {
	fmt.Println("error:", err)
}
// Encode definite length byte string.
if err := encoder.Encode([]byte{1, 2}); err != nil {
	fmt.Println("error:", err)
}
// Encode definite length byte string.
if err := encoder.Encode([3]byte{3, 4, 5}); err != nil {
	fmt.Println("error:", err)
}
// Close indefinite length byte string.
if err := encoder.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", buf.Bytes())
Output:

5f42010243030405ff
Example (IndefiniteLengthMap)

ExampleEncoder_indefiniteLengthMap encodes a stream of elements as an indefinite length map. Encoder supports nested indefinite length values.

var buf bytes.Buffer
em, err := cbor.EncOptions{Sort: cbor.SortCanonical}.EncMode()
if err != nil {
	fmt.Println("error:", err)
}
enc := em.NewEncoder(&buf)
// Start indefinite length map encoding.
if err := enc.StartIndefiniteMap(); err != nil {
	fmt.Println("error:", err)
}
// Encode map key.
if err := enc.Encode("a"); err != nil {
	fmt.Println("error:", err)
}
// Encode map value.
if err := enc.Encode(1); err != nil {
	fmt.Println("error:", err)
}
// Encode map key.
if err := enc.Encode("b"); err != nil {
	fmt.Println("error:", err)
}
// Start an indefinite length array as map value.
if err := enc.StartIndefiniteArray(); err != nil {
	fmt.Println("error:", err)
}
// Encoded array element.
if err := enc.Encode(2); err != nil {
	fmt.Println("error:", err)
}
// Encoded array element.
if err := enc.Encode(3); err != nil {
	fmt.Println("error:", err)
}
// Close indefinite length array.
if err := enc.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
// Close indefinite length map.
if err := enc.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", buf.Bytes())
Output:

bf61610161629f0203ffff
Example (IndefiniteLengthTextString)

ExampleEncoder_indefiniteLengthTextString encodes a stream of definite length text string ("chunks") as an indefinite length text string.

var buf bytes.Buffer
encoder := cbor.NewEncoder(&buf)
// Start indefinite length text string encoding.
if err := encoder.StartIndefiniteTextString(); err != nil {
	fmt.Println("error:", err)
}
// Encode definite length text string.
if err := encoder.Encode("strea"); err != nil {
	fmt.Println("error:", err)
}
// Encode definite length text string.
if err := encoder.Encode("ming"); err != nil {
	fmt.Println("error:", err)
}
// Close indefinite length text string.
if err := encoder.EndIndefinite(); err != nil {
	fmt.Println("error:", err)
}
fmt.Printf("%x\n", buf.Bytes())
Output:

7f657374726561646d696e67ff

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w using the default encoding options.

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode writes the CBOR encoding of v.

func (*Encoder) EndIndefinite

func (enc *Encoder) EndIndefinite() error

EndIndefinite closes last opened indefinite length value.

func (*Encoder) StartIndefiniteArray

func (enc *Encoder) StartIndefiniteArray() error

StartIndefiniteArray starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the array until EndIndefinite is called.

func (*Encoder) StartIndefiniteByteString

func (enc *Encoder) StartIndefiniteByteString() error

StartIndefiniteByteString starts byte string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length byte strings ("chunks") as one contiguous string until EndIndefinite is called.

func (*Encoder) StartIndefiniteMap

func (enc *Encoder) StartIndefiniteMap() error

StartIndefiniteMap starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the map until EndIndefinite is called.

func (*Encoder) StartIndefiniteTextString

func (enc *Encoder) StartIndefiniteTextString() error

StartIndefiniteTextString starts text string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length text strings ("chunks") as one contiguous string until EndIndefinite is called.

type ExtraDecErrorCond added in v2.3.0

type ExtraDecErrorCond uint

ExtraDecErrorCond specifies extra conditions that should be treated as errors.

const ExtraDecErrorNone ExtraDecErrorCond = 0

ExtraDecErrorNone indicates no extra error condition.

const (
	// ExtraDecErrorUnknownField indicates error condition when destination
	// Go struct doesn't have a field matching a CBOR map key.
	ExtraDecErrorUnknownField ExtraDecErrorCond = 1 << iota
)

type ExtraneousDataError added in v2.5.0

type ExtraneousDataError struct {
	// contains filtered or unexported fields
}

ExtraneousDataError indicates found extraneous data following well-formed CBOR data item.

func (*ExtraneousDataError) Error added in v2.5.0

func (e *ExtraneousDataError) Error() string

type FieldNameByteStringMode added in v2.6.0

type FieldNameByteStringMode int

FieldNameByteStringMode specifies the behavior when decoding a CBOR byte string map key as a Go struct field name.

const (
	// FieldNameByteStringForbidden generates an error on an attempt to decode a CBOR byte string map key as a Go struct field name.
	FieldNameByteStringForbidden FieldNameByteStringMode = iota

	// FieldNameByteStringAllowed permits CBOR byte string map keys to be recognized as Go struct field names.
	FieldNameByteStringAllowed
)

type FieldNameMatchingMode added in v2.6.0

type FieldNameMatchingMode int

FieldNameMatchingMode specifies how string keys in CBOR maps are matched to Go struct field names.

const (
	// FieldNameMatchingPreferCaseSensitive prefers to decode map items into struct fields whose names (or tag
	// names) exactly match the item's key. If there is no such field, a map item will be decoded into a field whose
	// name is a case-insensitive match for the item's key.
	FieldNameMatchingPreferCaseSensitive FieldNameMatchingMode = iota

	// FieldNameMatchingCaseSensitive decodes map items only into a struct field whose name (or tag name) is an
	// exact match for the item's key.
	FieldNameMatchingCaseSensitive
)

type FieldNameMode added in v2.6.0

type FieldNameMode int

FieldNameMode specifies the CBOR type to use when encoding struct field names.

const (
	// FieldNameToTextString encodes struct fields to CBOR text string (major type 3).
	FieldNameToTextString FieldNameMode = iota

	// FieldNameToTextString encodes struct fields to CBOR byte string (major type 2).
	FieldNameToByteString
)

type InadmissibleTagContentTypeError added in v2.7.0

type InadmissibleTagContentTypeError struct {
	// contains filtered or unexported fields
}

InadmissibleTagContentTypeError is returned when unmarshaling built-in CBOR tags fails because of inadmissible type for tag content. Currently, the built-in CBOR tags in this codec are tags 0-3 and 21-23. See "Tag validity" in RFC 8949 Section 5.3.2.

func (*InadmissibleTagContentTypeError) Error added in v2.7.0

type IndefLengthMode added in v2.2.0

type IndefLengthMode int

IndefLengthMode specifies whether to allow indefinite length items.

const (
	// IndefLengthAllowed allows indefinite length items.
	IndefLengthAllowed IndefLengthMode = iota

	// IndefLengthForbidden disallows indefinite length items.
	IndefLengthForbidden
)

type IndefiniteLengthError added in v2.2.0

type IndefiniteLengthError struct {
	// contains filtered or unexported fields
}

IndefiniteLengthError indicates found disallowed indefinite length items.

func (*IndefiniteLengthError) Error added in v2.2.0

func (e *IndefiniteLengthError) Error() string

type InfConvertMode

type InfConvertMode int

InfConvertMode specifies how to encode Infinity and overrides ShortestFloatMode. ShortestFloatMode is not used for encoding Infinity and NaN values.

const (
	// InfConvertFloat16 always converts Inf to lossless IEEE binary16 (float16).
	InfConvertFloat16 InfConvertMode = iota

	// InfConvertNone never converts (used by CTAP2 Canonical CBOR).
	InfConvertNone

	// InfConvertReject returns UnsupportedValueError on attempts to encode an infinite value.
	InfConvertReject
)

type InfMode added in v2.7.0

type InfMode int

InfMode specifies how to decode floating-point values (major type 7, additional information 25 through 27) representing positive or negative infinity.

const (
	// InfDecodeAllowed will decode infinite values to Go float32 or float64.
	InfDecodeAllowed InfMode = iota

	// InfDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode an
	// infinite value.
	InfDecodeForbidden
)

type IntDecMode added in v2.3.0

type IntDecMode int

IntDecMode specifies which Go type (int64, uint64, or big.Int) should be used when decoding CBOR integers (major type 0 and 1) to Go interface{}.

const (
	// IntDecConvertNone affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
	// It decodes CBOR unsigned integer (major type 0) to:
	// - uint64
	// It decodes CBOR negative integer (major type 1) to:
	// - int64 if value fits
	// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
	IntDecConvertNone IntDecMode = iota

	// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
	// It decodes CBOR integers (major type 0 and 1) to:
	// - int64 if value fits
	// - big.Int or *big.Int (see BigIntDecMode) if value < math.MinInt64
	// - return UnmarshalTypeError if value > math.MaxInt64
	// Deprecated: IntDecConvertSigned should not be used.
	// Please use other options, such as IntDecConvertSignedOrError, IntDecConvertSignedOrBigInt, IntDecConvertNone.
	IntDecConvertSigned

	// IntDecConvertSignedOrFail affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
	// It decodes CBOR integers (major type 0 and 1) to:
	// - int64 if value fits
	// - return UnmarshalTypeError if value doesn't fit into int64
	IntDecConvertSignedOrFail

	// IntDecConvertSigned affects how CBOR integers (major type 0 and 1) decode to Go interface{}.
	// It makes CBOR integers (major type 0 and 1) decode to:
	// - int64 if value fits
	// - big.Int or *big.Int (see BigIntDecMode) if value doesn't fit into int64
	IntDecConvertSignedOrBigInt
)

type InvalidMapKeyTypeError added in v2.5.0

type InvalidMapKeyTypeError struct {
	GoType string
}

InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map. For example, Go doesn't allow slice as map key.

func (*InvalidMapKeyTypeError) Error added in v2.5.0

func (e *InvalidMapKeyTypeError) Error() string

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	// contains filtered or unexported fields
}

InvalidUnmarshalError describes an invalid argument passed to Unmarshal.

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type MapKeyByteStringMode added in v2.5.0

type MapKeyByteStringMode int

MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2) as Go map key when decoding CBOR map key into an empty Go interface value. Specifically, this option applies when decoding CBOR map into - Go empty interface, or - Go map with empty interface as key type. The CBOR map key types handled by this option are - byte string - tagged byte string - nested tagged byte string

const (
	// MapKeyByteStringAllowed allows CBOR byte string to be decoded as Go map key.
	// Since Go doesn't allow []byte as map key, CBOR byte string is decoded to
	// ByteString which has underlying string type.
	// This is the default setting.
	MapKeyByteStringAllowed MapKeyByteStringMode = iota

	// MapKeyByteStringForbidden forbids CBOR byte string being decoded as Go map key.
	// Attempting to decode CBOR byte string as map key into empty interface value
	// returns a decoding error.
	MapKeyByteStringForbidden
)

type Marshaler

type Marshaler interface {
	MarshalCBOR() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into valid CBOR.

type MarshalerError added in v2.7.0

type MarshalerError struct {
	// contains filtered or unexported fields
}

MarshalerError represents error from checking encoded CBOR data item returned from MarshalCBOR for well-formedness and some very limited tag validation.

func (*MarshalerError) Error added in v2.7.0

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap added in v2.7.0

func (e *MarshalerError) Unwrap() error

type MaxArrayElementsError added in v2.2.0

type MaxArrayElementsError struct {
	// contains filtered or unexported fields
}

MaxArrayElementsError indicates exceeded max number of elements for CBOR arrays.

func (*MaxArrayElementsError) Error added in v2.2.0

func (e *MaxArrayElementsError) Error() string

type MaxMapPairsError added in v2.2.0

type MaxMapPairsError struct {
	// contains filtered or unexported fields
}

MaxMapPairsError indicates exceeded max number of key-value pairs for CBOR maps.

func (*MaxMapPairsError) Error added in v2.2.0

func (e *MaxMapPairsError) Error() string

type MaxNestedLevelError added in v2.2.0

type MaxNestedLevelError struct {
	// contains filtered or unexported fields
}

MaxNestedLevelError indicates exceeded max nested level of any combination of CBOR arrays/maps/tags.

func (*MaxNestedLevelError) Error added in v2.2.0

func (e *MaxNestedLevelError) Error() string

type NaNConvertMode

type NaNConvertMode int

NaNConvertMode specifies how to encode NaN and overrides ShortestFloatMode. ShortestFloatMode is not used for encoding Infinity and NaN values.

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

	// NaNConvertReject returns UnsupportedValueError on attempts to encode a NaN value.
	NaNConvertReject
)

type NaNMode added in v2.7.0

type NaNMode int

NaNMode specifies how to decode floating-point values (major type 7, additional information 25 through 27) representing NaN (not-a-number).

const (
	// NaNDecodeAllowed will decode NaN values to Go float32 or float64.
	NaNDecodeAllowed NaNMode = iota

	// NaNDecodeForbidden will return an UnacceptableDataItemError on an attempt to decode a NaN value.
	NaNDecodeForbidden
)

type NilContainersMode added in v2.5.0

type NilContainersMode int

NilContainersMode specifies how to encode nil slices and maps.

const (
	// NilContainerAsNull encodes nil slices and maps as CBOR null.
	// This is the default.
	NilContainerAsNull NilContainersMode = iota

	// NilContainerAsEmpty encodes nil slices and maps as
	// empty container (CBOR bytestring, array, or map).
	NilContainerAsEmpty
)

type OmitEmptyMode added in v2.6.0

type OmitEmptyMode int

OmitEmptyMode specifies how to encode struct fields with omitempty tag. The default behavior omits if field value would encode as empty CBOR value.

const (
	// OmitEmptyCBORValue specifies that struct fields tagged with "omitempty"
	// should be omitted from encoding if the field would be encoded as an empty
	// CBOR value, such as CBOR false, 0, 0.0, nil, empty byte, empty string,
	// empty array, or empty map.
	OmitEmptyCBORValue OmitEmptyMode = iota

	// OmitEmptyGoValue specifies that struct fields tagged with "omitempty"
	// should be omitted from encoding if the field has an empty Go value,
	// defined as false, 0, 0.0, a nil pointer, a nil interface value, and
	// any empty array, slice, map, or string.
	// This behavior is the same as the current (aka v1) encoding/json package
	// included in Go.
	OmitEmptyGoValue
)

type RawMessage

type RawMessage []byte

RawMessage is a raw encoded CBOR value.

func (RawMessage) MarshalCBOR

func (m RawMessage) MarshalCBOR() ([]byte, error)

MarshalCBOR returns m or CBOR nil if m is nil.

func (*RawMessage) UnmarshalCBOR

func (m *RawMessage) UnmarshalCBOR(data []byte) error

UnmarshalCBOR creates a copy of data and saves to *m.

type RawTag added in v2.1.0

type RawTag struct {
	Number  uint64
	Content RawMessage
}

RawTag represents CBOR tag data, including tag number and raw tag content. RawTag implements Unmarshaler and Marshaler interfaces.

func (RawTag) MarshalCBOR added in v2.1.0

func (t RawTag) MarshalCBOR() ([]byte, error)

MarshalCBOR returns CBOR encoding of t.

func (*RawTag) UnmarshalCBOR added in v2.1.0

func (t *RawTag) UnmarshalCBOR(data []byte) error

UnmarshalCBOR sets *t with tag number and raw tag content copied from data.

type SemanticError

type SemanticError struct {
	// contains filtered or unexported fields
}

SemanticError is a description of a CBOR semantic error.

func (*SemanticError) Error

func (e *SemanticError) Error() string

type ShortestFloatMode

type ShortestFloatMode int

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.

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
)

type SimpleValue added in v2.5.0

type SimpleValue uint8

SimpleValue represents CBOR simple value. CBOR simple value is:

  • an extension point like CBOR tag.
  • a subset of CBOR major type 7 that isn't floating-point.
  • "identified by a number between 0 and 255, but distinct from that number itself". For example, "a simple value 2 is not equivalent to an integer 2" as a CBOR map key.

CBOR simple values identified by 20..23 are: "false", "true" , "null", and "undefined". Other CBOR simple values are currently unassigned/reserved by IANA.

func (SimpleValue) MarshalCBOR added in v2.6.0

func (sv SimpleValue) MarshalCBOR() ([]byte, error)

MarshalCBOR encodes SimpleValue as CBOR simple value (major type 7).

func (*SimpleValue) UnmarshalCBOR added in v2.6.0

func (sv *SimpleValue) UnmarshalCBOR(data []byte) error

UnmarshalCBOR decodes CBOR simple value (major type 7) to SimpleValue.

type SimpleValueRegistry added in v2.7.0

type SimpleValueRegistry struct {
	// contains filtered or unexported fields
}

SimpleValueRegistry is a registry of unmarshaling behaviors for each possible CBOR simple value number (0...23 and 32...255).

func NewSimpleValueRegistryFromDefaults added in v2.7.0

func NewSimpleValueRegistryFromDefaults(fns ...func(*SimpleValueRegistry) error) (*SimpleValueRegistry, error)

Creates a new SimpleValueRegistry. The registry state is initialized by executing the provided functions in order against a registry that is pre-populated with the defaults for all well-formed simple value numbers.

type SortMode

type SortMode int

SortMode identifies supported sorting order.

const (
	// SortNone encodes map pairs and struct fields in an arbitrary order.
	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

	// SortShuffle encodes map pairs and struct fields in a shuffled
	// order. This mode does not guarantee an unbiased permutation, but it
	// does guarantee that the runtime of the shuffle algorithm used will be
	// constant.
	SortFastShuffle SortMode = 3

	// 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
)

type StringMode added in v2.6.0

type StringMode int

StringMode specifies how to encode Go string values.

const (
	// StringToTextString encodes Go string to CBOR text string (major type 3).
	StringToTextString StringMode = iota

	// StringToByteString encodes Go string to CBOR byte string (major type 2).
	StringToByteString
)

type SyntaxError

type SyntaxError struct {
	// contains filtered or unexported fields
}

SyntaxError is a description of a CBOR syntax error.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Tag added in v2.1.0

type Tag struct {
	Number  uint64
	Content interface{}
}

Tag represents CBOR tag data, including tag number and unmarshaled tag content. Marshaling and unmarshaling of tag content is subject to any encode and decode options that would apply to enclosed data item if it were to appear outside of a tag.

type TagOptions added in v2.1.0

type TagOptions struct {
	DecTag DecTagMode
	EncTag EncTagMode
}

TagOptions specifies how encoder and decoder handle tag number.

type TagSet added in v2.1.0

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)
	// contains filtered or unexported methods
}

TagSet is an interface to add and remove tag info. It is used by EncMode and DecMode to provide CBOR tag support.

func NewTagSet added in v2.1.0

func NewTagSet() TagSet

NewTagSet returns TagSet (safe for concurrency).

type TagsMdError added in v2.2.0

type TagsMdError struct {
}

TagsMdError indicates found disallowed CBOR tags.

func (*TagsMdError) Error added in v2.2.0

func (e *TagsMdError) Error() string

type TagsMode added in v2.2.0

type TagsMode int

TagsMode specifies whether to allow CBOR tags.

const (
	// TagsAllowed allows CBOR tags.
	TagsAllowed TagsMode = iota

	// TagsForbidden disallows CBOR tags.
	TagsForbidden
)

type TimeMode

type TimeMode int

TimeMode specifies how to encode time.Time values.

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
)

type TimeTagToAnyMode added in v2.7.0

type TimeTagToAnyMode int

TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any). Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.

const (
	// TimeTagToTime decodes CBOR tag 0 and 1 into a time.Time value
	// when decoding tag 0 or 1 into an empty interface.
	TimeTagToTime TimeTagToAnyMode = iota

	// TimeTagToRFC3339 decodes CBOR tag 0 and 1 into a time string in RFC3339 format
	// when decoding tag 0 or 1 into an empty interface.
	TimeTagToRFC3339

	// TimeTagToRFC3339Nano decodes CBOR tag 0 and 1 into a time string in RFC3339Nano format
	// when decoding tag 0 or 1 into an empty interface.
	TimeTagToRFC3339Nano
)

type UTF8Mode added in v2.5.0

type UTF8Mode int

UTF8Mode option specifies if decoder should decode CBOR Text containing invalid UTF-8 string.

const (
	// UTF8RejectInvalid rejects CBOR Text containing
	// invalid UTF-8 string.
	UTF8RejectInvalid UTF8Mode = iota

	// UTF8DecodeInvalid allows decoding CBOR Text containing
	// invalid UTF-8 string.
	UTF8DecodeInvalid
)

type UnacceptableDataItemError added in v2.7.0

type UnacceptableDataItemError struct {
	CBORType string
	Message  string
}

UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item that is not acceptable to a specific CBOR-based application protocol ("invalid or unexpected" as described in RFC 8949 Section 5 Paragraph 3).

func (UnacceptableDataItemError) Error added in v2.7.0

type UnknownFieldError added in v2.3.0

type UnknownFieldError struct {
	Index int
}

UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.

func (*UnknownFieldError) Error added in v2.3.0

func (e *UnknownFieldError) Error() string

type UnmarshalTypeError

type UnmarshalTypeError struct {
	CBORType        string // type of CBOR value
	GoType          string // type of Go value it could not be decoded into
	StructFieldName string // name of the struct field holding the Go value (optional)
	// contains filtered or unexported fields
}

UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type.

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalCBOR([]byte) error
}

Unmarshaler is the interface implemented by types that wish to unmarshal CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR must copy the CBOR data if it needs to use it after returning.

type UnrecognizedTagToAnyMode added in v2.6.0

type UnrecognizedTagToAnyMode int

UnrecognizedTagToAnyMode specifies how to decode unrecognized CBOR tag into an empty interface (any). Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.

const (
	// UnrecognizedTagNumAndContentToAny decodes CBOR tag number and tag content to cbor.Tag
	// when decoding unrecognized CBOR tag into an empty interface.
	UnrecognizedTagNumAndContentToAny UnrecognizedTagToAnyMode = iota

	// UnrecognizedTagContentToAny decodes only CBOR tag content (into its default type)
	// when decoding unrecognized CBOR tag into an empty interface.
	UnrecognizedTagContentToAny
)

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

UnsupportedTypeError is returned by Marshal when attempting to encode value of an unsupported type.

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

type UnsupportedValueError added in v2.6.0

type UnsupportedValueError struct {
	// contains filtered or unexported fields
}

UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

func (*UnsupportedValueError) Error added in v2.6.0

func (e *UnsupportedValueError) Error() string

type UserBufferEncMode added in v2.7.0

type UserBufferEncMode interface {
	EncMode
	MarshalToBuffer(v interface{}, buf *bytes.Buffer) error
	// contains filtered or unexported methods
}

UserBufferEncMode is an interface for CBOR encoding, which extends EncMode by adding MarshalToBuffer to support user specified buffer rather than encoding into the built-in buffer pool.

type WrongTagError added in v2.1.0

type WrongTagError struct {
	RegisteredType   reflect.Type
	RegisteredTagNum []uint64
	TagNum           []uint64
}

WrongTagError describes mismatch between CBOR tag and registered tag.

func (*WrongTagError) Error added in v2.1.0

func (e *WrongTagError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL