Binary format

The wire format of binary mode, with every node type, its byte layout and the rules the decoder checks.

This page describes the bytes that binary.serialize writes and binary.deserialize reads. You only need it to write your own encoder or decoder, or to debug a payload.

Overview

Data types

The field tables below use these types:

TypeSizeDescription
byte1 byteAn 8-bit unsigned value.
int4 bytesA 32-bit signed integer.
uint4 bytesA 32-bit unsigned integer.
number8 bytesA number, as a 64-bit float.
id4 bytesA uint that declares a new value.
ref4 bytesA uint that holds an id declared earlier, and stands for that value.
bytesanyA run of bytes whose length is given by an earlier field.

int, uint and number use the byte order declared in the Preamble. The serializer uses the byte order of its platform.

Every node starts with a type byte, followed by the fields of that type. Offsets in the field tables count from the type byte, which is at offset 0. A ref field names the node types it accepts, such as ref to String. A ref with no type accepts any value.

Structure

A payload is a stream of nodes, not a single tree:

  • The serializer always sends the Preamble first.
  • Each node declares a value with an id, or acts on values declared earlier, such as ObjectAssign or PromiseSuccess.
  • A value's node is always sent before any node that refers to it, so a ref never points forward.
  • Ids are numbered in the order values are visited, so they do not always grow in the order nodes are sent. For example, an Error gets its id before its message, but its node comes after the message's String node.
  • A value that appears more than once is sent once, and later uses refer to its id. This includes strings and numbers.
  • A container is sent as a declaration node, such as Object, Array or Map, then the nodes for its contents, then one Pending node. Because a container's id exists before its contents are sent, its contents can refer back to it. This is how cycles work.
  • The Root node names the top-level value. It is sent once the synchronous part of the value is written.
  • Nodes for asynchronous values, such as PromiseSuccess, StreamNext and the values they carry, can follow the Root as those values settle.

Chunks

The serializer sends the nodes in chunks. The first chunk holds everything up to the Root. Each settled promise and each stream event is one more chunk. A decoder must not rely on chunk boundaries: a node can be split across chunks, and a chunk can hold many nodes.

A first payload

These are the bytes for { a: 1 } on a little-endian platform. They show the whole life of a container: declare it, send its contents, assign them, close it with Pending, then name it as the root.

Text
00 01
12 01 00 00 00
04 02 00 00 00 01 00 00 00 61
03 03 00 00 00 00 00 00 00 00 00 F0 3F
07 01 00 00 00 02 00 00 00 03 00 00 00
26 01 00 00 00 01 00 00 00
01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
12 01 00 00 00ObjectId 1 is {}.
04 02 00 00 00 01 00 00 00 61StringId 2 is the key "a", 1 UTF-8 byte.
03 03 00 00 00 00 00 00 00 00 00 F0 3FNumberId 3 is the value 1.
07 01 00 00 00 02 00 00 00 03 00 00 00ObjectAssignSets key id 2 of id 1 to id 3.
26 01 00 00 00 01 00 00 00PendingId 1 received 1 assignment.
01 01 00 00 00RootThe root is id 1.

The key and the value are sent as their own nodes before the ObjectAssign that refers to them, because a ref never points forward. The object is extensible, so no ObjectFlag node follows. More payloads are in Examples.

Node types

Type bytes are shown in decimal and in hexadecimal, as they appear in a dump. Size is the size of the whole node, type byte included.

A container is a value that receives assignments: Object, NullConstructor, Error, AggregateError, Array, Map, Set and Sequence.

Control

Nodes that frame the payload and close containers. They declare no value.

Preamble

Type 0 (00). 2 bytes. Always the first node.

OffsetFieldTypeDescription
0typebyte0
1endiannessbyte1 for little endian, 2 for big endian.

Tells the decoder the byte order of every int, uint and number field that follows.

Rules: any other byte order value is malformed.

Root

Type 1 (01). 5 bytes.

OffsetFieldTypeDescription
0typebyte1
1valuerefThe top-level value.

Names the top-level value. The decoder resolves its result with this value once every container in it is complete.

Rules: a payload has exactly one Root, sent after the node of the value it names.

Pending

Type 38 (26). 9 bytes.

OffsetFieldTypeDescription
0typebyte38
1targetref to a containerThe container to close.
5amountuintThe number of assignments the container received.

Closes a container. The decoder uses amount to know when the container is complete.

Sent: after the container's last assignment. Every container gets exactly one Pending node, even with no assignments.

Rules: amount must equal the assignments received. An assignment after the Pending node, or a second Pending node, is malformed.

ObjectFlag

Type 9 (09). 6 bytes.

OffsetFieldTypeDescription
0typebyte9
1targetref to Object, NullConstructor or ArrayThe value to change.
5flagbyteSee below.

Changes how target can be modified:

ByteEffect
0None.
1Object.preventExtensions
2Object.seal
3Object.freeze

Sent: only for a target that is not extensible, right after the target's Pending node.

Decoded: the flag is applied once the target is complete. Flag 0 is accepted and leaves the target unchanged.

Rules: a flag above 3 is malformed.

Primitives

Nodes that declare a complete value in one node. None of them receives assignments.

Constant

Type 2 (02). 6 bytes.

OffsetFieldTypeDescription
0typebyte2
1ididThe new value.
5constantbyteSee below.

A value that needs no data:

ByteValue
0null
1undefined
2true
3false
4-0
5Infinity
6-Infinity
7NaN

Number

Type 3 (03). 13 bytes.

OffsetFieldTypeDescription
0typebyte3
1ididThe new value.
5valuenumberThe number.

A finite number. -0, NaN, Infinity and -Infinity are sent as Constant nodes instead.

String

Type 4 (04). 9 bytes plus the string's bytes.

OffsetFieldTypeDescription
0typebyte4
1ididThe new value.
5lengthuintThe encoding bit and the byte count. See below.
9databytesThe string.

The top bit of length picks the encoding, and the other 31 bits are the number of bytes in data:

  • 0: UTF-8.
  • 1: UTF-16 code units, 2 bytes each, in the byte order of the Preamble. UTF-8 cannot hold a lone surrogate, so the serializer only uses this for a string that has one.

Rules: a UTF-16 string has an even number of bytes.

BigInt

Type 5 (05). 9 bytes plus the value's bytes.

OffsetFieldTypeDescription
0typebyte5
1ididThe new value.
5lengthuintThe sign bit and the byte count. See below.
9databytesThe absolute value, most significant byte first.

A bigint. The top bit of length is 1 for a negative value, and the other 31 bits are the number of bytes in data. The serializer sends 0n with no bytes and no leading zero bytes. The decoder also accepts leading zero bytes, and a negative zero, which decodes to 0n.

WKSymbol

Type 6 (06). 6 bytes.

OffsetFieldTypeDescription
0typebyte6
1ididThe new value.
5symbolbyteSee below.

A well-known symbol:

ByteSymbol
0Symbol.asyncIterator
1Symbol.hasInstance
2Symbol.isConcatSpreadable
3Symbol.iterator
4Symbol.match
5Symbol.matchAll
6Symbol.replace
7Symbol.search
8Symbol.species
9Symbol.split
10Symbol.toPrimitive
11Symbol.toStringTag
12Symbol.unscopables

Date

Type 20 (14). 13 bytes.

OffsetFieldTypeDescription
0typebyte20
1ididThe new value.
5timestampnumberMilliseconds since the Unix epoch, from getTime().

A Date. An invalid date has a NaN timestamp.

RegExp

Type 34 (22). 13 bytes.

OffsetFieldTypeDescription
0typebyte34
1ididThe new value.
5patternref to StringThe source.
9flagsref to StringThe flags.

A RegExp. It requires Feature.RegExp. See Compatibility.

Rules: the node is only accepted when Feature.RegExp is enabled. A pattern has at most 20,000 characters. In u or v mode, the engine builds each Unicode property escape (\p{...} or \P{...}) eagerly. So the RegExp nodes of a payload hold at most 32 of them.

Temporal

Type 39 (27). 10 bytes.

OffsetFieldTypeDescription
0typebyte39
1ididThe new value.
5temporal-typebyteSee below.
6isoref to StringThe value's toString().

A Temporal value, rebuilt with the from method of its type:

ByteType
0Temporal.Instant
1Temporal.Duration
2Temporal.PlainDate
3Temporal.PlainDateTime
4Temporal.PlainMonthDay
5Temporal.PlainTime
6Temporal.PlainYearMonth
7Temporal.ZonedDateTime

Rules: the node is only accepted when Feature.Temporal is enabled and the Temporal global exists on the receiving side.

Reference

Type 40 (28). 9 bytes.

OffsetFieldTypeDescription
0typebyte40
1ididThe new value.
5keyref to StringThe key the value was registered under.

A value registered with createReference. Only its key is sent.

Rules: the receiver must have a value registered under the same key, or the payload is rejected with SerovalMissingReferenceForIdError.

Objects

Objects and errors. Object, NullConstructor, Error and AggregateError are containers: ObjectAssign nodes set their properties, then a Pending node closes them.

Object

Type 18 (12). 5 bytes.

OffsetFieldTypeDescription
0typebyte18
1ididThe new value.

Declares a plain object, {}. If it is frozen, sealed or not extensible, an ObjectFlag node follows its Pending node.

A plain object with a Symbol.iterator or Symbol.asyncIterator method is sent as an Object, with an Iterator or AsyncIterator value for that key. Other iterable objects, such as generators and class instances, are sent the same way as a NullConstructor.

NullConstructor

Type 19 (13). 5 bytes.

OffsetFieldTypeDescription
0typebyte19
1ididThe new value.

Declares an object with no prototype, Object.create(null). It works like Object.

ObjectAssign

Type 7 (07). 13 bytes.

OffsetFieldTypeDescription
0typebyte7
1targetref to Object, NullConstructor, Error or AggregateErrorThe object to change.
5keyref to String or WKSymbolThe property key.
9valuerefThe property value.

Sets the property key of target to value.

Sent: after the nodes of key and value, before the target's Pending node. The serializer only sends four symbol keys: Symbol.iterator, Symbol.asyncIterator, Symbol.isConcatSpreadable and Symbol.toStringTag.

Decoded: see Property keys for how keys are applied.

Error

Type 21 (15). 10 bytes.

OffsetFieldTypeDescription
0typebyte21
1ididThe new value.
5constructorbyteSee below.
6messageref to StringThe message.

An error with the given constructor and message:

ByteConstructor
0Error
1EvalError
2RangeError
3ReferenceError
4SyntaxError
5TypeError
6URIError

Other properties follow as ObjectAssign nodes, then a Pending node. These include stack when Feature.ErrorPrototypeStack is on, name when it differs from the constructor's name, and every other own property.

AggregateError

Type 35 (23). 9 bytes.

OffsetFieldTypeDescription
0typebyte35
1ididThe new value.
5messageref to StringThe message.

An AggregateError. Its errors array and any other properties follow as ObjectAssign nodes, then a Pending node, as for Error.

It requires Feature.AggregateError. Without it, the serializer sends an AggregateError as an Error node.

Boxed

Type 22 (16). 9 bytes.

OffsetFieldTypeDescription
0typebyte22
1ididThe new value.
5valuerefThe primitive.

A boxed primitive, such as Object(1) or Object('text'), built with Object(value).

Collections

Arrays, maps and sets. Each is declared empty, filled by its own assignment node, then closed by a Pending node.

Array

Type 10 (0A). 9 bytes.

OffsetFieldTypeDescription
0typebyte10
1ididThe new value.
5lengthuintThe array's length.

Declares an array of length elements. ArrayAssign nodes set its elements. A hole in a sparse array is never assigned, so length can be larger than the number of ArrayAssign nodes.

Rules: length is at most maxArrayLength, 1,000,000 by default. The holes of all the arrays in a payload together number at most maxArrayLength.

ArrayAssign

Type 8 (08). 13 bytes.

OffsetFieldTypeDescription
0typebyte8
1targetref to ArrayThe array to change.
5indexuintThe element index.
9valuerefThe element.

Sets the element at index of target to value.

Sent: after the Array node and the node of value, before the array's Pending node.

Rules: index is below the array's length.

Map

Type 27 (1B). 5 bytes.

OffsetFieldTypeDescription
0typebyte27
1ididThe new value.

Declares an empty Map. MapSet nodes add its entries in insertion order.

MapSet

Type 28 (1C). 13 bytes.

OffsetFieldTypeDescription
0typebyte28
1targetref to MapThe map to change.
5keyrefThe entry key.
9valuerefThe entry value.

Sets key to value in target.

Sent: after the Map node and the nodes of key and value, before the map's Pending node.

Set

Type 29 (1D). 5 bytes.

OffsetFieldTypeDescription
0typebyte29
1ididThe new value.

Declares an empty Set. SetAdd nodes add its values in insertion order.

SetAdd

Type 30 (1E). 9 bytes.

OffsetFieldTypeDescription
0typebyte30
1targetref to SetThe set to change.
5valuerefThe value to add.

Adds value to target.

Sent: after the Set node and the node of value, before the set's Pending node.

Iteration

Nodes for Symbol.iterator and Symbol.asyncIterator methods. A sync iterable is sent as the values it yielded, in a Sequence. An async iterable is sent as a Stream.

Sequence

Type 15 (0F). 13 bytes.

OffsetFieldTypeDescription
0typebyte15
1ididThe new value.
5throws-atintThe index of the value the iterator threw, or -1.
9done-atintThe index of the value the iterator returned with, or -1.

Declares the values an iterable yielded when it was serialized. SequencePush nodes add the values, then a Pending node gives their count. At most one of throws-at and done-at is not -1.

Rules: both indices are between -1 and the count minus 1, and the count equals the number of SequencePush nodes. The decoder rejects a sequence that breaks either rule, because its iterator would never finish.

SequencePush

Type 16 (10). 9 bytes.

OffsetFieldTypeDescription
0typebyte16
1targetref to SequenceThe sequence to change.
5valuerefThe next value.

Adds value to target.

Sent: after the Sequence node and the node of value, before the sequence's Pending node.

Iterator

Type 36 (24). 9 bytes.

OffsetFieldTypeDescription
0typebyte36
1ididThe new value.
5sequenceref to SequenceThe values to yield.

A Symbol.iterator method that yields the values of sequence.

Rules: the Sequence already has its Pending node.

AsyncIterator

Type 37 (25). 9 bytes.

OffsetFieldTypeDescription
0typebyte37
1ididThe new value.
5streamref to StreamThe values to yield.

A Symbol.asyncIterator method that yields the values of stream.

Async

Promises and streams. They are declared before the Root, and the nodes that settle them often come after it, one chunk per event.

Promise

Type 31 (1F). 5 bytes.

OffsetFieldTypeDescription
0typebyte31
1ididThe new value.

Declares a pending promise. One PromiseSuccess or PromiseFailure node settles it later.

PromiseSuccess

Type 32 (20). 9 bytes.

OffsetFieldTypeDescription
0typebyte32
1targetref to PromiseThe promise to settle.
5valuerefThe fulfillment value.

Resolves target with value. The decoder waits until every container in value is complete before it resolves the promise.

Rules: a promise gets at most one PromiseSuccess or PromiseFailure. value is not a Promise or any other value with a then method.

PromiseFailure

Type 33 (21). 9 bytes.

OffsetFieldTypeDescription
0typebyte33
1targetref to PromiseThe promise to settle.
5valuerefThe rejection reason.

Rejects target with value.

Rules: a promise gets at most one PromiseSuccess or PromiseFailure.

Stream

Type 11 (0B). 6 bytes.

OffsetFieldTypeDescription
0typebyte11
1ididThe new value.
5livebyte1 for a live stream, 0 otherwise.

Declares a stream that receives values over time, through StreamNext, StreamThrow and StreamReturn nodes.

live is 1 for a live stream and 0 for a stream from createStream or an async iterable. A live stream is decoded as a stream that keeps its values only until the first listener subscribes. After that, it passes values on without storing them, and a second listener throws.

Rules: live is 0 or 1.

StreamNext

Type 12 (0C). 9 bytes.

OffsetFieldTypeDescription
0typebyte12
1targetref to StreamThe stream.
5valuerefThe next value.

Sends value as the next value of target. A stream can receive any number of these.

StreamThrow

Type 13 (0D). 9 bytes.

OffsetFieldTypeDescription
0typebyte13
1targetref to StreamThe stream.
5valuerefThe error.

Ends target with the error value.

Rules: no more nodes for that stream follow.

StreamReturn

Type 14 (0E). 9 bytes.

OffsetFieldTypeDescription
0typebyte14
1targetref to StreamThe stream.
5valuerefThe final value.

Ends target with the final value value.

Rules: no more nodes for that stream follow.

Binary data

An ArrayBuffer carries the bytes. Views refer to it by its id instead of repeating them, so views over the same buffer still share it after decoding.

ArrayBuffer

Type 23 (17). 9 bytes plus the buffer's bytes.

OffsetFieldTypeDescription
0typebyte23
1ididThe new value.
5lengthuintThe byte count.
9databytesThe buffer's contents.

Rules: length is at most maxArrayBufferLength, 1,000,000 by default.

TypedArray

Type 24 (18). 18 bytes.

OffsetFieldTypeDescription
0typebyte24
1ididThe new value.
5constructorbyteSee below.
6bufferref to ArrayBufferThe backing buffer.
10offsetuintThe start, in bytes.
14lengthuintThe length, in elements.

A typed array over buffer:

ByteConstructor
1Int8Array
2Int16Array
3Int32Array
4Uint8Array
5Uint16Array
6Uint32Array
7Uint8ClampedArray
8Float32Array
9Float64Array

Sent: with the whole backing buffer, or with compactArrayBufferViews, a copy of the view's bytes at offset 0. The serializer rejects a typed array longer than 1,000,000 elements.

Rules: the view fits inside buffer, and has at most 1,000,000 elements.

BigIntTypedArray

Type 25 (19). 18 bytes.

OffsetFieldTypeDescription
0typebyte25
1ididThe new value.
5constructorbyteSee below.
6bufferref to ArrayBufferThe backing buffer.
10offsetuintThe start, in bytes.
14lengthuintThe length, in elements.

The bigint version of TypedArray:

ByteConstructor
1BigInt64Array
2BigUint64Array

It requires Feature.BigIntTypedArray. Without it, the serializer does not use this node, and sends the array as an iterable object with no prototype, as the other modes do.

Rules: as for TypedArray.

DataView

Type 26 (1A). 17 bytes.

OffsetFieldTypeDescription
0typebyte26
1ididThe new value.
5bufferref to ArrayBufferThe backing buffer.
9offsetuintThe start, in bytes.
13lengthuintThe length, in bytes.

A DataView over buffer. The serializer rejects a DataView longer than 1,000,000 bytes.

Rules: the view fits inside buffer, and has at most 1,000,000 bytes.

Extension

Plugin

Type 17 (11). 13 bytes.

OffsetFieldTypeDescription
0typebyte17
1ididThe new value.
5tagref to StringThe plugin's tag.
9datarefWhat the plugin's binary.serialize returned.

A value built by a plugin. data can be any value, not only an object.

Sent: after the nodes of tag and data.

Decoded: the decoder waits until every container in data is complete, then passes it to the binary.deserialize of the plugin with the same tag. The value is available once that function returns, or once the promise it returns resolves.

Validation

The decoder treats its input as untrusted. Each node's own limits are listed under Rules in its entry. On top of those, the decoder rejects a payload that breaks any of these rules:

  • The type byte of each node is a known node type.
  • An id is declared once.
  • A ref points to an id that was already declared, with a node type that the referencing node accepts.
  • Every enumerated byte has a known value. This covers the byte order, constants, symbols, error constructors, typed array constructors, Temporal types and ObjectFlag flags. The Stream live byte is 0 or 1.
  • A container gets no assignments after its Pending node, only one Pending node, and exactly as many assignments as its Pending amount.
  • When the input ends:
    • no node is cut off,
    • the Root has been read,
    • every container has its Pending node and all its assignments,
    • every Promise and Stream has settled.

When a payload is rejected:

  • The error goes to onError.
  • The returned promise is rejected, if it has not resolved yet.
  • Unsettled promises are rejected, and open streams are thrown into.

Some errors are reported through onError without rejecting the payload. An assignment that cannot be applied is skipped, and decoding continues. For example, its value refers to an id with no value, or comes from a plugin that failed.

Property keys

The decoder also guards the keys of ObjectAssign nodes:

  • A key is a String or a WKSymbol.
  • A symbol key is only applied for Symbol.iterator, Symbol.asyncIterator, Symbol.isConcatSpreadable and Symbol.toStringTag. Other symbol keys are ignored.
  • The keys __proto__, constructor, prototype, __defineGetter__, __defineSetter__, __lookupGetter__ and __lookupSetter__ are defined as own properties instead of assigned.

Examples

Each example shows the bytes in hexadecimal for a little-endian payload, so the Preamble is 00 01. A uint takes 4 bytes and a number 8 bytes. The first payload, { a: 1 }, is in the Overview.

null

Text
00 01   02 01 00 00 00 00   01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
02 01 00 00 00 00ConstantId 1 is null.
01 01 00 00 00RootThe root is id 1.

42

Text
00 01   03 01 00 00 00 00 00 00 00 00 00 45 40   01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
03 01 00 00 00 00 00 00 00 00 00 45 40NumberId 1 is 42, as a little-endian float.
01 01 00 00 00RootThe root is id 1.

"hi"

Text
00 01   04 01 00 00 00 02 00 00 00 68 69   01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
04 01 00 00 00 02 00 00 00 68 69StringId 1 is the 2 UTF-8 bytes of "hi".
01 01 00 00 00RootThe root is id 1.

A repeated value

['x', 'x']: the second element refers to the same String node as the first.

Text
00 01
0A 01 00 00 00 02 00 00 00
04 02 00 00 00 01 00 00 00 78
08 01 00 00 00 00 00 00 00 02 00 00 00
08 01 00 00 00 01 00 00 00 02 00 00 00
26 01 00 00 00 02 00 00 00
01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
0A 01 00 00 00 02 00 00 00ArrayId 1 is an array of length 2.
04 02 00 00 00 01 00 00 00 78StringId 2 is "x".
08 01 00 00 00 00 00 00 00 02 00 00 00ArrayAssignElement 0 of id 1 is id 2.
08 01 00 00 00 01 00 00 00 02 00 00 00ArrayAssignElement 1 of id 1 is id 2 again.
26 01 00 00 00 02 00 00 00PendingId 1 received 2 assignments.
01 01 00 00 00RootThe root is id 1.

A cycle

a where a.self = a: the object's id exists before its Pending node, so its own assignment can refer to it.

Text
00 01
12 01 00 00 00
04 02 00 00 00 04 00 00 00 73 65 6C 66
07 01 00 00 00 02 00 00 00 01 00 00 00
26 01 00 00 00 01 00 00 00
01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
12 01 00 00 00ObjectId 1 is {}.
04 02 00 00 00 04 00 00 00 73 65 6C 66StringId 2 is the key "self".
07 01 00 00 00 02 00 00 00 01 00 00 00ObjectAssignSets key id 2 of id 1 to id 1.
26 01 00 00 00 01 00 00 00PendingId 1 received 1 assignment.
01 01 00 00 00RootThe root is id 1.

A frozen object

Object.freeze({}): the ObjectFlag node follows the Pending node.

Text
00 01   12 01 00 00 00   26 01 00 00 00 00 00 00 00   09 01 00 00 00 03   01 01 00 00 00
BytesNodeMeaning
00 01PreambleLittle endian.
12 01 00 00 00ObjectId 1 is {}.
26 01 00 00 00 00 00 00 00PendingId 1 received no assignments.
09 01 00 00 00 03ObjectFlagFreeze id 1.
01 01 00 00 00RootThe root is id 1.

A promise

A promise that resolves with 1 after serialization starts. The payload arrives in two chunks: the first ends with the Root, the second settles the promise.

Text
00 01   1F 01 00 00 00   01 01 00 00 00
Text
03 02 00 00 00 00 00 00 00 00 00 F0 3F   20 01 00 00 00 02 00 00 00
ChunkBytesNodeMeaning
100 01PreambleLittle endian.
11F 01 00 00 00PromiseId 1 is a pending promise.
101 01 00 00 00RootThe root is id 1.
203 02 00 00 00 00 00 00 00 00 00 F0 3FNumberId 2 is 1.
220 01 00 00 00 02 00 00 00PromiseSuccessResolves id 1 with id 2.