CBOR.js - JavaScript API
Abstract
This document describes a JavaScript API for encoding and decoding data in the
CBOR [RFC8949] format.
Through platform independent definitions of deterministic encoding and
a textual representation of CBOR data items, compatible implementations could,
together with the rich set of data types,
provide a viable alternative to JSON.
Table of Contents
1. Introduction
This document describes a JavaScript API for encoding and decoding data in the
CBOR [RFC8949] format.
The API loosely mimics the "JSON" object by exposing a single global object,
unsurprisingly named "CBOR".
To minimize the need for application developers having detailed knowledge of CBOR,
the CBOR.js API provides a set of high level wrapper objects.
The wrapper objects are used for encoding CBOR data items,
as well as being the result of CBOR decoding.
The CBOR.js API provides some specific features including:
Note: in this specification CBOR data items are subsequently referred to as CBOR objects.
2. CBOR Wrapper Objects
This section describes the wrapper objects and their specific methods.
Note that using the "new" operator with a wrapper object
is flagged as an error.
The following table lists the wrapper objects and their relation to
the CBOR objects supported by this specification:
- See also Integer Numbers.
- See also Floating Point Numbers.
Note that this implementation does not support CBOR "simple" values beyond
true, false, null, and the three floating point variants.
The wrapper concept adds strict type checking to the API.
That is, if an application expects a CBOR integer and calls
getInt32(), an exception will
be thrown if the referenced object is not an instance of
CBOR.Int or if the CBOR integer
does not fit in a 32-bit two-complement representation.
See also Common Wrapper Methods.
2.1. CBOR.Int
Syntax | CBOR.Int(value) |
Description | Constructor. Creates a CBOR integer wrapper object.
See also Integer Numbers. |
|
Parameter | Type | Description |
value | Number | Integer to be wrapped. |
|
Returns | Description |
CBOR.Int | Wrapper object. |
2.1.1. CBOR.Int Methods
2.1.1.1. getInt()
Syntax | getInt() |
Description | Get CBOR integer.Values outside of -253+1 to 253-1 will cause an exception to be thrown. See also getBigInt(). |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.2. getInt8()
Syntax | getInt8() |
Description | Get CBOR integer. Values outside of -0x80 to 0x7f will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.3. getUint8()
Syntax | getUint8() |
Description | Get CBOR integer. Values outside of 0 to 0xff will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.4. getInt16()
Syntax | getInt16() |
Description | Get CBOR integer. Values outside of -0x8000 to 0x7fff will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.5. getUint16()
Syntax | getUint16() |
Description | Get CBOR integer. Values outside of 0 to 0xffff will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.6. getInt32()
Syntax | getInt32() |
Description | Get CBOR integer. Values outside of -0x80000000 to 0x7fffffff will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.7. getUint32()
Syntax | getUint32() |
Description | Get CBOR integer. Values outside of 0 to 0xffffffff will cause an exception to be thrown. |
|
Returns | Description |
Number | Decoded integer. |
2.1.1.8. getInt64()
Syntax | getInt64() |
Description | Get CBOR integer. Values outside of -0x8000000000000000 to 0x7fffffffffffffff will cause an exception to be thrown. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.1.1.9. getUint64()
Syntax | getUint64() |
Description | Get CBOR integer. Values outside of 0 to 0xffffffffffffffff will cause an exception to be thrown. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.1.1.10. getBigInt()
Syntax | getBigInt() |
Description | Get CBOR integer of any size.
See also Integer Numbers. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.2. CBOR.BigInt
Syntax | CBOR.BigInt(value) |
Description | Constructor. Creates a CBOR big integer wrapper object.
See also Integer Numbers. |
|
Parameter | Type | Description |
value | BigInt | Big integer to be wrapped. |
|
Returns | Description |
CBOR.BigInt | Wrapper object. |
2.2.1. CBOR.BigInt Methods
2.2.1.1. getInt64()
Syntax | getInt64() |
Description | Get CBOR integer. Values outside of -0x8000000000000000 to 0x7fffffffffffffff will cause an exception to be thrown. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.2.1.2. getUint64()
Syntax | getUint64() |
Description | Get CBOR integer. Values outside of 0 to 0xffffffffffffffff will cause an exception to be thrown. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.2.1.3. getBigInt()
Syntax | getBigInt() |
Description | Get CBOR integer of any size.
See also Integer Numbers. |
|
Returns | Description |
BigInt | Decoded big integer. |
2.3. CBOR.Float
Syntax | CBOR.Float(value) |
Description | Constructor. Creates a CBOR floating point wrapper object.
See also Floating Point Numbers. |
|
Parameter | Type | Description |
value | Number | Floating point number to be wrapped. |
|
Returns | Description |
CBOR.Float | Wrapper object. |
2.3.1. CBOR.Float Methods
2.3.1.1. getFloat16()
Syntax | getFloat16() |
Description | Get CBOR floating point value. Note: the CBOR object must be a 16-bit IEEE-754 item, otherwise an exception will be thrown. |
|
Returns | Description |
Number | Decoded floating point number. |
2.3.1.2. getFloat32()
Syntax | getFloat32() |
Description | Get CBOR floating point value. Note: the CBOR object must be a 16-bit or 32-bit IEEE-754 item, otherwise an exception will be thrown. |
|
Returns | Description |
Number | Decoded floating point number. |
2.3.1.3. getFloat64()
Syntax | getFloat64() |
Description | Get CBOR floating point value. |
|
Returns | Description |
Number | Decoded floating point number. |
2.3.2. CBOR.Float Properties
2.3.2.1. length
Name | Type | Description |
length | Number | Length in bytes of the underlying CBOR IEEE 754 type. |
2.4. CBOR.String
Syntax | CBOR.String(textString) |
Description | Constructor. Creates a CBOR text string wrapper object. |
|
Parameter | Type | Description |
textString | String | String to be wrapped. |
|
Returns | Description |
CBOR.String | Wrapper object. |
2.4.1. CBOR.String Methods
2.4.1.1. getString()
Syntax | getString() |
Description | Get CBOR text string. |
|
Returns | Description |
String | Decoded text string. |
2.5. CBOR.Bytes
Syntax | CBOR.Bytes(byteString) |
Description | Constructor. Creates a CBOR byte string wrapper object. |
|
Parameter | Type | Description |
byteString | Uint8Array | Binary data to be wrapped. |
|
Returns | Description |
CBOR.Bytes | Wrapper object. |
2.5.1. CBOR.Bytes Methods
2.5.1.1. getBytes()
Syntax | getBytes() |
Description | Get CBOR byte string. |
|
Returns | Description |
Uint8Array | Decoded byte string. |
2.6. CBOR.Boolean
Syntax | CBOR.Boolean(value) |
Description | Constructor. Creates a CBOR boolean wrapper object. |
|
Parameter | Type | Description |
value | Boolean | Boolean to be wrapped. |
|
Returns | Description |
CBOR.Boolean | Wrapper object. |
2.6.1. CBOR.Boolean Methods
2.6.1.1. getBoolean()
Syntax | getBoolean() |
Description | Get CBOR boolean. |
|
Returns | Description |
Boolean | Decoded boolean. |
2.7. CBOR.Null
Syntax | CBOR.Null() |
Description | Constructor. Creates a CBOR null wrapper object.
See also isNull(). |
|
Returns | Description |
CBOR.Null | Wrapper object. |
2.8. CBOR.Array
Syntax | CBOR.Array() |
Description | Constructor. Creates an empty CBOR array wrapper object. |
|
Returns | Description |
CBOR.Array | Wrapper object. |
2.8.1. CBOR.Array Methods
2.8.1.1. add()
Syntax | add(object) |
Description | Add CBOR wrapper object to the array. |
|
Parameter | Type | Description |
object | CBOR.Wrapper | Object to be appended to the array. |
|
Returns | Description |
this | Current object. |
2.8.1.2. get()
Syntax | get(index) |
Description | Get CBOR wrapper object from array.
If index is out of range, an exception is thrown. |
|
Parameter | Type | Description |
index | Number | Index (0..length-1) of object. |
|
Returns | Description |
CBOR.Wrapper | Retrieved object. |
2.8.1.3. toArray()
Syntax | toArray() |
Description | Copy array. |
|
Returns | Description |
[...] | JavaScript array holding a copy of current CBOR.Wrapper objects. |
2.8.2. CBOR.Array Properties
2.8.2.1. length
Name | Type | Description |
length | Number | Number of objects in the array. |
2.9. CBOR.Map
Syntax | CBOR.Map() |
Description | Constructor. Creates an empty CBOR map wrapper object. |
|
Returns | Description |
CBOR.Map | Wrapper object. |
2.9.1. CBOR.Map Methods
2.9.1.1. set()
Syntax | set(key, value) |
Description | Set map entry.
If key entry is already defined, an exception is thrown.
|
|
Parameter | Type | Description |
key | CBOR.Wrapper | Key (name) wrapper object. |
value | CBOR.Wrapper | Value wrapper object. |
|
Returns | Description |
this | Current object. |
2.9.1.2. get()
Syntax | get(key) |
Description | Get map entry.
If key entry is undefined, an exception is thrown. |
|
Parameter | Type | Description |
key | CBOR.Wrapper | Key (name) wrapper object. |
|
Returns | Description |
CBOR.Wrapper | Retrieved object. |
2.9.1.3. getConditional()
Syntax | getConditional(key, defaultValue) |
Description | Get map entry conditionally. |
|
Parameter | Type | Description |
key | CBOR.Wrapper | Key (name) wrapper object. |
defaultValue | CBOR.Wrapper | Value to return if key entry is undefined.
Note:
defaultValue may be null . |
|
Returns | Description |
CBOR.Wrapper | Retrieved or default object. |
2.9.1.4. containsKey()
Syntax | containsKey(key) |
Description | Check map for key presence. |
|
Parameter | Type | Description |
key | CBOR.Wrapper | Key (name) wrapper object. |
|
Returns | Description |
Boolean | true or false . |
2.9.1.5. remove()
Syntax | remove(key) |
Description | Remove map entry.
If key entry is undefined, an exception is thrown. |
|
Parameter | Type | Description |
key | CBOR.Wrapper | Key (name) wrapper object. |
|
Returns | Description |
CBOR.Wrapper | Removed object (value component). |
2.9.1.6. getKeys()
Syntax | getKeys() |
Description | Get map keys. |
|
Returns | Description |
[...] | JavaScript array holding a copy of current CBOR.Wrapper map keys. |
2.9.1.7. setSortingMode()
Syntax | setSortingMode(preSortedKeys) |
Description | Set the sorting mode of the
CBOR.Map() object during
set() operations.
Typical usage:
let map = CBOR.Map().setSortingMode(true)
This method may be called multiple times which could be
useful if you have a moderate set of unsorted meta data keys
combined with a sorted large table-like set of keys.
Note that this method has no effect on decoding operations. |
|
Parameter | Type | Description |
preSortedKeys | Boolean | If true ,
keys must be provided in (CBOR wise) ascending order
which can improve performance for maps having a huge number of keys.
Improper key order will cause an exception to be thrown.
By default map keys are sorted internally. |
|
Returns | Description |
this | Current object. |
2.9.2. CBOR.Map Properties
2.9.2.1. length
Name | Type | Description |
length | Number | Number of map entries. |
2.10. CBOR.Tag
Syntax | CBOR.Tag(tagNumber, object) |
Description | Constructor. Creates a CBOR tag wrapper object. |
|
Parameter | Type | Description |
tagNumber | BigInt | Tag number. |
object | CBOR.Wrapper | Object to be wrapped in a tag. |
|
Returns | Description |
CBOR.Tag | Wrapper object. |
2.10.1. CBOR.Tag Methods
2.10.1.1. getTagNumber()
Syntax | getTagNumber() |
Description | Get CBOR tag number. |
|
Returns | Description |
BigInt | Decoded tag number. |
2.10.1.2. getTaggedObject()
Syntax | getTaggedObject() |
Description | Get tagged CBOR object. |
|
Returns | Description |
CBOR.Wrapper | Retrieved object. |
3. Common Wrapper Methods
The CBOR wrapper objects
support a set of common methods, described in this sub section.
3.1. encode()
Syntax | encode() |
Description | Encode this object.
|
|
Returns | Description |
Uint8Array | CBOR encoded data. |
3.2. clone()
Syntax | clone() |
Description | Create a new instance of this object, initialized
with the original CBOR content. |
|
Returns | Description |
CBOR.Wrapper | Deep copy of this object. |
3.3. equals()
Syntax | equals(object) |
Description | Compare this object with another object with respect to CBOR data. |
|
Parameter | Type | Description |
object | CBOR.Wrapper | The object to compare with. |
|
Returns | Description |
Boolean | true if this object is equal to object ,
otherwise false . |
3.4. toDiag()
Syntax | toDiag(prettyPrint) |
Description | Render this object in Diagnostic Notation.
In similarity to encode(), this method always produce
data in Deterministic Encoding, irrespective to how
the data was created.
See also: toString(). |
|
Parameter | Type | Description |
prettyPrint | Boolean | If prettyPrint is true ,
additional white space is inserted between individual objects
in maps and arrays, to make the result easier to read. |
|
Returns | Description |
String | Textual version of the wrapped CBOR content. |
3.5. toString()
Syntax | toString() |
Description | Render this object in Diagnostic Notation.
Equivalent to calling toDiag()
with a true argument. |
|
Returns | Description |
String | Textual version of the wrapped CBOR content. |
3.6. isNull()
Syntax | isNull() |
Description | Check for CBOR null .
Note: if checkForUnread()
is used, this object will only be regarded as "read"
if it actually is a CBOR null item.
See also CBOR.Null(). |
|
Returns | Description |
Boolean | Returns true if this object
holds a CBOR null item, otherwise false
is returned. |
3.7. checkForUnread()
Syntax | checkForUnread() |
Description | Check if this object including possible child objects has been read
(like calling getInt()).
If any of the associated objects have not been read, an exception will be thrown.
The purpose of this method is to detect possible misunderstandings between parties
using CBOR based protocols. Together with the strict type checking performed
by the CBOR.js API, a programmatic counterpart to schema based processing
can be achieved.
Note that array get(),
map get(), and
tag getTaggedObject()
only locate objects,
and thus do not count as "read".
Note that empty array and map objects are excluded from
this check.
See also scan(). |
|
Returns | Description |
this | Current object. |
3.8. scan()
Syntax | scan() |
Description | Scan this object as well as possible child objects
in order to make them appear as "read".
This is only meaningful in conjunction with
checkForUnread(). |
|
Returns | Description |
this | Current object. |
4. Decoding CBOR
CBOR decoding comes in two flavors, binary and
Diagnostic Notation.
Both decoders return the result as CBOR wrapper objects.
This section lists the decoder methods.
4.1. CBOR.decode()
Syntax | CBOR.decode(cbor) |
Description | Decode a CBOR object.
This method is equivalent to
CBOR.initDecoder(cbor).decodeWithOptions() |
|
Parameter | Type | Description |
cbor | Uint8Array | CBOR binary data holding exactly one CBOR object. |
|
Returns | Description |
CBOR.Wrapper | CBOR wrapper object. |
4.2. CBOR.initDecoder()
Syntax | CBOR.initDecoder(cbor) |
Description | Create a CBOR decoder supporting options.
This decoding method presumes that the actual
decoding is performed by one or more (for sequences only) calls to
Decoder.decodeWithOptions().
|
|
Parameter | Type | Description |
cbor | Uint8Array | The CBOR data (bytes) to be decoded. |
|
Returns | Description |
Decoder | Decoder object for optional use by the
Decoder.set*()
methods and finally used by
Decoder.decodeWithOptions(). |
4.3. Decoder.setDeterministicMode()
Syntax | Decoder.setDeterministicMode(enforce) |
Description | Set CBOR decoder deterministic mode.
By default the decoder assumes that CBOR data conforms to the
Deterministic Encoding rules.
This method enables overriding the default.
|
|
Parameter | Type | Description |
enforce | Boolean | If the enforce flag is set to false ,
the decoder will accept CBOR data that does not adhere to the map sorting
and preferred number serialization requirements.
This option may be needed for dealing with "legacy" CBOR implementations.
Note: duplicate keys and other invalid (or not supported) CBOR constructs
will still cause an exception to be thrown.
|
|
Returns | Description |
this | Updated Decoder object. |
4.4. Decoder.setSequenceMode()
Syntax | Decoder.setSequenceMode(sequence) |
Description | Set CBOR decoder sequence mode.
By default the decoder assumes that CBOR data constitutes
of a single CBOR object.
This method enables overriding the default.
|
|
Parameter | Type | Description |
sequence | Boolean | If the sequence flag is set to true ,
the following apply:
- Immediately return after decoding a CBOR object, while preparing the
decoder for the next item.
See also Decoder.getByteCount().
- If no data is found (EOF),
null is returned
(empty sequences are permitted).
- Note that data succeeding a just decoded CBOR object
is not verified for correctness.
|
|
Returns | Description |
this | Updated Decoder object. |
4.5. Decoder.setNaNSupport()
Syntax | Decoder.setNaNSupport(accept) |
Description | Set CBOR decoder NaN/Infinity support.
By default the decoder supports
NaN , Infinity ,
and -Infinity .
In case these variants are not applicable for the application in question,
this method enables overriding the default.
|
|
Parameter | Type | Description |
accept | Boolean | If the accept flag is set to false ,
the mentioned exceptional floating point values will
cause an exception to be thrown.
|
|
Returns | Description |
this | Updated Decoder object. |
4.6. Decoder.decodeWithOptions()
Syntax | Decoder.decodeWithOptions() |
Description | Decode CBOR data with options. |
|
Returns | Description |
CBOR.Wrapper | CBOR wrapper object or null (for EOF sequences only). |
4.7. Decoder.getByteCount()
Syntax | Decoder.getByteCount() |
Description | Get decoder byte count.
This is equivalent to the position of the next item to be read. |
|
Returns | Description |
Number | The number of bytes read so far. |
4.8. CBOR.diagDecode()
Syntax | CBOR.diagDecode(cborText) |
Description | Decode a CBOR object provided in Diagnostic Notation.
See also CBOR.diagDecodeSequence().
|
|
Parameter | Type | Description |
cborText | String | CBOR in textual format. |
|
Returns | Description |
CBOR.Wrapper | CBOR wrapper object. |
4.9. CBOR.diagDecodeSequence()
Syntax | CBOR.diagDecodeSequence(cborText) |
Description | Decode a CBOR object provided in Diagnostic Notation.
Unlike CBOR.diagDecode(),
this method also accepts CBOR sequences, using a comma
character (',' ) as a separator. |
|
Parameter | Type | Description |
cborText | String | CBOR in textual format. |
|
Returns | Description |
[...] | Array holding one or more CBOR wrapper objects. |
5. Utility Methods
The following utility methods are unrelated to CBOR but have been included
here because they are a part of the current CBOR.js implementation.
5.1. CBOR.addArrays()
Syntax | CBOR.addArrays(a, b) |
Description | Add two arrays. |
|
Parameter | Type | Description |
a | Uint8Array | First array. |
b | Uint8Array | Second array. |
|
Returns | Description |
Uint8Array | Concatenation of array a and b . |
5.2. CBOR.compareArrays()
Syntax | CBOR.compareArrays(a, b) |
Description | Compare two arrays lexicographically. |
|
Parameter | Type | Description |
a | Uint8Array | First array. |
b | Uint8Array | Second array. |
|
Returns | Description |
Number | If a and b are identical,
0 is retuned.
If a > b ,
a positive number is returned.
If a < b ,
a negative number is returned. |
5.3. CBOR.toHex()
Syntax | CBOR.toHex(byteArray) |
Description | Encode binary data to hexadecimal. |
|
Parameter | Type | Description |
byteArray | Uint8Array | Zero or more bytes to be encoded. |
|
Returns | Description |
String | Hexadecimal encoded data. |
5.4. CBOR.fromHex()
Syntax | CBOR.fromHex(hexString) |
Description | Decode hexadecimal data into binary. |
|
Parameter | Type | Description |
hexString | String | String with zero or more hexadecimal pairs. Each pair represents one byte. |
|
Returns | Description |
Uint8Array | The resulting binary (bytes). |
5.5. CBOR.toBase64Url()
Syntax | CBOR.toBase64Url(byteArray) |
Description | Encode binary data to base64Url. |
|
Parameter | Type | Description |
byteArray | Uint8Array | Zero or more bytes to be encoded. |
|
Returns | Description |
String | Base64Url encoded data. |
5.6. CBOR.fromBase64Url()
Syntax | CBOR.fromBase64Url(base64) |
Description | Decode base64Url encoded data into binary.
Note that this method is permissive; it accepts
base64 encoded data as well as data with or without
'=' padding. |
|
Parameter | Type | Description |
base64 | String | String in base64Url notation. The string may be empty. |
|
Returns | Description |
Uint8Array | The resulting binary (bytes). |
6. JavaScript Number Considerations
Since JavaScript natively only supports Number
(backed
by 64-bit IEEE 754 floating point data), and BigInt
(offering unlimited integers), it is important to understand how these
number types are mapped to CBOR which offers
two variants of integers and three variants of floating point types.
6.1. Integer Numbers
Due to the Number.MAX_SAFE_INTEGER limitation, CBOR
protocols using integer objects where the magnitude may exceed
253-1, must
for such objects turn to BigInt
,
otherwise run-time errors may occur when accessing integer data using
getInt() or
during creation of integers using
CBOR.Int().
That is, for creation of such integers,
CBOR.BigInt()
is the proper solution, while access requires
getBigInt(),
which for convenience reasons is supported by both of the integer wrapper types.
Note that selecting CBOR.BigInt()
or CBOR.Int() only affects the maximum
numeric range with respect to JavaScript limits, not the CBOR encoding.
During CBOR decoding, the selection between
CBOR.BigInt()
and CBOR.Int() is governed by the decoded value
with respect to JavaScript limits.
The selection between the CBOR unsigned and negative
integer variants is dealt with by the CBOR.js implementation;
transparent to the API.
6.2. Floating Point Numbers
Although CBOR encoding depends on 16, 32, and 64-bit IEEE 754
variants, the CBOR.js implementation makes this
transparent. The CBOR.Float()
wrapper object only exposes the JavaScript Number
type.
See also the Decoder.setNaNSupport()
decoder method.
7. Diagnostic Notation
Creating CBOR data in diagnostic notation (as described in section 8 of RFC 8949),
is provided by the toString() method.
However, through the CBOR.diagDecode()
method, CBOR data may also be provided in diagnostic (textual) notation,
making CBOR useful for local "config" and test data files as well.
Due to the
Deterministic Encoding
scheme used by CBOR.js, CBOR data can be bidirectionally
converted between its native (binary) format and diagnostic notation
without getting corrupted. Note though that text-binary-text "roundtrips"
do not necessarily return identical text: 0x10
used
as diagnostic notation input will return 16
as
diagnostic notation output.
The following table shows how CBOR objects should be represented in
diagnostic notation:
CBOR Object | Syntax | Notes | Description |
|
/ comment text / |
7 |
Multi-line comment.
Multi-line comments are treated as whitespace and may thus also be used
between CBOR objects.
|
# comment text |
7 |
Single-line comment.
Single-line comments are terminated by a newline character ('\n' ) or EOF .
Single-line comments may also terminate lines holding regular CBOR items.
|
integer |
{sign}{0b |0o |0x }n |
1, 2 |
Arbitrary sized integers without fractional components or exponents.
See also CBOR integer encoding.
For input data in diagnostic notation, binary, octal, and hexadecimal notation
is also supported by prepending numbers with 0b , 0o , and 0x respectively.
The latter also permit arbitrary insertions of '_' characters between digits to
enable grouping of data like 0b100_000000001 .
|
bignum |
floating point |
{sign}n. n{e± n} |
1, 2 |
Floating point values
must include a decimal point and an optional exponent.
See also CBOR floating point encoding.
|
NaN |
|
Not a number.
See also CBOR floating point encoding.
|
{sign}Infinity |
2 |
Infinity.
See also CBOR floating point encoding.
|
byte string |
h' hex data' |
3, 6 |
Byte data provided in hexadecimal notation.
Each byte must be represented by two hexadecimal digits.
|
b64' base64 data' |
3, 6, 7 |
Byte data provided in base64 or base64URL notation.
Padding with '=' characters is optional.
|
' text' |
4, 5, 7 |
Byte data provided as UTF-8 encoded text. |
<< object >> |
7 |
Construct holding a CBOR object which is subsequently embedded in a byte string. |
text string |
" text"
| 4, 5 |
UTF-8 encoded text string. |
true |
true |
|
Boolean value. |
false | false |
null |
null |
|
Null value. |
array |
[ objects ] |
|
Array with zero or more comma separated CBOR objects. |
map |
{ key: value } |
|
Map with zero or more comma separated key/value pairs.
Keys and values are expressed as CBOR objects.
|
tag |
n( object ) |
1 |
Tag holding a CBOR object. |
|
, |
7 |
Separator character for CBOR sequences. |
- The letter n in the Syntax column denotes one or more digits.
- The optional {sign} must be a single hyphen (
'-'
) character.
-
Input only: the whitespace characters
(
' '
, '\t'
, '\r'
, '\n'
)
inside of string quotes are ignored.
-
Input only: the control characters
(
'\t'
and '\n'
)
inside of string quotes become a part of the text.
For nomalizing line terminators,
a single '\r'
or the combination '\r\n'
are rewritten as '\n'
.
To avoid getting newline characters ('\n'
)
included in multi-line text strings,
a line continuation marker consisting of a backslash ('\'
)
immediately preceding the newline may be used.
-
Text strings may also include JavaScript compatible escape sequences
(
'\''
, '\"'
, '\\'
,
'\b'
, '\f'
, '\n'
,
'\r'
, '\t'
, '\u
hhhh'
).
- Zero-length strings (
''
) return byte strings of length zero.
-
Input only:
the toString() method does not produce this item.
8. Deterministic Encoding
This section is primarily targeting implementers of CBOR tools.
While there are different ways you can encode certain CBOR objects,
this is non-trivial to support in a generic platform API without
adding complexity and that for little provable gain.
Therefore the CBOR.js API defines specific (non-variant)
encodings, aka "Deterministic Encoding". The chosen encoding
model is compatible with most existing CBOR decoders.
However, to not limit CBOR.js to new applications only,
deterministic encoding checking may optionally be turned off
for accepting input from "legacy" CBOR encoders.
The encoding scheme adheres to section 4.2 of RFC 8949, but adds
a few constraints (denoted by RFC+), where the RFC offers choices.
The encoding rules are as follows:
-
RFC+: Floating point and integer objects must be treated as distinct types
regardless of their numeric value. This is compliant with
Rule 2 in section 4.2.2 of RFC 8949.
-
RFC: Integers, represented by the integer and
bignum types, must use the integer
type if the value is between -264
and 264-1,
otherwise the bignum type must be used.
The following table holds a few sample values and their proper CBOR encoding:
Value | Encoding |
0 | 00 |
-1 | 20 |
255 | 18ff |
256 | 190100 |
-256 | 38ff |
-257 | 390100 |
1099511627775 | 1b000000ffffffffff |
18446744073709551615 | 1bffffffffffffffff |
18446744073709551616 | c249010000000000000000 |
-18446744073709551616 | 3bffffffffffffffff |
-18446744073709551617 | c349010000000000000000 |
Note that integers must not be supplied with
leading zero bytes (like 1900ff) unless the
CBOR representation offers no alternative (like 1b000000ffffffffff).
Note that the integer encoding scheme above does not always return the
most compact representation; the value
1099511627775
(0xffffffffff)
would actually yield two bytes less using the bignum type.
-
RFC+: Floating point data must use the shortest IEEE 754
variant and associated CBOR encoding.
The following table holds floating point values needing special considerations
as well as a small set of "edge cases":
Value | Encoding |
0.0 | f90000 |
-0.0 | f98000 |
Infinity | f97c00 |
-Infinity | f9fc00 |
NaN | f97e00 |
Assorted Edge Cases |
-5.960464477539062e-8 | fbbe6fffffffffffff |
-5.960464477539063e-8 | f98001 |
-5.960464477539064e-8 | fbbe70000000000001 |
-5.960465188081798e-8 | fab3800001 |
0.00006097555160522461 | f903ff |
65504.0 | f97bff |
65504.00390625 | fa477fe001 |
65536.0 | fa47800000 |
10.559998512268066 | fa4128f5c1 |
10.559998512268068 | fb40251eb820000001 |
3.4028234663852886e+38 | fa7f7fffff |
3.402823466385289e+38 | fb47efffffe0000001 |
1.401298464324817e-45 | fa00000001 |
1.4012986313726115e-45 | fb36a0000020000000 |
1.1754942106924411e-38 | fa007fffff |
5.0e-324 | fb0000000000000001 |
-1.7976931348623157e+308 | fbffefffffffffffff |
Note that NaN "signaling" (like f97e01),
must be flagged as an error.
Note that the shortest encoding may result in subnormal
numbers like f98001.
-
RFC: Map keys must be sorted in the bytewise lexicographic
order of their deterministic encoding.
Duplicate keys must be rejected.
-
RFC+: Since CBOR encoding according to this specification
maintains type and data uniqueness, there are no specific restrictions or
tests needed in order to determine map key equivalence.
As an example, the floating point numbers 0.0 and
-0.0, and the integer number 0
represent the distinct keys
f90000, f98000, and 00 respectively.
-
RFC+: Deterministic CBOR according to this specification
may also be provided in
Diagnostic Notation.
9. Using the CBOR API
This section provides a few examples on how to use the CBOR API.
9.1. Encode CBOR
The following code shows how you can create CBOR-encoded data:
let cbor = CBOR.Map()
.set(CBOR.Int(1), CBOR.Float(45.7))
.set(CBOR.Int(2), CBOR.String("Hi there!")).encode();
console.log(CBOR.toHex(cbor));
--------------------------------------------
a201fb4046d9999999999a0269486920746865726521
9.2. Decode CBOR
The following code shows how you can decode CBOR-encoded data,
here using the result of the encoding example:
let map = CBOR.decode(cbor);
console.log(map.toString()); // Diagnostic notation
----------------------------------------------------
{
1: 45.7,
2: "Hi there!"
}
console.log('Value=' + map.get(CBOR.Int(1)));
---------------------------------------------
Value=45.7
9.3. Using Diagnostic Notation
The following code shows how you can decode CBOR specified in
Diagnostic Notation:
let cbor = CBOR.diagDecode(`{
# Comments are also permitted
1: 45.7,
2: "Hi there!"
}`).encode();
console.log(CBOR.toHex(cbor));
------------------------------
a201fb4046d9999999999a0269486920746865726521
10. Version
API version: 1.0.9. Note that the current API version is accessible through
the static property CBOR.version
.
Document version: 2024-10-17
undefined
and typed arrays beyondUint8Array
.