BON8

BON8 (Binary Object Notation 8) is a compact binary serialization format for JSON values. It uses the byte values that cannot begin a UTF-8 character as type markers, so strings are stored as plain UTF-8 without a length prefix: a string ends at the first byte that cannot continue it. Integers from -10 to 39, true, false, null, and the floating-point values -1.0, 0.0, and 1.0 take a single byte, and arrays and objects with up to four elements need no terminator.

!!! abstract “References”

- [BON8 specification](https://github.com/hikoworks/hikogui/blob/main/docs/BON8.md)
- [Reference implementation](https://github.com/hikoworks/hikogui/blob/main/src/hikogui/codec/BON8.hpp) in HikoGUI

Serialization

The library uses the following mapping from JSON values types to BON8 types according to the BON8 specification:

JSON value typevalue/rangeBON8 typefirst byte
nullnullnull0xFA
booleantruetrue0xF9
booleanfalsefalse0xF8
number_integer-9223372036854775808..-2147483649int640x8D
number_integer-2147483648..-33818507int320x8C
number_integer-33818506..-2640754-byte negative integer0xF0..0xF7
number_integer-264074..-19313-byte negative integer0xE0..0xEF
number_integer-1930..-112-byte negative integer0xC2..0xDF
number_integer-10..-11-byte negative integer0xB8..0xC1
number_integer0..391-byte positive integer0x90..0xB7
number_integer40..38792-byte positive integer0xC2..0xDF
number_integer3880..5281673-byte positive integer0xE0..0xEF
number_integer528168..676370314-byte positive integer0xF0..0xF7
number_integer67637032..2147483647int320x8C
number_integer2147483648..9223372036854775807int640x8D
number_unsigned0..391-byte positive integer0x90..0xB7
number_unsigned40..38792-byte positive integer0xC2..0xDF
number_unsigned3880..5281673-byte positive integer0xE0..0xEF
number_unsigned528168..676370314-byte positive integer0xF0..0xF7
number_unsigned67637032..2147483647int320x8C
number_unsigned2147483648..9223372036854775807int640x8D
number_float-1.0-1.00xFB
number_float0.00.00xFC
number_float1.01.00xFD
number_floatany other value representable by a floatbinary320x8E
number_floatany value NOT representable by a floatbinary640x8F
stringemptyend of string0xFF
stringnon-emptyUTF-8 string0x00..0x7F, 0xC2..0xF4
arraysize: 0..4array with count0x80..0x84
arraysize: 5 or morearray (terminated by 0xFE)0x85
objectsize: 0..4object with count0x86..0x8A
objectsize: 5 or moreobject (terminated by 0xFE)0x8B
binarysize: 0..4array with count0x80..0x84
binarysize: 5 or morearray (terminated by 0xFE)0x85

An integer that takes 2 to 4 bytes starts with a UTF-8 lead byte (0xC2..0xF7) that is followed by a byte that cannot continue a UTF-8 character: 0x00..0x7F for positive and 0xC0..0xFF for negative integers. A string is terminated by 0xFF only if it is empty, if another string follows it, or if nothing follows it in the message; otherwise, the byte after it ends it: the first byte of the next value, or the 0xFE that ends an array or object. For example, ["e"] is serialized as 0x81 0x65 0xFF, but [1,2,3,4,"e"] as 0x85 0x91 0x92 0x93 0x94 0x65 0xFE.

!!! success “Complete mapping”

Except for the values listed below, any JSON value can be converted to a BON8 value.

Any BON8 output created by `to_bon8` can be successfully parsed by `from_bon8`.

!!! warning “Unsupported values”

The following values can **not** be converted to a BON8 value:

  - unsigned integers above 9223372036854775807, because BON8 has no unsigned 64-bit integer type
    ([out_of_range.407](../../home/exceptions.md#jsonexceptionout_of_range407))
  - strings that are not valid UTF-8, because the end of a string is determined from its encoding
    ([type_error.316](../../home/exceptions.md#jsonexceptiontype_error316))

!!! info “NaN/infinity handling”

`-0.0`, `Infinity`, and `-Infinity` are serialized as binary32 (type 0x8E, 5 bytes total). `NaN` is serialized as
the binary32 value 0x7F800001 that the specification recommends. This is in contrast to the
[dump](../../api/basic_json/dump.md) function which serializes NaN or Infinity to `null`.

!!! warning “Binary values”

BON8 has no binary type. Binary values are serialized as arrays of integers (0..255), so they are read back as
arrays. The subtype is not serialized.

!!! info “Canonical representation”

The output follows the specification's canonical representation rules: every value uses the shortest encoding,
floating-point numbers use binary32 whenever that loses no precision, and object keys are sorted by their UTF-8
code units. There are two exceptions:

- Strings are not normalized to Unicode Normalization Form C (NFC).
- Object keys are written in the order of the object type, which is sorted for `json`, but not for
  [`ordered_json`](../../api/ordered_json.md).

??? example “Example: serialize a JSON value to BON8”

```cpp
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>

using json = nlohmann::json;
using namespace nlohmann::literals;

int main()
{
    // create a JSON value
    json j = R"({"compact": true, "format": "BON8", "schema": 0})"_json;

    // serialize it to BON8
    std::vector<std::uint8_t> v = json::to_bon8(j);

    // print the vector content
    for (auto& byte : v)
    {
        std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
    }
    std::cout << std::endl;
}

```

Output:

```c
0x89 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xf9 0x66 0x6f 0x72 0x6d 0x61 0x74 0xff 0x42 0x4f 0x4e 0x38 0xff 0x73 0x63 0x68 0x65 0x6d 0x61 0x90 

```

Byte layout

Consider the following JSON value (shown formatted for readability):

{
  "id": 300,
  "name": "json",
  "pi": 3.14,
  "tags": [
    "a",
    "b"
  ]
}

to_bon8 encodes it to 35 bytes (shown in hexadecimal; the encoding contains no whitespace). The colors mark the role of each byte: type/marker length/count/size data.

Deserialization

The library maps BON8 types to JSON value types as follows:

BON8 typeJSON value typefirst byte
UTF-8 stringstring0x00..0x7F
array with countarray0x80..0x84
array (terminated by 0xFE)array0x85
object with countobject0x86..0x8A
object (terminated by 0xFE)object0x8B
int32number_unsigned or number_integer0x8C
int64number_unsigned or number_integer0x8D
binary32number_float0x8E
binary64number_float0x8F
1-byte positive integernumber_unsigned0x90..0xB7
1-byte negative integernumber_integer0xB8..0xC1
UTF-8 stringstring0xC2..0xF4, followed by 0x80..0xBF
2- to 4-byte positive integernumber_unsigned0xC2..0xF7, followed by 0x00..0x7F
2- to 4-byte negative integernumber_integer0xC2..0xF7, followed by 0xC0..0xFF
falsefalse0xF8
truetrue0xF9
nullnull0xFA
-1.0number_float0xFB
0.0number_float0xFC
1.0number_float0xFD
empty stringstring0xFF

Non-negative integers are read as number_unsigned, negative integers as number_integer.

!!! info

Values that do not use the canonical representation, such as integers with a longer encoding than necessary,
arrays and objects with up to four elements that are terminated by 0xFE, unsorted object keys, or a 0xFF after a
string that would also end without it, are accepted. A second 0xFF is not a terminator but an empty string.

Strings must be valid UTF-8, and a string at the very end of a message must be terminated by 0xFF.

!!! info

Any BON8 output created by `to_bon8` can be successfully parsed by `from_bon8`.

??? example “Example: deserialize a JSON value from BON8”

```cpp
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create byte vector
    std::vector<std::uint8_t> v = {0x89, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74,
                                   0xf9, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0xff,
                                   0x42, 0x4f, 0x4e, 0x38, 0xff, 0x73, 0x63, 0x68,
                                   0x65, 0x6d, 0x61, 0x90
                                  };

    // deserialize it with BON8
    json j = json::from_bon8(v);

    // print the deserialized JSON value
    std::cout << std::setw(2) << j << std::endl;
}

```

Output:

```json
{
  "compact": true,
  "format": "BON8",
  "schema": 0
}

```