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 := cbor.EncOptions{...}.EncMode()
em := cbor.CanonicalEncOptions().EncMode()
em := cbor.CTAP2EncOptions().EncMode()
Modes use immutable options to avoid side-effects and simplify concurrency. Behavior of modes won't accidentally change at runtime after they're created.
Modes are intended to be reused and are safe for concurrent use.
EncMode and DecMode Interfaces
// EncMode interface uses immutable options and is safe for concurrent use.
type EncMode interface {
Marshal(v interface{}) ([]byte, error)
NewEncoder(w io.Writer) *Encoder
EncOptions() EncOptions // returns copy of options
}
// DecMode interface uses immutable options and is safe for concurrent use.
type DecMode interface {
Unmarshal(data []byte, v interface{}) error
NewDecoder(r io.Reader) *Decoder
DecOptions() DecOptions // returns copy of options
}
Using Default Encoding Mode
b, err := cbor.Marshal(v) encoder := cbor.NewEncoder(w) err = encoder.Encode(v)
Using Default Decoding Mode
err := cbor.Unmarshal(b, &v) decoder := cbor.NewDecoder(r) err = decoder.Decode(&v)
Creating and Using Encoding Modes
// Create EncOptions using either struct literal or a function. opts := cbor.CanonicalEncOptions() // If needed, modify encoding options opts.Time = cbor.TimeUnix // Create reusable EncMode interface with immutable options, safe for concurrent use. em, err := opts.EncMode() // Use EncMode like encoding/json, with same function signatures. b, err := em.Marshal(v) // or encoder := em.NewEncoder(w) err := encoder.Encode(v) // 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 fxamacker/cbor-fuzz.
Index ¶
- Constants
- func Marshal(v interface{}) ([]byte, error)
- func Unmarshal(data []byte, v interface{}) error
- func Valid(data []byte) error
- type BigIntConvertMode
- type ByteString
- type DecMode
- type DecOptions
- type DecTagMode
- type Decoder
- type DupMapKeyError
- type DupMapKeyMode
- type EncMode
- type EncOptions
- type EncTagMode
- type Encoder
- type ExtraDecErrorCond
- type Float16
- type IndefLengthMode
- type IndefiniteLengthError
- type InfConvertMode
- type IntDecMode
- type InvalidUnmarshalError
- type MapKeyByteStringMode
- type Marshaler
- type MaxArrayElementsError
- type MaxMapPairsError
- type MaxNestedLevelError
- type NaNConvertMode
- type Precision
- type RawMessage
- type RawTag
- type SemanticError
- type ShortestFloatMode
- type SortMode
- type SyntaxError
- type Tag
- type TagOptions
- type TagSet
- type TagsMdError
- type TagsMode
- type TimeMode
- type UnknownFieldError
- type UnmarshalTypeError
- type Unmarshaler
- type UnsupportedTypeError
- type WrongTagError
Constants ¶
const ErrInvalidNaNValue = float16Error("float16: invalid NaN value, expected IEEE 754 NaN")
ErrInvalidNaNValue indicates a NaN was not received.
Variables ¶
This section is empty.
Functions ¶
func Marshal ¶
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.
func Unmarshal ¶
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.
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:
- "cbor" key in struct field tag,
- "json" key in struct field tag,
- 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.
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).
Types ¶
type BigIntConvertMode ¶
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 interger (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 )
type ByteString ¶
type ByteString struct {
// contains filtered or unexported fields
}
func NewByteString ¶
func NewByteString(data []byte) ByteString
func (ByteString) Bytes ¶
func (bs ByteString) Bytes() []byte
func (ByteString) String ¶
func (bs ByteString) String() string
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
// Valid checks whether the CBOR data is complete and well-formed.
Valid(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 to check validity of time.Time (e.g. valid tag number and tag content type).
// For now, valid tag number means 0 or 1 as specified in RFC 7049 if the Go type is time.Time.
TimeTag DecTagMode
// MaxNestedLevels specifies the max nested levels allowed for any combination of CBOR array, maps, and tags.
// Default is 32 levels and it can be set to [4, 256].
MaxNestedLevels int
// MaxArrayElements specifies the max number of elements for CBOR arrays.
// Default is 128*1024=131072 and it can be set to [16, 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 whether to use a wrapper object for byte strings.
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
}
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 ¶
func (opts DecOptions) DecModeWithSharedTags(tags TagSet) (DecMode, error)
DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).
func (DecOptions) DecModeWithTags ¶
func (opts DecOptions) DecModeWithTags(tags TagSet) (DecMode, error)
DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).
type DecTagMode ¶
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.
func NewDecoder ¶
NewDecoder returns a new decoder that reads and decodes from r using the default decoding options.
func (*Decoder) NumBytesRead ¶
NumBytesRead returns the number of bytes read.
type DupMapKeyError ¶
type DupMapKeyError struct {
Key interface{}
Index int
}
DupMapKeyError describes detected duplicate map key in CBOR map.
func (*DupMapKeyError) Error ¶
func (e *DupMapKeyError) Error() string
type DupMapKeyMode ¶
type DupMapKeyMode int
DupMapKeyMode specifies how to enforce duplicate map key.
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
// TagsMd specifies whether to allow CBOR tags (major type 6).
TagsMd TagsMode
}
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:
- "Integers must be encoded as small as possible."
- "The representations of any floating-point values are not changed."
- "The expression of lengths in major types 2 through 5 must be as short as possible."
- "Indefinite-length items must be made into definite-length items.""
- The keys in every map must be sorted in bytewise lexicographic order. See SortBytewiseLexical for details.
- "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:
- "Integers must be as small as possible."
- "The expression of lengths in major types 2 through 5 must be as short as possible."
- The keys in every map must be sorted in length-first sorting order. See SortLengthFirst for details.
- "Indefinite-length items must be made into definite-length items."
- "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:
- "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"
- "Indefinite-length items MUST NOT appear."
- "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:
- "The preferred serialization always uses the shortest form of representing the argument (Section 3);"
- "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)."
- "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 ¶
func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error)
EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency).
func (EncOptions) EncModeWithTags ¶
func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error)
EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency).
type EncTagMode ¶
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.
func NewEncoder ¶
NewEncoder returns a new encoder that writes to w using the default encoding options.
func (*Encoder) EndIndefinite ¶
EndIndefinite closes last opened indefinite length value.
func (*Encoder) StartIndefiniteArray ¶
StartIndefiniteArray starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the array until EndIndefinite is called.
func (*Encoder) StartIndefiniteByteString ¶
StartIndefiniteByteString starts byte string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length byte strings ("chunks") as one continguous string until EndIndefinite is called.
func (*Encoder) StartIndefiniteMap ¶
StartIndefiniteMap starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the map until EndIndefinite is called.
func (*Encoder) StartIndefiniteTextString ¶
StartIndefiniteTextString starts text string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length text strings ("chunks") as one continguous string until EndIndefinite is called.
type ExtraDecErrorCond ¶
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 Float16 ¶
type Float16 uint16
Float16 represents IEEE 754 half-precision floating-point numbers (binary16).
func FromNaN32ps ¶
FromNaN32ps converts nan to IEEE binary16 NaN while preserving both signaling and payload. Unlike Fromfloat32(), which can only return qNaN because it sets quiet bit = 1, this can return both sNaN and qNaN. If the result is infinity (sNaN with empty payload), then the lowest bit of payload is set to make the result a NaN. Returns ErrInvalidNaNValue and 0x7c01 (sNaN) if nan isn't IEEE 754 NaN. This function was kept simple to be able to inline.
func Frombits ¶
Frombits returns the float16 number corresponding to the IEEE 754 binary16 representation u16, with the sign bit of u16 and the result in the same bit position. Frombits(Bits(x)) == x.
func Fromfloat32 ¶
Fromfloat32 returns a Float16 value converted from f32. Conversion uses IEEE default rounding (nearest int, with ties to even).
func Inf ¶
Inf returns a Float16 with an infinity value with the specified sign. A sign >= returns positive infinity. A sign < 0 returns negative infinity.
func NaN ¶
func NaN() Float16
NaN returns a Float16 of IEEE 754 binary16 not-a-number (NaN). Returned NaN value 0x7e01 has all exponent bits = 1 with the first and last bits = 1 in the significand. This is consistent with Go's 64-bit math.NaN(). Canonical CBOR in RFC 7049 uses 0x7e00.
func (Float16) Bits ¶
Bits returns the IEEE 754 binary16 representation of f, with the sign bit of f and the result in the same bit position. Bits(Frombits(x)) == x.
func (Float16) Float32 ¶
Float32 returns a float32 converted from f (Float16). This is a lossless conversion.
func (Float16) IsInf ¶
IsInf reports whether f is an infinity (inf). A sign > 0 reports whether f is positive inf. A sign < 0 reports whether f is negative inf. A sign == 0 reports whether f is either inf.
func (Float16) IsQuietNaN ¶
IsQuietNaN reports whether f is a quiet (non-signaling) IEEE 754 binary16 “not-a-number” value.
type IndefLengthMode ¶
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 ¶
type IndefiniteLengthError struct {
// contains filtered or unexported fields
}
IndefiniteLengthError indicates found disallowed indefinite length items.
func (*IndefiniteLengthError) Error ¶
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 )
type IntDecMode ¶
type IntDecMode int
IntDecMode specifies which Go int type (int64 or uint64) should be used when decoding CBOR int (major type 0 and 1) to Go interface{}.
const ( // IntDecConvertNone affects how CBOR int (major type 0 and 1) decodes to Go interface{}. // It makes CBOR positive int (major type 0) decode to uint64 value, and // CBOR negative int (major type 1) decode to int64 value. IntDecConvertNone IntDecMode = iota // IntDecConvertSigned affects how CBOR int (major type 0 and 1) decodes to Go interface{}. // It makes CBOR positive/negative int (major type 0 and 1) decode to int64 value. // If value overflows int64, UnmarshalTypeError is returned. IntDecConvertSigned )
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 ¶
type MapKeyByteStringMode int
MapKeyByteStringMode specifies whether to use a wrapper object for byte strings.
const ( // MapKeyByteStringFail affects how a CBOR byte string as a map key is decoded. // It makes the parsing fail as Go cannot use []byte as a map key. MapKeyByteStringFail MapKeyByteStringMode = iota // MapKeyByteStringWrap affects how a CBOR byte string as a map key is decoded. // It allows the parsing to succeed by wrapping the byte string in a wrapper object // that can be used as a map key in Go. MapKeyByteStringWrap )
type Marshaler ¶
Marshaler is the interface implemented by types that can marshal themselves into valid CBOR.
type MaxArrayElementsError ¶
type MaxArrayElementsError struct {
// contains filtered or unexported fields
}
MaxArrayElementsError indicates exceeded max number of elements for CBOR arrays.
func (*MaxArrayElementsError) Error ¶
func (e *MaxArrayElementsError) Error() string
type MaxMapPairsError ¶
type MaxMapPairsError struct {
// contains filtered or unexported fields
}
MaxMapPairsError indicates exceeded max number of key-value pairs for CBOR maps.
func (*MaxMapPairsError) Error ¶
func (e *MaxMapPairsError) Error() string
type MaxNestedLevelError ¶
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 ¶
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 )
type Precision ¶
type Precision int
Precision indicates whether the conversion to Float16 is exact, subnormal without dropped bits, inexact, underflow, or overflow.
const ( // PrecisionExact is for non-subnormals that don't drop bits during conversion. // All of these can round-trip. Should always convert to float16. PrecisionExact Precision = iota // PrecisionUnknown is for subnormals that don't drop bits during conversion but // not all of these can round-trip so precision is unknown without more effort. // Only 2046 of these can round-trip and the rest cannot round-trip. PrecisionUnknown // PrecisionInexact is for dropped significand bits and cannot round-trip. // Some of these are subnormals. Cannot round-trip float32->float16->float32. PrecisionInexact // PrecisionUnderflow is for Underflows. Cannot round-trip float32->float16->float32. PrecisionUnderflow // PrecisionOverflow is for Overflows. Cannot round-trip float32->float16->float32. PrecisionOverflow )
func PrecisionFromfloat32 ¶
PrecisionFromfloat32 returns Precision without performing the conversion. Conversions from both Infinity and NaN values will always report PrecisionExact even if NaN payload or NaN-Quiet-Bit is lost. This function is kept simple to allow inlining and run < 0.5 ns/op, to serve as a fast filter.
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 ¶
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 ¶
MarshalCBOR returns CBOR encoding of t.
func (*RawTag) UnmarshalCBOR ¶
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 SortMode ¶
type SortMode int
SortMode identifies supported sorting order.
const ( // SortNone means no sorting. SortNone SortMode = 0 // SortLengthFirst causes map keys or struct fields to be sorted such that: // - If two keys have different lengths, the shorter one sorts earlier; // - If two keys have the same length, the one with the lower value in // (byte-wise) lexical order sorts earlier. // It is used in "Canonical CBOR" encoding in RFC 7049 3.9. SortLengthFirst SortMode = 1 // SortBytewiseLexical causes map keys or struct fields to be sorted in the // bytewise lexicographic order of their deterministic CBOR encodings. // It is used in "CTAP2 Canonical CBOR" and "Core Deterministic Encoding" // in RFC 7049bis. SortBytewiseLexical SortMode = 2 // SortCanonical is used in "Canonical CBOR" encoding in RFC 7049 3.9. SortCanonical SortMode = SortLengthFirst // SortCTAP2 is used in "CTAP2 Canonical CBOR". SortCTAP2 SortMode = SortBytewiseLexical // SortCoreDeterministic is used in "Core Deterministic Encoding" in RFC 7049bis. SortCoreDeterministic SortMode = SortBytewiseLexical )
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 ¶
type Tag struct {
Number uint64
Content interface{}
}
Tag represents CBOR tag data, including tag number and unmarshaled tag content.
type TagOptions ¶
type TagOptions struct {
DecTag DecTagMode
EncTag EncTagMode
}
TagOptions specifies how encoder and decoder handle tag number.
type TagSet ¶
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.
type TagsMdError ¶
type TagsMdError struct {
}
TagsMdError indicates found disallowed CBOR tags.
func (*TagsMdError) Error ¶
func (e *TagsMdError) Error() string
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 UnknownFieldError ¶
type UnknownFieldError struct {
Index int
}
UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.
func (*UnknownFieldError) Error ¶
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 ¶
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 UnsupportedTypeError ¶
UnsupportedTypeError is returned by Marshal when attempting to encode value of an unsupported type.
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
type WrongTagError ¶
WrongTagError describes mismatch between CBOR tag and registered tag.
func (*WrongTagError) Error ¶
func (e *WrongTagError) Error() string