pure-cbor · CBOR for JavaScript and TypeScript
From a value to bytes and back, through every line that matters
pure-cbor implements CBOR (RFC 8949) in about 2,800 lines of strict TypeScript, with no runtime dependencies. This page is one walk through it. Try the codec first; it is the real library, running in your browser. Then follow a value through the code: the principles it is built on, the encode path, the decode path, streaming, and how we know it is fast and correct.
- npm:
pure-cbor - Plain ESM with TypeScript declarations
- No Node APIs, no generated code (CSP-safe)
- MIT licence
Two promises
Clean, functional code
Pure functions over explicit state, in the spirit of OCaml. There are no classes apart from the error type, and no state kept between calls apart from two documented caches: decoded map keys, and one write function per encode-option set (which holds no data). Tagged values and simple values are immutable variants, and the wire format is described by one named set of constants.
The fastest pure-JavaScript CBOR library
Pure JavaScript, with no native addon. On public benchmark data it decodes 1.21–1.72× faster than cbor-x, the next fastest library measured, and encodes from level with it to 1.55× faster. Small messages decoded from a fresh buffer are 5–13× faster. On Node, cbor-x's optional native addon makes it decode text-heavy data up to 1.26× faster.
It covers the whole RFC 8949 data model (tags, bignums, dates, Map, simple values, typed arrays), deterministic encoding, CBOR sequences over Web Streams, and COSE, CWT, WebAuthn and mdoc messages, which are checked against their published test vectors. It is standard CBOR only: there is no private wire format.
Try it
The codec, live
Type a JavaScript value, or pick an example, and see the exact bytes pure-cbor writes, what each byte means, and the value decode gives back. Switch to Decode hex to read any CBOR, including malformed input. This runs the library built from src/ on main.
A JavaScript literal: objects, arrays, strings, numbers, 12n, true/false/null/undefined, new Map([[k, v]]), new Date('…'), new Uint8Array([…]) and the other typed arrays, tagged(tag, value) and simple(n). It is parsed, never evaluated.
Spaces, line breaks and a 0x prefix are ignored. Decoding uses the defaults: duplicate keys, invalid UTF-8 and trailing bytes are errors.
Bytes hover or focus a byte to see the item it belongs to
What each item means
Decoded back
Part 1
Core principles
pure-cbor makes two promises that usually pull against each other: functional code you can read, and the fastest CBOR in pure JavaScript. These six principles are how the code keeps both. Each one is shown with the code that carries it out.
1. Explicit state over hidden state
A decoder needs a cursor, a nesting depth and some limits. Rather than keeping them in a class instance or module variables, pure-cbor puts them in one plain record. The record is created for a single decode call and passed down by argument, so every function that touches it says so in its signature.
/** Explicit state for decoding one container tree. Created per decode call
* (only when the value is an array or map) and passed down; nothing is
* shared between calls. */
/** The current text window (see string.ts): part of the input, masked to
* ASCII and decoded with one TextDecoder call, that medium-length ASCII
* strings are sliced from. Empty until the first such string. */
export interface TextWindow {
windowStart: number;
windowText: string;
}
export interface DecodeState extends TextWindow {
readonly bytes: Uint8Array;
/** Cursor: the next unread byte. */
position: number;
depth: number;
/** Items the remaining containers may still declare. Every item takes at
* least one input byte, so a valid message never exceeds its own length;
* this stops nested headers from preallocating O(bytes × depth). */
itemBudget: number;
readonly options: DecodeOptions | undefined;
/** Created at most once per decode, on the first float64 array element of
* an input over 64 bytes (already off-heap, so a DataView is cheap there). */
floatView: DataView | undefined;
/** Byte strings copied during this decode (see arena.ts). */
arena: Uint8Array | undefined;
arenaUsed: number;
// …
readonly rejectDuplicateKeys: boolean;
/** mapKeys: 'integer-or-text': Map keys must be integers or text. */
readonly integerOrTextKeys: boolean;
readonly mapMode: 'auto' | 'object' | 'map';
}Encoding works the same way. The output is a Writer record holding bytes and a cursor. Functions that write take the writer and return nothing, or take a position and return the next one. Nothing else changes.
/** Output for one encode call: bytes plus a cursor. A growable writer (owned
* encoding into staging memory) reallocates on demand; a fixed writer
* (caller-owned memory) never grows, and its capacity is checked up front.
* Encode options are not stored here: they select which write function runs
* (see writerFor in codec.ts), so the default path never checks them. */
export interface Writer {
bytes: Uint8Array;
position: number;
readonly growable: boolean;
}The README lists every resource shared between calls: constants and a tag lookup, the standard UTF-8 encoders and decoders, two scratch areas used only within one synchronous call (a one-element float array and the owned-output staging buffer), and one cache that does outlive a call. That cache is documented where it lives:
/** Decoded map keys, reused across messages. A repeated key skips UTF-8
* decoding and, more importantly, V8 internalizing a brand-new string each
* time it becomes a property name: object construction measured ~2.3x faster
* with cached keys. Hits are confirmed byte for byte, so a hash collision only
* costs a miss. Only keys that decoded as valid UTF-8 are stored, so a hit is
* correct in every decode mode. Holds key text only, never values. */
const SLOT_COUNT = 1024;
const MAX_KEY_BYTES = 32;
const slotBytes: (Uint8Array | undefined)[] = Array.from({ length: SLOT_COUNT }, () => undefined);
const slotKeys: string[] = Array.from({ length: SLOT_COUNT }, () => '');Variants, not classes
CBOR tags and simple values become immutable values made by tagged() and simple(). They are recognised by a private, frozen prototype rather than by their shape, so a plain object that happens to have tag and value fields is still just an object. The only class in the library is CborError, used on the cold error path.
const TaggedPrototype: object = Object.freeze(Object.create(Object.prototype, {
[Symbol.toStringTag]: { value: 'Tagged' },
}));
/** An immutable tagged value. Tag numbers are safe integers. */
export function tagged(tag: number, value: Value): Tagged {
if (!Number.isSafeInteger(tag) || tag < 0) throw new RangeError('Tag numbers are non-negative safe integers');
const result = Object.create(TaggedPrototype) as { tag: number; value: Value };
result.tag = tag;
result.value = value;
return Object.freeze(result);
}
export function isTagged(value: unknown): value is Tagged {
return typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === TaggedPrototype;
}2. Options choose functions; loops never check them
Encode options (floats: 'shortest' and deterministic: true) are not stored on the writer and tested per value. They are turned into a frozen EncodeProfile once, and the profile selects which write function runs. The default write function has no option checks in it at all.
Scroll sideways to see the whole diagram.
DEFAULT_PROFILE picks the default writer without a lookup./** How values are written: fixed per encode call. */
export interface EncodeProfile {
readonly shortestFloats: boolean;
readonly sortKeys: boolean;
}
export const DEFAULT_PROFILE: EncodeProfile = Object.freeze({ shortestFloats: false, sortKeys: false });
const SHORTEST_FLOATS: EncodeProfile = Object.freeze({ shortestFloats: true, sortKeys: false });
const DETERMINISTIC: EncodeProfile = Object.freeze({ shortestFloats: true, sortKeys: true });
export function profileOf(options: EncodeOptions | undefined): EncodeProfile {
if (options === undefined) return DEFAULT_PROFILE;
if (options.deterministic) return DETERMINISTIC;
return options.floats === 'shortest' ? SHORTEST_FLOATS : DEFAULT_PROFILE;
}/** A write function for non-default options (shortest floats, sorted keys).
* These modes are opt-in and slower anyway (sorting), so this is a plain
* recursive dispatcher; keeping it separate means the default writeValue
* never checks options. (Reading them per object cost ~10% on small objects.) */
function optionsWriter(profile: EncodeProfile): WriteValue {
const { shortestFloats, sortKeys } = profile;
// …
return writeWithOptions;
}
const writers = new Map<EncodeProfile, WriteValue>();
/** The write function for an encode profile. The default needs no lookup:
* this runs on every encode call. */
export function writerFor(profile: EncodeProfile): WriteValue {
if (profile === DEFAULT_PROFILE) return writeValue;
let writer = writers.get(profile);
if (writer === undefined) {
writer = optionsWriter(profile);
writers.set(profile, writer);
}
return writer;
}The same idea runs down to single functions. The number writer has a separate writeShortest, rather than a flag on write, so that the default stays small enough to inline into the array and object loops:
/** Like write, but floats in their shortest exact form (RFC 8949 §4.1). A
* separate function, so the default write stays small enough for V8 to inline
* into the array and object loops (an unused option branch cost ~5%). */
export function writeShortest(bytes: Uint8Array, offset: number, value: number): number {
if (majorTypeOf(value) !== FLOAT) return write(bytes, offset, value);
writable(bytes, offset, shortestFloatSize(value));
return writeShortestFloat(bytes, offset, value);
}And the public encode sends any options down a separate path on its first line, so the default path below it is unchanged by them:
/** Exact-sized, independently owned output. Small outputs never touch a
* `.buffer`, so they stay cheap V8 on-heap allocations. */
export function encode(value: Value, options?: EncodeOptions): Uint8Array {
// Options take a separate path; the default below is unchanged by them.
if (options !== undefined) return encodeWithOptions(value, profileOf(options));
// …
return staged(value, DEFAULT_PROFILE, copyOut);
}3. Allocation is a policy the caller picks
The README says to choose the API by the lifetime of your data, not merely its speed. There are three encode policies, and no codec module depends on which one is in use.
| Policy | API | What you get |
|---|---|---|
| Owned output (default) | encode(value) | Exactly sized, with no shared backing buffer. The bytes can be kept or transferred to another worker. |
| Caller-owned buffer | write(binary, offset, value), encodeInto(value, bytes, offset) | Writes into your memory and returns the next offset. A capacity error never partially writes the destination. |
| Slab-backed (opt-in) | createSlabEncoder(options) | Appends values into one shared slab. Earlier views are never overwritten; values above maxPooledValueSize get exact owned output instead. |
The slab encoder is a closure, not a serializer class. Its state is three local variables, and separate instances share nothing:
/** An explicit allocation policy. The closure owns at most one current slab.
* Previously returned views stay valid and never overlap subsequent writes.
* Large items bypass the pool. Callers must not transfer/detach or modify the
* entire backing buffer; mutating their own returned slice is allowed. */
export function createSlabEncoder(options: SlabOptions = {}): (value: Value) => Uint8Array {
const slabSize = options.slabSize ?? 65536;
const threshold = options.maxPooledValueSize ?? Math.max(1, Math.floor(slabSize / 4));
if (!Number.isSafeInteger(slabSize) || slabSize < 1 || slabSize > 0x7fffffff ||
!Number.isSafeInteger(threshold) || threshold < 0 || threshold > slabSize) {
throw new RangeError('Invalid slab size or maxPooledValueSize');
}
const profile = profileOf(options);
let slab: Uint8Array | undefined;
let cursor = 0;
let busy = false;
const pool = (bytes: Uint8Array, end: number): Uint8Array => {
if (end > threshold) return bytes.slice(0, end);
if (!slab || end > slab.length - cursor) {
slab = new Uint8Array(slabSize);
cursor = 0;
}
slab.set(bytes.subarray(0, end), cursor);
cursor += end;
return slab.subarray(cursor - end, cursor);
};Decoding has the same choice for byte strings, as an option rather than a separate API:
export interface DecodeOptions {
/** How byte strings and typed arrays relate to the input:
* 'copy' (default): copied, so independent of the input; byte strings over
* 64 bytes from one decode may share one backing buffer (an arena).
* 'copy-separate': each copied into its own exactly sized buffer.
* 'borrow': views into the input where possible (aligned, native-endian);
* fastest, valid while the input is unchanged. */
readonly binaryOwnership?: 'copy' | 'copy-separate' | 'borrow';4. Named wire constants that compile to literals
Every module reads and writes CBOR through one vocabulary in header.ts. The constants are const enums, so the TypeScript compiler replaces each use with its number. The source reads Major.Text; the compiled loop compares against 3.
// A CBOR data item starts with an initial byte: the major type in the top 3
// bits and "additional info" in the low 5. Additional info below 24 is the
// argument itself; 24–27 mean the argument follows in 1, 2, 4 or 8 bytes;
// 31 marks an indefinite length. Read them as `token >>> 5` and `token & 31`.
// Named wire constants. Const enums: the compiler substitutes each value at
// its use site, so hot loops compare against literals. (Imported `const`
// bindings measured ~15% slower in the array decoder.)
/** Major types, as read from an initial byte with `token >>> 5`. */
export const enum Major { Unsigned = 0, Negative = 1, Bytes = 2, Text = 3, Array = 4, Map = 5, Tag = 6, Simple = 7 }
/** Major types shifted into place, for writing an initial byte. */
export const enum MajorBits {
Unsigned = Major.Unsigned << 5, Negative = Major.Negative << 5, Bytes = Major.Bytes << 5, Text = Major.Text << 5,
Array = Major.Array << 5, Map = Major.Map << 5, Tag = Major.Tag << 5, Simple = Major.Simple << 5,
}
/** Additional info (`token & 31`) values with a meaning of their own. */
export const enum Info { OneByte = 24, EightBytes = 27, Indefinite = 31 }
/** Whole initial bytes. */
export const enum Token { Float64 = 0xfb, Break = 0xff }Here they are in the array decoder's hot loop:
const majorType = token >>> 5;
const elementInfo = token & 31;
if (majorType === Major.Text && elementInfo !== Info.Indefinite) {
const byteLength = readArgumentValue(bytes, position, elementInfo);
position = argumentEnd(position, elementInfo);
values[index] = StringCodec.readPayload(bytes, position, byteLength, state.options, state);
position += byteLength;
} else if (majorType === Major.Unsigned && elementInfo < Info.EightBytes) {
values[index] = readArgumentValue(bytes, position, elementInfo);
position = argumentEnd(position, elementInfo);
} else if (majorType <= Major.Negative) { // unsigned or negative, including 64-bit arguments (maybe bigints)5. Readable names, even in hot paths
The fastest loops in the library still use whole words: position, token, additionalInfo, byteLength. Comments explain each non-obvious choice and the measurement behind it. This is the start of the array decoder, the loop that runs once per element:
// Preallocated (holey) beats push by ~1.6x here; holey elements had no
// measurable cost for consumers (indexing, map, for-of) in V8.
// oxlint-disable-next-line unicorn/no-new-array -- a length, deliberately
const values: Value[] = new Array(length);
for (let index = 0; index < length; index++) {
readable(bytes, position, 1);
const token = bytes[position++];
if (token < 24) {
values[index] = token; // small unsigned integer: the token is the value
continue;
}
if (token === Token.Float64) {
readable(bytes, position, 8);
// DataView.getFloat64 is an intrinsic and the fastest path, but building
// a DataView over a small on-heap buffer is costly. Inputs over 64 bytes
// are already off-heap, so one view is shared by the whole decode.
if (state.floatView === undefined && bytes.length > 64) {
state.floatView = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
}
values[index] = state.floatView !== undefined
? state.floatView.getFloat64(position)
: NumberCodec.readFloat64(bytes, position);
position += 8;
continue;
}
if (Simple.isToken(token)) {
values[index] = Simple.valueOf(token);
continue;
}Even an eight-bytes-at-a-time ASCII decoder spells its bytes out:
/** Short ASCII: checks 8 bytes at a time and builds 8 characters per call.
* Returns undefined at the first non-ASCII byte. */
function decodeAscii(bytes: Uint8Array, start: number, end: number): string | undefined {
let position = start;
let text = '';
while (position + 8 <= end) {
const byte0 = bytes[position], byte1 = bytes[position + 1], byte2 = bytes[position + 2], byte3 = bytes[position + 3];
const byte4 = bytes[position + 4], byte5 = bytes[position + 5], byte6 = bytes[position + 6], byte7 = bytes[position + 7];
if ((byte0 | byte1 | byte2 | byte3 | byte4 | byte5 | byte6 | byte7) & 0x80) return undefined;
text += fromCharCode(byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7);
position += 8;
}
if (position === end) return text;
let highBits = 0;
for (let index = position; index < end; index++) highBits |= bytes[index];
if (highBits & 0x80) return undefined;
return text + asciiTail(bytes, position, end - position);
}6. Performance is measured, one process per benchmark
Each workload in the benchmark runs in its own Node process. The README explains why: workloads sharing a process skew each other's V8 type feedback by up to 2×. Results are the median of 5 × 80 ms rounds, and BENCHMARK.md treats anything within about ±10% of 1.0 as level, because repeated runs of the same code moved that much.
Measurements decide the shape of the code, and the code records them where they apply. Here a helper that would read more cleanly was kept out of the object loop, because V8 did not reliably inline it:
/** Whether another entry follows; consumes the break of an indefinite map.
* Loops test `index < entryCount` themselves first: per-entry calls here,
* when V8 did not inline them, made small-object decoding bimodal (+40%). */
function moreEntries(state: DecodeState, index: number, entryCount: number, headerOffset: number): boolean {
if (entryCount !== UNTIL_BREAK) return index < entryCount;
readable(state.bytes, state.position, 1);
if (state.bytes[state.position] === Token.Break) {
state.position++;
return false;
}
if (index >= state.maxMapEntries) fail('map-limit', headerOffset, 'Map exceeds maxMapEntries');
return true;
}/** state.position is immediately after the map's initial byte. Text keys build
* a plain object; Map is used in 'map' mode, or in 'auto' mode from the first
* non-text key. The object loop stays in this function: one call deeper, it
* was not reliably inlined and small-object decoding became bimodal. */
export function read(state: DecodeState, additionalInfo: number, readValue: ReadValue): Value {The design records go further: DESIGN-coverage.md lists two "cleaner" refactors that measured slower and were reverted. Correctness is checked before speed, too. Before timing, every workload must round-trip exactly through pure-cbor and read back identically in cbor-x and cborg. The performance notes collect each of these choices with its measured effect.
Part 2
Encode, step by step
Owned encoding writes a value once into a reusable staging buffer, then copies the used bytes out once. There is no sizing pass, and the output is one exactly sized allocation. As you scroll, the panel follows { id: 7, name: 'Ada' } through each step: the function that is running, and the bytes it is responsible for.
1. encode(): the front door
The public encode lives in allocation.ts, because it is an allocation policy. Options leave on the first line. Numbers, booleans, null, undefined and typed arrays have sizes known up front, so they are written straight into an exactly sized array with no writer at all. Strings go directly into staging memory. Everything else is staged.
/** Exact-sized, independently owned output. Small outputs never touch a
* `.buffer`, so they stay cheap V8 on-heap allocations. */
export function encode(value: Value, options?: EncodeOptions): Uint8Array {
// Options take a separate path; the default below is unchanged by them.
if (options !== undefined) return encodeWithOptions(value, profileOf(options));
if (typeof value === 'number') {
const bytes = new Uint8Array(NumberCodec.size(value));
NumberCodec.write(bytes, 0, value);
return bytes;
}
if (Simple.isSimple(value)) {
const bytes = new Uint8Array(1);
bytes[0] = Simple.tokenOf(value);
return bytes;
}
if (typeof value === 'string') {
// Direct into staging: the most common owned value needs no writer.
const capacity = StringCodec.maxSize(value);
if (capacity > STAGING_LIMIT || stagingInUse) return StringCodec.encodeOwned(value);
if (staging.length < capacity) staging = new Uint8Array(Math.max(capacity, 2 * staging.length, 256));
return staging.slice(0, StringCodec.write(staging, 0, value));
}
if (arrayKind(value) !== undefined) {
const bytes = new Uint8Array(TypedArrayCodec.size(value as TypedArray));
TypedArrayCodec.write(bytes, 0, value as TypedArray);
return bytes;
}
return staged(value, DEFAULT_PROFILE, copyOut);
}2. staged(): one growable pass
The staging buffer is the only module-level memory the encoder uses, and it holds no data between calls: take must copy what it needs before staged returns. If an exotic input such as an accessor property calls encode again in the middle, the inner call gets a private buffer instead. A buffer that grew is kept up to 256 KiB, so outputs up to that size don't regrow it on every call.
/** Staging memory for owned text and container output: one growable pass,
* then the used bytes are copied out once. One output allocation and no
* sizing pass. (In V8 any typed array over 64 bytes is a separate off-heap
* allocation costing ~0.5 µs, so allocation count dominates.) It holds no data
* between calls; a reentrant call, possible only through exotic inputs such
* as accessor properties, uses a private buffer instead. A buffer that grew
* is kept up to 256 KiB: at 64 KiB, every larger output regrew it and copied
* the first 64 KB again, which made a 130 KB float mesh 6% and a 90 KB float
* array 18% slower to encode. */
const STAGING_LIMIT = 256 * 1024;
let staging: Uint8Array = new Uint8Array(0);
let stagingInUse = false;
/** Encode into staging memory and hand the used bytes to `take`, which must
* copy what it needs before returning. */
function staged<R>(value: Value, profile: EncodeProfile, take: (bytes: Uint8Array, end: number) => R): R {
if (stagingInUse) {
const writer = createWriter(new Uint8Array(256), 0, true);
writerFor(profile)(writer, value, 0);
return take(writer.bytes, writer.position);
}
stagingInUse = true;
try {
const writer = createWriter(staging, 0, true);
writerFor(profile)(writer, value, 0);
if (writer.bytes.length <= STAGING_LIMIT) staging = writer.bytes;
return take(writer.bytes, writer.position);
} finally {
stagingInUse = false;
}
}
const copyOut = (bytes: Uint8Array, end: number): Uint8Array => bytes.slice(0, end);The README gives the reason for this design: in V8 every typed array over 64 bytes is a separate off-heap allocation of about 0.5 µs, so allocation count dominates. Writing once into reused memory and copying out once gives one output allocation and no sizing pass.
3. writerFor() picks the write function
For the default profile this is a single identity comparison. Other profiles get a separate recursive writer, built once and kept in a Map. Principle 2 shows how profiles are chosen.
const writers = new Map<EncodeProfile, WriteValue>();
/** The write function for an encode profile. The default needs no lookup:
* this runs on every encode call. */
export function writerFor(profile: EncodeProfile): WriteValue {
if (profile === DEFAULT_PROFILE) return writeValue;
let writer = writers.get(profile);
if (writer === undefined) {
writer = optionsWriter(profile);
writers.set(profile, writer);
}
return writer;
}4. writeValue(): the dispatcher
The dispatcher tests the common types first: scalars, then arrays, plain objects, byte strings and typed arrays. The rarer variants are moved into a second function, writeRareValue, which keeps the hot one small. Containers get nestedDepth(depth), which fails with depth-limit at 128 levels. That limit also turns cyclic input into a typed error.
/** Encode-side nesting limit; also turns cyclic input into a typed error. */
const MAX_ENCODE_DEPTH = 128;
function nestedDepth(depth: number): number {
if (depth >= MAX_ENCODE_DEPTH) fail('depth-limit', 0, 'Nesting exceeds maximum depth (cyclic input?)');
return depth + 1;
}
// …
// ---------------------------------------------------------------- writing
/** Write one value at the writer's cursor. Growable writers grow as needed;
* fixed writers were preflighted by the caller. */
export function writeValue(writer: Writer, value: Value, depth: number): void {
const end = writeScalar(writer, writer.position, value);
if (end !== NOT_SCALAR) {
writer.position = end;
} else if (Array.isArray(value)) {
ArrayCodec.write(writer, value, nestedDepth(depth), writeValue);
} else if (MapCodec.isPlainObject(value)) {
MapCodec.writeObject(writer, value, nestedDepth(depth), writeValue);
} else if (value instanceof Uint8Array) { // and Buffer: a byte string, no kind lookup
ensure(writer, 9 + value.length);
writer.position = TypedArrayCodec.writeByteString(writer.bytes, writer.position, value);
} else if (arrayKind(value) !== undefined) {
ensure(writer, TypedArrayCodec.size(value as TypedArray));
writer.position = TypedArrayCodec.write(writer.bytes, writer.position, value as TypedArray);
} else {
writeRareValue(writer, value, depth);
}
}
/** bigint, Date, Map, Tagged and SimpleValue. */
function writeRareValue(writer: Writer, value: Value, depth: number): void {
if (typeof value === 'bigint') {
ensure(writer, Bignum.size(value));
writer.position = Bignum.write(writer.bytes, writer.position, value);
} else if (value instanceof Date) {
writeDate(writer, value, false);
} else if (value instanceof Map) {
MapCodec.writeMap(writer, value, nestedDepth(depth), writeValue);
} else if (Tag.isTagged(value)) {
ensure(writer, argumentSize(value.tag));
writer.position = writeArgument(writer.bytes, writer.position, MajorBits.Tag, value.tag);
writeValue(writer, value.value, nestedDepth(depth));
} else if (Simple.isSimpleValue(value)) {
ensure(writer, Simple.simpleSize(value));
writer.position = Simple.writeSimpleValue(writer.bytes, writer.position, value);
} else {
unsupported();
}
}5. Scalars and the argument header
writeScalar returns the new position, or NOT_SCALAR so the dispatcher can carry on. It asks the writer for room first: 9 bytes covers any number.
/** Returned by writeScalar when the value is not a scalar. */
export const NOT_SCALAR = -1;
/** Above this many UTF-16 units, size strings exactly rather than reserving 3 bytes per unit. */
const LARGE_STRING = 16 * 1024;
/** Write a number, string, boolean, null or undefined at `position` and
* return the new position, or NOT_SCALAR for anything else. */
export function writeScalar(writer: Writer, position: number, value: unknown): number {
if (typeof value === 'number') {
return NumberCodec.write(roomFor(writer, position, 9), position, value);
}
if (typeof value === 'string') {
const capacity = value.length > LARGE_STRING ? StringCodec.size(value) : StringCodec.maxSize(value);
return StringCodec.write(roomFor(writer, position, capacity), position, value);
}
if (Simple.isSimple(value)) {
roomFor(writer, position, 1)[position] = Simple.tokenOf(value);
return position + 1;
}
return NOT_SCALAR;
}Safe integers are always CBOR integers in their preferred width, so millisecond timestamps reach other languages as integers. Everything else, including -0 and NaN, is binary64 by default:
/** Every safe integer is a CBOR integer in its preferred width, so other
* languages receive integer types (e.g. millisecond timestamps). Everything
* else (fractions, -0, NaN, infinities, unsafe integers) is binary64. */
function majorTypeOf(value: number): Major.Unsigned | Major.Negative | Major.Simple {
if ((value >>> 0) === value) return Object.is(value, -0) ? FLOAT : Major.Unsigned;
if (Number.isSafeInteger(value)) return value < 0 ? Major.Negative : Major.Unsigned;
return FLOAT;
}
// …
/** The default: integers in their preferred width, everything else binary64. */
export function write(bytes: Uint8Array, offset: number, value: number): number {
const majorType = majorTypeOf(value);
if (majorType === FLOAT) {
writable(bytes, offset, 9);
return writeFloat64(bytes, offset, value);
}
const argument = majorType === Major.Unsigned ? value : -1 - value;
writable(bytes, offset, argumentSize(argument));
return writeArgument(bytes, offset, majorType << 5, argument);
}Every header goes through writeArgument, which picks the smallest width for the argument. It writes byte by byte, with no DataView:
/** majorBits is the already-shifted major type, e.g. 0x60 for text.
* Internal primitive: the caller checks capacity for header and payload once. */
export function writeArgument(bytes: Uint8Array, offset: number, majorBits: number, argument: number): number {
if (argument < 24) {
bytes[offset] = majorBits | argument;
return offset + 1;
}
if (argument < 256) {
bytes[offset] = majorBits | 24;
bytes[offset + 1] = argument;
return offset + 2;
}
if (argument < 65536) {
bytes[offset] = majorBits | 25;
bytes[offset + 1] = argument >>> 8;
bytes[offset + 2] = argument;
return offset + 3;
}
if (argument <= MAX_UINT32) {
bytes[offset] = majorBits | 26;
writeUint32(bytes, offset + 1, argument);
return offset + 5;
}
bytes[offset] = majorBits | 27;
writeUint32(bytes, offset + 1, Math.floor(argument / TWO_POW_32));
writeUint32(bytes, offset + 5, argument >>> 0);
return offset + 9;
}6. The Writer cursor
A growable writer reallocates on demand; a fixed writer wraps caller memory and never grows, because its capacity was checked before writing began. Loops that keep the cursor in a local variable call roomFor, which stores the position back only if it has to grow.
/** Make room for `byteCount` more bytes at the cursor (growable writers only). */
export function ensure(writer: Writer, byteCount: number): void {
if (byteCount > writer.bytes.length - writer.position && writer.growable) grow(writer, byteCount);
}
/** The writer's bytes, with room for `byteCount` at `position`. For loops that
* keep the cursor in a local variable; fixed writers were preflighted. */
export function roomFor(writer: Writer, position: number, byteCount: number): Uint8Array {
if (byteCount > writer.bytes.length - position && writer.growable) {
writer.position = position;
grow(writer, byteCount);
}
return writer.bytes;
}
function grow(writer: Writer, byteCount: number): void {
const larger = new Uint8Array(Math.max(2 * writer.bytes.length, writer.position + byteCount, 256));
larger.set(writer.bytes.subarray(0, writer.position));
writer.bytes = larger;
}7. Arrays: a local cursor and inline scalars
The array writer keeps position in a local variable and spells out the scalar cases rather than calling writeScalar. Only nested items go back through the dispatcher, which is passed in as a parameter so that array.ts does not import codec.ts.
/** Scalars are written inline with a local cursor (the hot path); only
* nested items go through the dispatcher. The scalar branches are spelled out
* here rather than calling writeScalar: V8 often declines to inline a shared
* helper into this loop, and that measured 10-20% slower. */
export function write(writer: Writer, values: readonly Value[], depth: number, writeValue: WriteValue): void {
let position = writeArgument(roomFor(writer, writer.position, 9), writer.position, MajorBits.Array, values.length);
for (let index = 0; index < values.length; index++) {
const element = values[index];
if (typeof element === 'number') {
position = NumberCodec.write(roomFor(writer, position, 9), position, element);
} else if (typeof element === 'string') {
position = StringCodec.write(roomFor(writer, position, StringCodec.maxSize(element)), position, element);
} else if (Simple.isSimple(element)) { // includes undefined and holes
roomFor(writer, position, 1)[position++] = Simple.tokenOf(element);
} else {
writer.position = position;
writeValue(writer, element, depth);
position = writer.position;
}
}
writer.position = position;
}8. Plain objects and the back-patched header
Only objects whose prototype is Object.prototype or null are encoded as maps; dates, class instances and boxed primitives are rejected rather than flattened. Keys are enumerated with for…in, and the own-property check runs only if Object.prototype has gained enumerable properties.
/** Plain objects only: prototype Object.prototype or null. Dates, Maps, class
* instances and boxed primitives are rejected rather than silently flattened. */
export function isPlainObject(value: unknown): value is ValueObject {
if (typeof value !== 'object' || value === null) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
/** True if Object.prototype has gained enumerable properties (prototype
* pollution), which `for...in` would otherwise report as the object's own. */
function objectPrototypeHasEnumerableKeys(): boolean {
for (const _ in Object.prototype) return true;
return false;
}The entry count is only known after the loop, because properties set to undefined are skipped. So the writer reserves one header byte, which is enough for up to 23 entries, and fills it in at the end. A larger map shifts its entries right by the extra header bytes, which keeps the preferred, smallest header.
/** One pass with a local cursor. The entry count is only known at the end, so
* a 1-byte header (fewer than 24 entries, the common case) is reserved and
* filled in last; larger maps shift their entries right to fit the wider
* header, which keeps the preferred (smallest) encoding. */
export function writeObject(writer: Writer, object: ValueObject, depth: number, writeValue: WriteValue): void {
const checkOwn = objectPrototypeHasEnumerableKeys();
const headerOffset = writer.position;
roomFor(writer, headerOffset, 1);
let position = headerOffset + 1;
let entryCount = 0;
for (const key in object) {
if (checkOwn && !Object.hasOwn(object, key)) continue;
const value = object[key];
if (value === undefined) continue;
entryCount++;
position = writeKey(writer, position, key);
// Scalar values inline, as in the array writer (see the note there).
if (typeof value === 'number') {
position = NumberCodec.write(roomFor(writer, position, 9), position, value);
} else if (typeof value === 'string') {
position = StringCodec.write(roomFor(writer, position, StringCodec.maxSize(value)), position, value);
} else if (Simple.isSimple(value)) {
roomFor(writer, position, 1)[position++] = Simple.tokenOf(value);
} else {
writer.position = position;
writeValue(writer, value, depth);
position = writer.position;
}
}
const extraHeaderBytes = argumentSize(entryCount) - 1;
const bytes = roomFor(writer, position, extraHeaderBytes);
if (extraHeaderBytes > 0) {
bytes.copyWithin(headerOffset + 1 + extraHeaderBytes, headerOffset + 1, position);
position += extraHeaderBytes;
}
writeArgument(bytes, headerOffset, MajorBits.Map, entryCount);
writer.position = position;
}
/** Keys are usually short ASCII: write the 1-byte header and the characters
* directly. Anything else goes through the general text writer. */
function writeKey(writer: Writer, position: number, key: string): number {
const length = key.length;
if (length >= 24) return StringCodec.write(roomFor(writer, position, StringCodec.maxSize(key)), position, key);
const bytes = roomFor(writer, position, length + 1);
for (let index = 0; index < length; index++) {
const unit = key.charCodeAt(index);
if (unit >= 0x80) return StringCodec.write(roomFor(writer, position, StringCodec.maxSize(key)), position, key);
bytes[position + 1 + index] = unit;
}
bytes[position] = MajorBits.Text | length;
return position + 1 + length;
}9. Map: any keys, inline COSE shapes
A Map knows its size up front, so its header is written first. Keys and values share one helper with inline paths for the shapes COSE uses: integer and short text keys, and byte-string and scalar values.
/** Any key types, in insertion order; undefined values are written (f7).
* A local cursor with inline paths for the common COSE shapes (integer and
* short text keys, byte-string and scalar values); anything else goes through
* the dispatcher. */
export function writeMap(writer: Writer, map: ReadonlyMap<Value, Value>, depth: number, writeValue: WriteValue): void {
let position = writeArgument(roomFor(writer, writer.position, 9), writer.position, MajorBits.Map, map.size);
for (const [key, value] of map) {
position = writeMapItem(writer, position, key, depth, writeValue);
position = writeMapItem(writer, position, value, depth, writeValue);
}
writer.position = position;
}
function writeMapItem(writer: Writer, position: number, item: Value, depth: number, writeValue: WriteValue): number {
if (typeof item === 'number') return NumberCodec.write(roomFor(writer, position, 9), position, item);
if (typeof item === 'string') return writeKey(writer, position, item);
if (item instanceof Uint8Array) {
return TypedArrayCodec.writeByteString(roomFor(writer, position, 9 + item.length), position, item);
}
if (Simple.isSimple(item)) {
roomFor(writer, position, 1)[position] = Simple.tokenOf(item);
return position + 1;
}
writer.position = position;
writeValue(writer, item, depth);
return writer.position;
}10. Strings: reserve, write, patch
Text uses the same trick as objects. The header is reserved for the string's UTF-16 length, the UTF-8 bytes are written, and the header is corrected afterwards, moving the payload only if the width changed. When the destination is tight, the exact size is computed first so a capacity error never leaves a partial write.
/** Common path is single-pass into spare capacity, back-patching the header.
* Tight buffers get exact sizing first, so an insufficient-capacity error never
* partially writes the destination. */
export function write(bytes: Uint8Array, offset: number, value: string): number {
if (maxSize(value) > bytes.length - offset) {
return writeSized(bytes, offset, value, utf8Size(value));
}
const reservedHeader = argumentSize(value.length);
const payloadStart = offset + reservedHeader;
const payloadEnd = writeUtf8(bytes, payloadStart, value);
const byteLength = payloadEnd - payloadStart;
const actualHeader = argumentSize(byteLength);
if (actualHeader !== reservedHeader) bytes.copyWithin(offset + actualHeader, payloadStart, payloadEnd);
writeArgument(bytes, offset, MajorBits.Text, byteLength);
return offset + actualHeader + byteLength;
}11. Deterministic encoding
With deterministic: true, optionsWriter collects each map's entries and writes them in the order of their encoded keys (RFC 8949 §4.2.1). Two keys that encode to the same bytes, such as 1 and 1n in one Map, are a duplicate-key error.
/** RFC 8949 §4.2.1: entries ordered by the bytes of their encoded keys.
* Keys that encode identically are duplicates, which deterministic CBOR forbids. */
export function writeSortedEntries(writer: Writer, entries: ReadonlyArray<readonly [Value, Value]>, depth: number, writeValue: WriteValue): void {
const encodedKeys = entries.map(([key]) => encodeKey(key, depth, writeValue));
const { order, hasEqual } = sortEncodedKeys(encodedKeys);
if (hasEqual) fail('duplicate-key', writer.position, 'Duplicate map key');
ensure(writer, 9);
writer.position = writeArgument(writer.bytes, writer.position, MajorBits.Map, entries.length);
for (const index of order) {
const key = encodedKeys[index];
ensure(writer, key.length);
writer.bytes.set(key, writer.position);
writer.position += key.length;
writeValue(writer, entries[index][1], depth);
}
}12. Caller memory: measure first, never write partially
encodeInto and write use a fixed writer over the caller's bytes. Scalars check their own size. For anything else, a cheap upper bound is measured first; only if that bound exceeds the free space is the exact size measured, and a capacity error thrown before any byte is written.
/** Append one item into caller memory. A capacity error never partially
* writes: scalars check their own size, everything else is measured first. */
export function writeBytes(bytes: Uint8Array, offset: number, value: Value, profile: EncodeProfile = DEFAULT_PROFILE): number {
checkOffset(bytes, offset);
if (typeof value === 'number') {
return profile.shortestFloats ? NumberCodec.writeShortest(bytes, offset, value) : NumberCodec.write(bytes, offset, value);
}
if (typeof value === 'string') return StringCodec.write(bytes, offset, value);
if (Simple.isSimple(value)) return Simple.write(bytes, offset, value);
if (arrayKind(value) !== undefined) return TypedArrayCodec.write(bytes, offset, value as TypedArray);
if (measure(value, true, 0, profile.shortestFloats) > bytes.length - offset) {
writable(bytes, offset, measure(value, false, 0, profile.shortestFloats));
}
const writer = createWriter(bytes, offset, false);
writerFor(profile)(writer, value, 0);
return writer.position;
}The README notes the trade-off: for arrays and objects this guarantee costs a sizing pass, so owned encode() can be faster for objects.
Part 3
Decode, step by step
Decoding a scalar touches no state at all. Decoding a container creates one small state record for that call and passes it down explicitly. The panel now reads the same 14 bytes back.
1. decode() and binary()
decode wraps the bytes in a Binary descriptor and reads exactly one item. The descriptor has no cursor and, deliberately, no DataView.
export function decode(bytes: Uint8Array, options?: DecodeOptions): Value {
return readWhole(binary(bytes), options);
}/** Immutable descriptor over explicitly mutable memory. No cursor.
* Deliberately holds no DataView: reading `.buffer` on a small, freshly
* allocated Uint8Array forces V8 to externalize its backing store, which costs
* far more than encoding or decoding a small value. */
export type Binary = Readonly<{ bytes: Uint8Array }>;
// …
/** Prepare once when repeatedly reading/writing the same buffer. */
export function binary(bytes: Uint8Array): Binary {
if (!(bytes instanceof Uint8Array) && arrayKind(bytes) !== 'Uint8Array') {
fail('invalid-buffer', 0, 'Expected a Uint8Array');
}
return { bytes };
}The comment explains why: building a DataView means reading .buffer, which forces V8 to move a small fresh array's bytes off-heap. The README measures that at about 900 ns per message, more than the encode or decode itself.
2. readItem(): scalars need no state
The top-level reader switches on the major type in the first byte. Integers, simple values, floats, text and byte strings are read straight from (bytes, offset). Only arrays, maps and tags create a DecodeState, once, for their whole tree. A whole-value read returns the value itself; read returns a [value, nextOffset] pair so callers can walk a sequence.
/** Top-level dispatch. Scalars, strings and typed arrays are read directly
* (no state, and no tuple for whole-value reads); containers and other tags
* create one DecodeState for their tree. */
function readItem(buffer: Binary, offset: number, options: DecodeOptions | undefined, whole: true): Value;
function readItem(buffer: Binary, offset: number, options: DecodeOptions | undefined, whole: false): Decoded;
function readItem(buffer: Binary, offset: number, options: DecodeOptions | undefined, whole: boolean): Value | Decoded {
const bytes = buffer.bytes;
checkOffset(bytes, offset);
readable(bytes, offset, 1);
const token = bytes[offset++];
const majorType = token >>> 5;
const additionalInfo = token & 31;
let value: Value;
let end: number;
switch (majorType) {
case Major.Unsigned: case Major.Negative:
value = NumberCodec.readValue(bytes, offset, token);
end = argumentEnd(offset, additionalInfo);
break;
case Major.Simple:
value = Simple.readMajor7(bytes, offset, token);
end = argumentEnd(offset, additionalInfo);
break;
case Major.Text:
if (additionalInfo !== Info.Indefinite) {
// Definite text inline: no result tuple on the most common path.
const byteLength = readArgumentValue(bytes, offset, additionalInfo);
const start = argumentEnd(offset, additionalInfo);
value = StringCodec.readPayload(bytes, start, byteLength, options);
end = start + byteLength;
} else {
[value, end] = Indefinite.readChunked(bytes, offset, Major.Text, options);
}
break;
case Major.Bytes:
[value, end] = readByteString(bytes, offset, additionalInfo, options);
break;
default: { // arrays, maps and tags
const state = createState(bytes, offset, options);
value = majorType === Major.Array ? ArrayCodec.read(state, additionalInfo, readValue)
: majorType === Major.Map ? MapCodec.read(state, additionalInfo, readValue)
: readTag(state, additionalInfo);
end = state.position;
}
}
if (whole) {
if (end !== bytes.length) fail('trailing-data', end, 'Unexpected bytes after CBOR value');
return value;
}
return [value, end];
}
export function read(buffer: Binary, offset: number, options?: DecodeOptions): Decoded {
return readItem(buffer, offset, options, false);
}
/** Prepared-buffer whole-value decode, useful for reused input views. */
export function readWhole(buffer: Binary, options?: DecodeOptions): Value {
return readItem(buffer, 0, options, true);
}3. createState() and the limits
The state record is built once, with its limits already validated. Its item budget starts at the number of bytes left. Every container subtracts its declared item count on entry; since each item needs at least one byte, a valid message can never exceed its own length.
/** position is immediately after the container's initial byte. */
export function createState(bytes: Uint8Array, position: number, options: DecodeOptions | undefined): DecodeState {
const headerOffset = position - 1;
const limits = containerLimits(options, headerOffset);
return {
bytes,
position,
depth: 0,
itemBudget: bytes.length - headerOffset,
options,
floatView: undefined,
arena: undefined,
arenaUsed: 0,
windowStart: 0,
windowText: '',
useArena: options?.binaryOwnership === undefined || options.binaryOwnership === 'copy',
maxArrayLength: limits.maxArrayLength,
maxMapEntries: limits.maxMapEntries,
maxDepth: limits.maxDepth,
rejectDuplicateKeys: options?.duplicateKeys !== 'last-wins',
integerOrTextKeys: options?.mapKeys === 'integer-or-text',
mapMode: options?.maps ?? 'auto',
};
}
/** Enter a container whose initial byte is at headerOffset and which declares
* itemCount nested items. */
export function enterContainer(state: DecodeState, itemCount: number, headerOffset: number): void {
if (state.depth >= state.maxDepth) fail('depth-limit', headerOffset, 'Nesting exceeds maxDepth');
if (itemCount > state.itemBudget) fail('truncated', headerOffset, 'Declared items exceed the remaining input');
state.depth++;
state.itemBudget -= itemCount;
}
export function leaveContainer(state: DecodeState): void {
state.depth--;
}The defaults are 1,000,000 elements per array, 1,000,000 entries per map and 128 levels of nesting. Tags count toward depth too, so deep input fails with depth-limit instead of overflowing the stack.
4. readValue(): the nested-item dispatcher
Every nested item goes through here. A token below 24 is a small unsigned integer and is its own value, so it returns before the switch. Definite text is decoded inline with no result tuple, and definite byte strings in the default 'copy' mode go through Arena.copyByteString.
/** Read one nested item at the cursor and advance it. */
export function readValue(state: DecodeState): Value {
const bytes = state.bytes;
let position = state.position;
readable(bytes, position, 1);
const token = bytes[position++];
if (token < 24) {
state.position = position;
return token; // small unsigned integer: the token is the value
}
const additionalInfo = token & 31;
switch (token >>> 5) {
case Major.Unsigned: case Major.Negative: {
const value = NumberCodec.readValue(bytes, position, token);
state.position = argumentEnd(position, additionalInfo);
return value;
}
case Major.Simple: {
const value = Simple.readMajor7(bytes, position, token);
state.position = argumentEnd(position, additionalInfo);
return value;
}
case Major.Text: {
if (additionalInfo !== Info.Indefinite) {
// Definite text inline: no result tuple on the most common path.
const byteLength = readArgumentValue(bytes, position, additionalInfo);
const start = argumentEnd(position, additionalInfo);
const value = StringCodec.readPayload(bytes, start, byteLength, state.options, state);
state.position = start + byteLength;
return value;
}
const [value, end] = Indefinite.readChunked(bytes, position, Major.Text, state.options);
state.position = end;
return value;
}
case Major.Bytes: {
if (additionalInfo !== Info.Indefinite && state.useArena) {
const byteLength = readArgumentValue(bytes, position, additionalInfo);
const start = argumentEnd(position, additionalInfo);
readable(bytes, start, byteLength);
state.position = start + byteLength;
return Arena.copyByteString(state, start, byteLength);
}
const [value, end] = readByteString(bytes, position, additionalInfo, state.options);
state.position = end;
return value;
}
case Major.Array:
state.position = position;
return ArrayCodec.read(state, additionalInfo, readValue);
case Major.Map:
state.position = position;
return MapCodec.read(state, additionalInfo, readValue);
default: // Major.Tag, the only major type left
state.position = position;
return readTag(state, additionalInfo);
}
}5. The array loop
The declared length is checked against maxArrayLength and against the bytes remaining before anything is allocated. Then the result array is preallocated. The first part of the loop, shown under principle 5, handles small integers, float64 and true/false/null/undefined. The rest handles text and wider integers inline, and hands anything nested to readValue.
/** One local cursor and one result allocation. Scalars are decoded inline with
* no per-element tuples; only nested items go through the dispatcher.
* state.position is immediately after the array's initial byte. */
export function read(state: DecodeState, additionalInfo: number, readValue: ReadValue): Value[] {
if (additionalInfo === Info.Indefinite) return readIndefinite(state, readValue);
const bytes = state.bytes;
const headerOffset = state.position - 1;
const length = readArgumentValue(bytes, state.position, additionalInfo);
let position = argumentEnd(state.position, additionalInfo);
if (length > state.maxArrayLength) fail('array-limit', headerOffset, 'Array exceeds maxArrayLength');
// Each element requires at least one byte, even for empty text.
readable(bytes, position, length);
enterContainer(state, length, headerOffset);
// …
const majorType = token >>> 5;
const elementInfo = token & 31;
if (majorType === Major.Text && elementInfo !== Info.Indefinite) {
const byteLength = readArgumentValue(bytes, position, elementInfo);
position = argumentEnd(position, elementInfo);
values[index] = StringCodec.readPayload(bytes, position, byteLength, state.options, state);
position += byteLength;
} else if (majorType === Major.Unsigned && elementInfo < Info.EightBytes) {
values[index] = readArgumentValue(bytes, position, elementInfo);
position = argumentEnd(position, elementInfo);
} else if (majorType <= Major.Negative) { // unsigned or negative, including 64-bit arguments (maybe bigints)
values[index] = NumberCodec.readValue(bytes, position, token);
position = argumentEnd(position, elementInfo);
} else if (majorType === Major.Simple) {
values[index] = Simple.readMajor7(bytes, position, token);
position = argumentEnd(position, elementInfo);
} else {
// Nested array, map, byte string, tag or chunked text: the dispatcher
// reads from the token.
state.position = position - 1;
values[index] = readValue(state);
position = state.position;
}
}
state.position = position;
leaveContainer(state);
return values;
}6. The map loop
In the default 'auto' mode, a map whose keys are all text becomes a plain object. The object loop lives inside MapCodec.read itself rather than a helper, and small unsigned integer values are decoded inline. A __proto__ key becomes an own data property through Object.defineProperty: no prototype pollution, and no renaming.
export function read(state: DecodeState, additionalInfo: number, readValue: ReadValue): Value {
const bytes = state.bytes;
const headerOffset = state.position - 1;
const indefinite = additionalInfo === Info.Indefinite;
let entryCount = UNTIL_BREAK;
if (indefinite) {
enterContainer(state, 0, headerOffset);
} else {
entryCount = readArgumentValue(bytes, state.position, additionalInfo);
state.position = argumentEnd(state.position, additionalInfo);
if (entryCount > state.maxMapEntries) fail('map-limit', headerOffset, 'Map exceeds maxMapEntries');
// Each entry is at least a key byte and a value byte.
readable(bytes, state.position, 2 * entryCount);
enterContainer(state, 2 * entryCount, headerOffset);
}
// …
const object: Record<string, Value> = {};
let index = 0;
for (; indefinite ? moreEntries(state, index, entryCount, headerOffset) : index < entryCount; index++) {
readable(bytes, state.position, 1);
const keyToken = bytes[state.position];
let key: string;
if (isDefiniteText(keyToken)) {
key = readTextKey(state, keyToken);
} else if (keyToken >>> 5 === Major.Text) {
key = readValue(state) as string; // chunked text
} else if (state.mapMode === 'object') {
return fail('unsupported-type', state.position, 'Map keys must be text strings (decode with maps: "auto" or "map")');
} else {
const map = continueAsMap(state, object, index, entryCount, headerOffset, readValue);
leaveContainer(state);
return map;
}
// Small unsigned integers are the most common value: decode them inline.
readable(bytes, state.position, 1);
const valueToken = bytes[state.position];
let value: Value;
if (valueToken < 24) {
value = valueToken;
state.position++;
} else {
value = readValue(state);
}
if (key === '__proto__') {
// A data property, not the prototype setter: no pollution, no renaming.
Object.defineProperty(object, key, { value, writable: true, enumerable: true, configurable: true });
} else {
object[key] = value;
}
}
if (index > 1) checkDuplicates(state, Object.keys(object).length, index, headerOffset);
leaveContainer(state);
return object;
}If a non-text key appears, the entries read so far move into a Map and decoding carries on there, keeping their order. Duplicate keys are found by counting once per map rather than checking each key. A Map tells keys such as byte strings and arrays apart by identity, so those are compared as CBOR values: byte strings by their bytes, the rest by a fingerprint built from the decoded value, so decoding never needs the encoder.
/** A duplicate key overwrites an earlier one, leaving fewer distinct keys
* than entries. Counting once is ~4x cheaper than checking each key. */
function checkDuplicates(state: DecodeState, distinctKeys: number, entries: number, headerOffset: number): void {
if (state.rejectDuplicateKeys && distinctKeys !== entries) fail('duplicate-key', headerOffset, 'Duplicate map key');
}
// …
/** A Map tells primitive keys apart by value but object keys (byte strings,
* arrays, maps, tags, dates) only by identity, so two equal byte strings are
* two entries. This runs only for maps that have object keys. Byte strings,
* the common case, are equal when their bytes are; the rest are compared by
* fingerprint. */
function checkObjectKeys(state: DecodeState, objectKeys: readonly Value[], headerOffset: number): void {
if (!state.rejectDuplicateKeys || objectKeys.length < 2) return;
const byteStrings: Uint8Array[] = [];
const fingerprints = new Set<string>();
let otherKeys = 0;
for (const key of objectKeys) {
if (key instanceof Uint8Array) {
byteStrings.push(key);
} else {
fingerprints.add(keyFingerprint(key));
otherKeys++;
}
}
if (hasEqualBytes(byteStrings) || fingerprints.size !== otherKeys) fail('duplicate-key', headerOffset, 'Duplicate map key');
}
// …
function readIntoMap(state: DecodeState, map: Map<Value, Value>, index: number, entryCount: number, headerOffset: number, readValue: ReadValue): Map<Value, Value> {
const bytes = state.bytes;
let objectKeys: Value[] | undefined;
let keysByFingerprint: Map<string, Value> | undefined;
for (; moreEntries(state, index, entryCount, headerOffset); index++) {
readable(bytes, state.position, 1);
const keyToken = bytes[state.position];
let key = isDefiniteText(keyToken) ? readTextKey(state, keyToken) : readOtherKey(state, keyToken, readValue);
if (typeof key === 'object' && key !== null) {
if (state.rejectDuplicateKeys) (objectKeys ??= []).push(key);
else key = earlierEqualKey(keysByFingerprint ??= new Map(), key);
}
map.set(key, readEntryValue(state, readValue));
}
checkDuplicates(state, map.size, index, headerOffset);
if (objectKeys !== undefined) checkObjectKeys(state, objectKeys, headerOffset);
return map;
}
/** 'auto' mode met a non-text key: move the entries so far into a Map and continue there. */
function continueAsMap(state: DecodeState, object: Record<string, Value>, index: number, entryCount: number, headerOffset: number, readValue: ReadValue): Map<Value, Value> {
if (index > 1) checkDuplicates(state, Object.keys(object).length, index, headerOffset);
return readIntoMap(state, new Map<Value, Value>(Object.entries(object)), index, entryCount, headerOffset, readValue);
}7. The decoded-key cache
Repeated keys are the norm in CBOR data: a hundred rows share six key names. readTextKey skips the cache for one-character ASCII keys, which V8 already interns, and otherwise asks the cache before decoding.
/** A definite-length text key: repeated keys come from the key cache. */
function readTextKey(state: DecodeState, token: number): string {
const bytes = state.bytes;
const keyOffset = state.position;
const additionalInfo = token & 31;
const byteLength = readArgumentValue(bytes, keyOffset + 1, additionalInfo);
const start = argumentEnd(keyOffset + 1, additionalInfo);
readable(bytes, start, byteLength);
state.position = start + byteLength;
// One ASCII character: V8 keeps these strings in a built-in table, so
// building one is cheaper than a cache lookup.
if (byteLength === 1 && bytes[start] < 0x80) return String.fromCharCode(bytes[start]);
const cached = KeyCache.lookup(bytes, start, byteLength);
if (cached !== undefined) return cached;
const key = StringCodec.readPayload(bytes, start, byteLength, state.options, state);
if (state.options?.invalidUtf8 !== 'replace') KeyCache.remember(bytes, start, byteLength, key);
return key;
}The cache is a 1,024-slot table for keys of up to 32 bytes. A hit is confirmed byte for byte, so a hash collision only costs a miss, and only keys that decoded as valid UTF-8 are stored.
/** Hash of length plus first, middle and last byte. byteLength >= 1. */
function slotFor(bytes: Uint8Array, start: number, byteLength: number): number {
const first = bytes[start];
const middle = bytes[start + (byteLength >>> 1)];
const last = bytes[start + byteLength - 1];
return (byteLength * 31 + first * 7 + middle * 3 + last) & (SLOT_COUNT - 1);
}
export function lookup(bytes: Uint8Array, start: number, byteLength: number): string | undefined {
if (byteLength === 0) return '';
if (byteLength > MAX_KEY_BYTES) return undefined;
const slot = slotFor(bytes, start, byteLength);
const cached = slotBytes[slot];
if (cached === undefined || cached.length !== byteLength) return undefined;
for (let index = 0; index < byteLength; index++) {
if (cached[index] !== bytes[start + index]) return undefined;
}
return slotKeys[slot];
}
/** Store a key whose bytes decoded as valid UTF-8. */
export function remember(bytes: Uint8Array, start: number, byteLength: number, key: string): void {
if (byteLength === 0 || byteLength > MAX_KEY_BYTES) return;
const slot = slotFor(bytes, start, byteLength);
slotBytes[slot] = bytes.slice(start, start + byteLength);
slotKeys[slot] = key;
}8. Text
Short text, up to 32 bytes, is decoded in JavaScript: ASCII eight bytes at a time, then a strict UTF-8 decoder. Anything those don't accept goes to the native TextDecoder, so strict and replacement behaviour are exactly the native ones. readPayload is kept small so V8 can inline it into the array and map loops. Inside a container, an ASCII string of 33–255 bytes starts a window: up to 4 KiB of the input, masked to 7 bits and decoded with one TextDecoder call. Strings of 16 bytes or more inside it are slices, so many strings cost one call instead of one each. Bluesky-style records decode 1.24× faster with it.
/** Kept small so V8 can inline it into hot array and map loops; the native
* decoder and its error handling live in decodeNative. A container decode
* passes its state as `window`; a single top-level string has none. */
export function readPayload(bytes: Uint8Array, start: number, byteLength: number, options: DecodeOptions | undefined, window?: TextWindow): string {
readable(bytes, start, byteLength);
const end = start + byteLength;
if (byteLength <= SHORT_DECODE) {
// Inside a window already decoded, even a short string is cheaper as a slice.
if (window !== undefined && byteLength >= MIN_SLICED && inWindow(window, start, end) && isAscii(bytes, start, end)) {
return window.windowText.slice(start - window.windowStart, end - window.windowStart);
}
const decoded = decodeAscii(bytes, start, end) ?? decodeShortUtf8(bytes, start, end);
if (decoded !== undefined) return decoded;
}
return decodeNative(bytes, start, end, options, window);
}
// …
/** The ASCII string at [start, end) as a slice of the current window, or of
* a new window starting at `start`. */
function sliceWindow(window: TextWindow, bytes: Uint8Array, start: number, end: number): string {
if (!inWindow(window, start, end)) {
const length = Math.min(bytes.length - start, WINDOW_BYTES);
windowScratch.set(bytes.subarray(start, start + length));
for (let index = 0; index < (length + 3) >>> 2; index++) windowWords[index] &= 0x7f7f7f7f;
window.windowText = strictDecoder.decode(windowScratch.subarray(0, length));
window.windowStart = start;
}
return window.windowText.slice(start - window.windowStart, end - window.windowStart);
}
function decodeNative(bytes: Uint8Array, start: number, end: number, options: DecodeOptions | undefined, window: TextWindow | undefined): string {
if (window !== undefined && end - start < WINDOW_MAX_STRING && isAscii(bytes, start, end)) {
return sliceWindow(window, bytes, start, end);
}
try {
const decoder = options?.invalidUtf8 === 'replace' ? lenientDecoder : strictDecoder;
return decoder.decode(bytes.subarray(start, end));
} catch (error) {
if (!(error instanceof TypeError)) throw error;
fail('invalid-utf8', start, 'Invalid UTF-8 text string');
}
}9. The byte-string arena
COSE and WebAuthn messages are mostly byte strings: keys, signatures and certificates. In the default 'copy' mode each must be independent of the input, but a separate copy over 64 bytes costs an off-heap allocation each. So byte strings over 64 bytes from one decode are copied into one shared arena.
// Byte strings copied out of the input during one decode. In V8 every
// Uint8Array over 64 bytes is a separate off-heap allocation (~0.5 µs), and
// COSE/WebAuthn messages are mostly such byte strings (keys, signatures,
// certificates). So larger byte strings are copied into a per-decode arena:
// one allocation, sized to what remains of the input (no larger than 64 KiB
// unless one byte string needs more), filled one after another. Results stay
// independent of the input; byte strings from one decode may share an arena.
// Small byte strings keep their own cheap on-heap copies.
const ON_HEAP_LIMIT = 64;
const MAX_ARENA = 64 * 1024;
/** A copy of bytes[start, start + length). Bounds are already checked. */
export function copyByteString(state: DecodeState, start: number, length: number): Uint8Array {
const input = state.bytes;
if (length <= ON_HEAP_LIMIT) return input.slice(start, start + length);
let arena = state.arena;
if (arena === undefined || length > arena.length - state.arenaUsed) {
// Everything still to come lies in the rest of the input, so this size
// never exceeds it, and a small message gets exactly one arena.
arena = new Uint8Array(Math.max(length, Math.min(input.length - start, MAX_ARENA)));
state.arena = arena;
state.arenaUsed = 0;
}
const offset = state.arenaUsed;
arena.set(input.subarray(start, start + length), offset);
state.arenaUsed = offset + length;
return arena.subarray(offset, offset + length);
}BENCHMARK.md records the effect: since 0.6.0 a COSE or WebAuthn message costs about one allocation, which halved the default mode's time on those flows. The trade-off is documented too: one result can keep its siblings' bytes alive. binaryOwnership: 'copy-separate' gives every byte string its own buffer, and 'borrow' returns views into the input.
10. Tags
RFC 8746 typed-array tags read their byte-string content directly into the right typed array. Every other tag decodes its content (counting toward maxDepth), then converts it: a caller's decoder first, then the built-ins for dates, bignums and the self-described marker, otherwise an immutable Tagged value.
/** A tag: typed arrays read their byte-string content directly; every other
* tag decodes its content (counted toward maxDepth) and then converts it.
* state.position is just after the tag's initial byte. */
function readTag(state: DecodeState, additionalInfo: number): Value {
const bytes = state.bytes;
const headerOffset = state.position - 1;
const tag = readArgumentValue(bytes, state.position, additionalInfo);
const contentOffset = argumentEnd(state.position, additionalInfo);
Tag.checkAllowed(state.options, tag, headerOffset);
if (TypedArrayCodec.isTypedArrayTag(tag) && Tag.handlingOf(state.options, tag) === undefined) {
const [value, end] = TypedArrayCodec.readTaggedContent(bytes, contentOffset, tag, state.options);
state.position = end;
return value;
}
state.position = contentOffset;
enterContainer(state, 1, headerOffset);
const content = readValue(state);
leaveContainer(state);
return Tag.decodeTag(tag, content, state.options, headerOffset);
}/** Checked at the tag's header, before its content is read: a 'reject'
* entry, or tag 55799 under unknownTags: 'reject'. */
export function checkAllowed(options: DecodeOptions | undefined, tag: number, offset: number): void {
const handling = handlingOf(options, tag);
if (handling === 'reject' || (handling === undefined && tag === SELF_DESCRIBED && options?.unknownTags === 'reject')) {
fail('unsupported-tag', offset, `CBOR tag ${tag} is rejected`);
}
}
/** Convert decoded tag content: the caller's entry first ('tagged' keeps the
* tag), then the built-ins, otherwise a Tagged value (or an error with
* unknownTags: 'reject'). */
export function decodeTag(tag: number, content: Value, options: DecodeOptions | undefined, offset: number): Value {
const handling = handlingOf(options, tag);
if (handling === 'tagged') return tagged(tag, content);
if (typeof handling === 'function') return handling(content);
switch (tag) {
case DATE_TIME: return dateFromText(content, offset);
case EPOCH_TIME: return dateFromEpoch(content, offset);
case POSITIVE_BIGNUM: return Bignum.fromBignum(content, false, offset);
case NEGATIVE_BIGNUM: return Bignum.fromBignum(content, true, offset);
case SELF_DESCRIBED: return content;
}
if (options?.unknownTags === 'reject') fail('unsupported-tag', offset, `Unsupported CBOR tag ${tag}`);
return tagged(tag, content);
}11. Limits for hostile input
The README lists what the decoder guarantees against hostile input:
- Every container's declared length is checked against its limit and the remaining input before anything is allocated.
- The per-decode item budget, bounded by the input length, stops a chain of nested headers from preallocating far more than the message could contain.
- Deep input fails with
depth-limitinstead of overflowing the stack. Encoding enforces the same depth limit, which turns cyclic input into a typed error. - Duplicate map keys are rejected by default, and invalid UTF-8 is rejected by default.
It is also clear about what this is not: a full memory-budget guarantee. Apply message byte limits at the transport boundary too. The limits are validated once, by a function shared with the streaming scanner so both report the same errors:
function validLimit(value: number | undefined, fallback: number, code: ErrorCode, name: string, offset: number): number {
if (value === undefined) return fallback;
if (!Number.isSafeInteger(value) || value < 0) fail(code, offset, `Invalid ${name}`);
return value;
}
export interface ContainerLimits {
readonly maxArrayLength: number;
readonly maxMapEntries: number;
readonly maxDepth: number;
}
/** Validated limits from options; shared by the decoder and the sequence scanner. */
export function containerLimits(options: DecodeOptions | undefined, offset: number): ContainerLimits {
return {
maxArrayLength: Math.min(
validLimit(options?.maxArrayLength, DEFAULT_MAX_ARRAY_LENGTH, 'array-limit', 'maxArrayLength', offset),
0xffffffff),
maxMapEntries: validLimit(options?.maxMapEntries, DEFAULT_MAX_MAP_ENTRIES, 'map-limit', 'maxMapEntries', offset),
maxDepth: validLimit(options?.maxDepth, DEFAULT_MAX_DEPTH, 'depth-limit', 'maxDepth', offset),
};
}Part 4
Streaming
A CBOR sequence (RFC 8742) is complete CBOR items written back to back. Over a network they arrive in chunks, and an item can be cut anywhere. pure-cbor decodes the items that sit inside a chunk in place, and gathers the rest with a scanner that reads headers only.
- decoded in place
- cut by a boundary, assembled
- chunk boundary
- pushed so far
| Chunk | Bytes | Values emitted | bufferedBytes after |
|---|
Every row of the table is what createSequenceDecoder().push() actually did, read from its callback and its bufferedBytes. Chunks here are much smaller than the 1 KiB scan-ahead zone, so every item's boundary is checked by the scanner before it is decoded.
Two layers
sequence.ts is an incremental core with no stream APIs in it. It can be fed from WebSocket messages, Node 'data' events or tests. stream.ts is a thin layer of Web Streams and async-iterator adapters over it, which touches stream globals only when called.
Scroll sideways to see the whole diagram.
onValue, onChunk), which allocate nothing per call and map directly onto controller.enqueue.Items across chunk boundaries
Most items sit wholly inside a chunk and are decoded in place, exactly like a normal decode. Only the end of a chunk needs care.
Scroll sideways to see the whole diagram.
SCAN_AHEAD_BYTES (1 KiB) of each chunk, where an item's boundary is checked before it is decoded. Orange: an item cut by the chunk's end, gathered into the assembly buffer.Three constants govern this, each commented with its reason:
const DEFAULT_MAX_ITEM_BYTES = 16 * 1024 * 1024;
/** While assembling an item that spans chunks, copy at least this much of each
* new chunk at a time: few copies, and little copied past the item's end. */
const ASSEMBLY_BLOCK = 4096;
const NO_BYTES = new Uint8Array(0);
/** Near the end of a chunk, check an item's boundary with the scanner before
* decoding it. A cut-off item is then detected without an exception, whose
* stack-trace capture measured ~3.7 µs per chunk boundary. */
const SCAN_AHEAD_BYTES = 1024;The boundary scanner
scanItem walks headers only and skips payloads by their declared length. It decodes nothing, allocates nothing and does not recurse: one counter, itemsPending, tracks how many items the current item still needs (an array adds its length, a map twice its entry count, a tag one). Indefinite-length items push the counter onto a small stack until their break.
/** Resumable boundary scan of one item starting at `start` in `bytes`, of
* which `[start, end)` is available. Walks headers only, skipping payloads by
* their declared length: no decoding, no allocation, no recursion.
* `position` may run past `end` while a payload is still arriving. */
interface ScanState {
position: number;
/** Items still to be seen at the innermost definite level: an array adds its
* length, a map twice its entry count, a tag one. */
itemsPending: number;
/** For each open indefinite-length item, the itemsPending to restore at its break. */
readonly openIndefinite: number[];
}The scan can stop at any byte and resume later from its saved state, so an item spread over many chunks is scanned once in total. That is what keeps decoding linear in the input whatever the chunking.
/** Bytes still needed before the scan can continue, or 0 when the item is
* complete (its end is then scan.position). Error offsets are relative to `start`. */
function scanItem(bytes: Uint8Array, start: number, end: number, scan: ScanState, maxItemBytes: number, limits: ContainerLimits): number {
while (scan.itemsPending > 0 || scan.openIndefinite.length > 0) {
if (scan.position >= end) return scan.position - end + 1;
const headerOffset = scan.position;
const token = bytes[headerOffset];
const additionalInfo = token & 31;
const majorType = token >>> 5;
// Directly inside an open indefinite-length item: its children are not counted.
const atIndefiniteLevel = scan.itemsPending === 0;
if (token === Token.Break) {
if (!atIndefiniteLevel) return deferToDecoder(scan, headerOffset);
scan.itemsPending = scan.openIndefinite.pop()!;
scan.position = headerOffset + 1;
continue;
}
if (additionalInfo === Info.Indefinite) {
if (majorType < Major.Bytes || majorType > Major.Map) return deferToDecoder(scan, headerOffset);
if (!atIndefiniteLevel) scan.itemsPending--;
scan.openIndefinite.push(scan.itemsPending);
scan.itemsPending = 0;
scan.position = headerOffset + 1;
} else {
if (additionalInfo > Info.EightBytes) return deferToDecoder(scan, headerOffset); // reserved
const headerSize = additionalInfo < 24 ? 1 : 1 + (1 << (additionalInfo - 24));
if (headerOffset + headerSize > end) return headerOffset + headerSize - end;
// Integers, simple values and floats are complete with their header;
// their values are validated by the decoder, not here.
const carriesLength = majorType > Major.Negative && majorType < Major.Simple;
if (carriesLength && additionalInfo === Info.EightBytes && readUint32(bytes, headerOffset + 1) > 0x1fffff) {
return deferToDecoder(scan, headerOffset); // a length beyond 2^53
}
scan.position = headerOffset + headerSize;
if (!atIndefiniteLevel) scan.itemsPending--;
if (carriesLength) {
const argument = readArgumentValue(bytes, headerOffset + 1, additionalInfo);
if (majorType === Major.Bytes || majorType === Major.Text) {
scan.position += argument; // skip the payload
} else if (majorType === Major.Array) {
// Same limit checks, in the same order, as the decoder: the error does
// not depend on where chunk boundaries fall.
if (argument > limits.maxArrayLength) fail('array-limit', headerOffset - start, 'Array exceeds maxArrayLength');
scan.itemsPending += argument;
} else if (majorType === Major.Map) {
if (argument > limits.maxMapEntries) fail('map-limit', headerOffset - start, 'Map exceeds maxMapEntries');
scan.itemsPending += 2 * argument;
} else { // Major.Tag
scan.itemsPending += 1; // its content
}
}
}
// Every pending item, and every open item's break, needs at least one more byte.
if (scan.position - start + scan.itemsPending + scan.openIndefinite.length > maxItemBytes) {
fail('item-limit', 0, 'Item exceeds maxItemBytes');
}
}
return scan.position > end ? scan.position - end : 0;
}Two details keep errors identical however the input is chunked. The scanner checks array and map limits in the same order as the decoder, using the same containerLimits. And for any malformed header it calls deferToDecoder, which ends the item just after the bad header so the decoder reads it and reports its own error.
/** A malformed header: end the item just after it, so the decoder reads up to
* this point and reports the error itself. The error is then the same
* wherever chunk boundaries fall. */
function deferToDecoder(scan: ScanState, headerOffset: number): number {
scan.position = headerOffset + 1;
scan.itemsPending = 0;
scan.openIndefinite.length = 0;
return 0;
}Decoding in place, scanning near the end
Within a chunk the decoder calls the ordinary read. Only in the last SCAN_AHEAD_BYTES does it scan first. If a truncated error still escapes the decode, the scan settles whether the item really was cut off.
/** Decode items in place from the chunk. Only the last item can be cut off
* by the chunk's end; it then moves to the spanning path. */
function decodeInChunk(chunk: Uint8Array, offset: number, onValue: (value: Value) => void): void {
const buffer = binary(chunk);
while (offset < chunk.length) {
if (chunk.length - offset < SCAN_AHEAD_BYTES) {
resetScan(scan, offset);
let needed: number;
try {
needed = scanItem(chunk, offset, chunk.length, scan, maxItemBytes, limits);
} catch (error) {
throw atStreamOffset(error, streamOffset + offset);
}
if (needed > 0) {
beginSpanning(chunk, offset);
return;
}
}
let value: Value;
let next: number;
try {
[value, next] = read(buffer, offset, options);
} catch (error) {
if (!(error instanceof CborError && error.code === 'truncated')) throw atStreamOffset(error, streamOffset);
// Probably cut off by the chunk's end. The scan settles it: either more
// bytes are needed, or the item is complete (and decoding it reports
// its real error, or it decodes and we carry on after it).
beginSpanning(chunk, offset);
const resumeAt = continueSpanning(NO_BYTES, onValue);
if (assembly !== undefined) return;
offset = chunk.length + resumeAt;
continue;
}
if (next - offset > maxItemBytes) fail('item-limit', streamOffset + offset, 'Item exceeds maxItemBytes');
offset = next;
onValue(value);
}
}BENCHMARK.md explains the scan-ahead: exceptions had cost about 3.7 µs per chunk boundary, almost all of it stack-trace capture. With 1 KiB chunks, 100,000 rows took 55 ms before the change and 35 ms after.
The assembly buffer
An item that runs past the end of a chunk is copied into an assembly buffer, a new one for each spanning item, so values that borrow from it stay valid. Each later chunk feeds it in blocks of at least ASSEMBLY_BLOCK bytes until the scan reports the item complete. Then it is decoded once, and normal decoding resumes in the chunk just after the item's end.
function append(chunk: Uint8Array, start: number, end: number): void {
const needed = filled + end - start;
if (assembly === undefined || needed > assembly.length) {
const larger = new Uint8Array(Math.max(needed, 2 * (assembly?.length ?? 0), ASSEMBLY_BLOCK));
if (assembly !== undefined) larger.set(assembly.subarray(0, filled));
assembly = larger;
}
assembly.set(chunk.subarray(start, end), filled);
filled = needed;
}
/** Start assembling an item that runs past the end of the chunk. */
function beginSpanning(chunk: Uint8Array, start: number): void {
assembly = undefined;
filled = 0;
itemOffset = streamOffset + start;
resetScan(scan, 0);
append(chunk, start, chunk.length);
}
/** Feed the spanning item from `chunk`. Returns where in the chunk normal
* decoding resumes (negative if the item ended in bytes appended earlier),
* or chunk.length if the item is still incomplete. */
function continueSpanning(chunk: Uint8Array, onValue: (value: Value) => void): number {
let taken = 0;
for (;;) {
let needed: number;
let value: Value | undefined;
try {
needed = scanItem(assembly!, 0, filled, scan, maxItemBytes, limits);
if (needed === 0) value = readWhole(binary(assembly!.subarray(0, scan.position)), options);
} catch (error) {
throw atStreamOffset(error, itemOffset);
}
if (needed === 0) {
const itemEnd = scan.position;
const resumeAt = taken - (filled - itemEnd); // bytes past the item came from this chunk
assembly = undefined;
filled = 0;
onValue(value!);
return resumeAt;
}
if (taken === chunk.length) return chunk.length;
const block = Math.min(chunk.length - taken, Math.max(needed, ASSEMBLY_BLOCK));
append(chunk, taken, taken + block);
taken += block;
}
}The decoder's public surface is two methods. A decoder that has thrown stays failed, push after end() or from inside its own callback is a TypeError, and errors carry absolute stream offsets.
return {
push(chunk, onValue) {
if (failure !== undefined) throw failure;
if (ended) throw new TypeError('push() after end()');
if (busy) throw new TypeError('push() called from inside onValue');
binary(chunk); // validates the chunk type
busy = true;
try {
const start = assembly !== undefined ? continueSpanning(chunk, onValue) : 0;
if (assembly === undefined) decodeInChunk(chunk, start, onValue);
streamOffset += chunk.length;
} catch (error) {
failure = error;
throw error;
} finally {
busy = false;
}
},
end() {
if (failure !== undefined) throw failure;
ended = true;
if (assembly !== undefined) {
failure = new CborError('truncated', itemOffset, 'Stream ended inside a CBOR item');
throw failure;
}
},
get bufferedBytes() { return assembly === undefined ? 0 : filled; },
get offset() { return streamOffset; },
};Bounded buffering
maxItemBytes (default 16 MiB) caps one item's encoded size. For an item still arriving, the scanner checks it from headers, before the bytes arrive, so a short header claiming a 4 GB string can't make the decoder buffer it. The other decode limits (maxDepth, maxArrayLength, maxMapEntries and the allocation budget) apply to each item.
The Web Streams adapters
decodeStream is a TransformStream around one decoder. With batch: true it emits one array per input chunk instead of one value per step: each Web Streams step costs about 1 µs in Node, more than decoding a small value.
// Batch modes exist because each Web Streams step costs about 1 µs per chunk
// in Node, more than decoding or encoding a small value. Moving values as
// arrays pays that cost once per chunk instead of once per value.
/** Bytes in, decoded values out; with `batch: true`, arrays of values out.
* Decode errors error the stream. */
export function decodeStream(options?: DecodeStreamOptions): TransformStream<BufferSource, Value>;
export function decodeStream(options: BatchDecodeStreamOptions): TransformStream<BufferSource, Value[]>;
export function decodeStream(options: DecodeStreamOptions | BatchDecodeStreamOptions = {}): TransformStream<BufferSource, Value | Value[]> {
const decoder = createSequenceDecoder(options);
const strategies = [options.writableStrategy, options.readableStrategy as QueuingStrategy<Value | Value[]>] as const;
if (options.batch) {
return new TransformStream<BufferSource, Value[]>({
transform(chunk, controller) {
const values: Value[] = [];
decoder.push(asBytes(chunk), value => { values.push(value); });
if (values.length > 0) controller.enqueue(values);
},
flush() { decoder.end(); },
}, ...strategies);
}
let enqueue: (value: Value) => void;
return new TransformStream<BufferSource, Value>({
start(controller) { enqueue = value => controller.enqueue(value); },
transform(chunk) { decoder.push(asBytes(chunk), enqueue); },
flush() { decoder.end(); },
}, ...strategies);
}decodeSequence is an async generator over a ReadableStream or any iterable of chunks. Stopping early cancels the source.
/** Decode a CBOR sequence from a byte stream or any (async) iterable of byte
* chunks, such as fetch's response.body or a Node Readable. Stopping early
* (break, return or throw in for await) cancels the source. */
export async function* decodeSequence(source: ByteSource, options: SequenceDecodeOptions = {}): AsyncGenerator<Value, void, undefined> {
const decoder = createSequenceDecoder(options);
const decoded: Value[] = [];
const collect = (value: Value): void => { decoded.push(value); };
const iterator: AsyncIterator<BufferSource> | Iterator<BufferSource> = isReadableStream(source)
? readerIterator(source)
: Symbol.asyncIterator in source ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
let finished = false;
try {
for (;;) {
const step = await iterator.next();
if (step.done) break;
decoder.push(asBytes(step.value), collect);
for (let index = 0; index < decoded.length; index++) yield decoded[index];
decoded.length = 0;
}
finished = true;
decoder.end();
} finally {
if (!finished) await iterator.return?.();
}
}Encoding sequences
The encoder has two modes. With chunkBytes: 0 (the default) each value becomes its own owned chunk, for the lowest latency. With chunkBytes: N values are written straight into a growable chunk, which is emitted once it holds at least N bytes. An unsupported value throws and leaves no partial bytes behind.
export function createSequenceEncoder(options: SequenceEncodeOptions = {}): SequenceEncoder {
const chunkBytes = options.chunkBytes ?? 0;
if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 0) throw new RangeError('Invalid chunkBytes');
if (chunkBytes === 0) {
return { push: (value, onChunk) => onChunk(encode(value, options)), flush: () => {} };
}
// Each emitted chunk is a fresh buffer that is never written again. It starts
// at up to 64 KiB and grows as values arrive, so a large chunkBytes does not
// allocate its full size up front.
const initialBytes = Math.min(chunkBytes, 65536);
const writeValue = writerFor(profileOf(options));
let writer: Writer = createWriter(new Uint8Array(initialBytes), 0, true);
const emit = (onChunk: (chunk: Uint8Array) => void): void => {
const chunk = writer.bytes.subarray(0, writer.position);
writer = createWriter(new Uint8Array(initialBytes), 0, true);
onChunk(chunk);
};
return {
push(value, onChunk) {
const start = writer.position;
try {
writeValue(writer, value, 0);
} catch (error) {
writer.position = start; // an unsupported value leaves no partial bytes
throw error;
}
if (writer.position >= chunkBytes) emit(onChunk);
},
flush(onChunk) {
if (writer.position > 0) emit(onChunk);
},
};
}Measured
From BENCHMARK.md (npm run bench:stream): each variant in its own process, median of 7 runs, 100,000 object rows (6.4 MB) as a CBOR sequence. Fresh chunk buffers are sliced inside the timed region for every variant. cbor-x is compared through its Node-stream DecoderStream and EncoderStream; cborg has no streaming API.
| Variant | 64 KiB chunks | 1 KiB chunks |
|---|---|---|
| pure-cbor sequence decoder | 23.5 ms | 38.1 ms |
pure-cbor decodeStream({ batch: true }) | 25.3 ms | 46.9 ms |
pure-cbor decodeSequence | 33.3 ms | 48.8 ms |
pure-cbor decodeStream(), one value per step | 49.1 ms | 68.1 ms |
cbor-x DecoderStream | 37.0 ms | 91.5 ms |
| Variant | Time |
|---|---|
pure-cbor encodeStream({ batch: true }), batches of 1,000, chunkBytes: 0 | 19.5 ms |
pure-cbor sequence encoder, chunkBytes: 16384 | 21.7 ms |
pure-cbor sequence encoder, chunkBytes: 0 | 24.2 ms |
pure-cbor encodeStream(), chunkBytes: 0, one value per step | 125.8 ms |
cbor-x EncoderStream | 66.2 ms |
- The incremental core is faster than cbor-x's streams in every case: 1.6× with 64 KiB chunks, 2.4× with 1 KiB chunks, 1.4× for a single large item, and 2.7–3.1× when encoding.
- Batched
decodeStreamis within 8% of the core decoder at 64 KiB chunks, and batchedencodeStreamis 3.4× faster than cbor-x'sEncoderStream. - Web Streams with one value per step cost about 1 µs per value in Node: a do-nothing
TransformStreampassing 100,000 values took about 100 ms by itself. For many small values, use batch mode,decodeSequenceor the core. - A 7.8 MB item spanning 16 KiB chunks costs about 20–25% more than decoding it whole (one copy into the assembly buffer plus a header scan).
Part 5
Performance notes
The README says each performance choice was measured, and the reasons are commented in the code. This part collects them: what the trick is, why it exists, and the effect the docs record. All numbers are Node 22 on macOS arm64; browser and workerd performance are not yet measured.
Headline numbers
The benchmark suite runs each workload in its own Node process, because workloads sharing a process skewed each other's V8 type feedback by up to 2×. The chart shows the five public corpus workloads. Hover over or focus a bar for the underlying times.
On public data, pure-cbor is ahead in every corpus measurement
Decode (reused input) and encode (owned output), five public corpus workloads
- Decode
- Encode
Show the numbers as a table
| Corpus workload | Decode: pure-cbor | cbor-x | cborg | vs best | Encode: pure-cbor | cbor-x | cborg | vs best |
|---|---|---|---|---|---|---|---|---|
| cbor-x example4 | 19.4 µs | 22.4 µs | 40.4 µs | 1.16× | 16.7 µs | 17.3 µs | 50.0 µs | 1.04× |
| msgpack sample-large | 12.0 µs | 20.5 µs | 27.8 µs | 1.71× | 12.0 µs | 14.8 µs | 21.2 µs | 1.24× |
| Bluesky records 100 | 46.6 µs | 71.2 µs | 86.2 µs | 1.53× | 47.3 µs | 56.5 µs | 66.7 µs | 1.20× |
| Float mesh 1000 | 183.7 µs | 301.3 µs | 845.3 µs | 1.64× | 214.8 µs | 228.7 µs | 2306.8 µs | 1.06× |
| float[] 10000 | 34.0 µs | 51.7 µs | 454.3 µs | 1.52× | 74.3 µs | 111.5 µs | 1566.1 µs | 1.50× |
Where it is not ahead
BENCHMARK.md says to treat anything within about ±10% of 1.0 as level. Outside the corpus:
- Arrays of short strings, decoded: 0.92–0.97× cbor-x. The time goes on allocating many tiny strings, which every library pays.
- Long text from a reused buffer (ASCII 4096): about 0.9×. pure-cbor's
TextDecoderis strict and rejects invalid UTF-8; cbor-x's replaces it. With fresh input they are level. - Encoding 64-byte strings: cborg is 8% faster (0.92×). Mixed arrays and the nested config object are level within noise.
- COSE and WebAuthn: pure-cbor copies byte strings by default, while cbor-x returns views into the input. It matches cbor-x only with
binaryOwnership: 'borrow'. - cbor-x with its native addon, which npm installs on Node: it creates many strings in one C++ call, and still decodes arrays of very short strings about 1.4× faster. pure-cbor does the same trick in JavaScript, one
TextDecodercall per window of nearby strings, and is ahead of the addon on real text-heavy data (BENCHMARK.md has the numbers). - cbor-x records mode, a non-standard wire format, decodes 100 rows about 2.6× faster than pure-cbor by generating readers with
new Function. pure-cbor stays standard CBOR and avoids code generation.
The full tables, including fresh-input decoding, are at the end of this part; the streaming numbers are in Streaming.
On-heap and off-heap typed arrays
Most of the design follows from one property of V8 that the docs describe: a small, freshly allocated typed array lives on the JavaScript heap and is cheap, but a typed array over 64 bytes, or a small one whose .buffer is touched, needs a separate off-heap backing store. BENCHMARK.md puts that at about 0.5 µs. For small messages that costs more than the encoding or decoding itself.
So the library avoids touching .buffer on small arrays, and counts allocations:
- Owned encoding writes into a reused staging buffer and copies out exactly once: one output allocation and no sizing pass (encode, step 2).
- Small owned outputs (numbers, simple values) are allocated at their exact size and never touch
.buffer, so they stay on-heap. - The slab encoder exists for larger messages: outputs of 64 bytes or less are already cheap on-heap allocations, so a slab mainly saves the off-heap allocation above that size.
- Byte strings over 64 bytes from one decode share an arena (decode, step 9).
No DataView for scalars
A DataView is the usual way to read big-endian numbers, but constructing one on a fresh small buffer forces that buffer off-heap. The README measured the cost at about 900 ns per message, more than the encode or decode itself. pure-cbor reads and writes headers and integers byte by byte, and converts floats through a one-element scratch array:
// Float conversion scratch, used synchronously within one call (no user code
// runs in between), so it carries no state across operations. It replaces
// DataView, whose construction is expensive on fresh small buffers.
const float64 = new Float64Array(1);
const float64Bytes = new Uint8Array(float64.buffer);
const float32 = new Float32Array(1);
const float32Bytes = new Uint8Array(float32.buffer);
const float32Bits = new Uint32Array(float32.buffer);
// …
/** Big-endian binary64 at offset; caller has checked 8 readable bytes. */
export function readFloat64(bytes: Uint8Array, offset: number): number {
const target = float64Bytes;
if (LITTLE_ENDIAN) {
target[0] = bytes[offset + 7]; target[1] = bytes[offset + 6]; target[2] = bytes[offset + 5]; target[3] = bytes[offset + 4];
target[4] = bytes[offset + 3]; target[5] = bytes[offset + 2]; target[6] = bytes[offset + 1]; target[7] = bytes[offset];
} else {
target[0] = bytes[offset]; target[1] = bytes[offset + 1]; target[2] = bytes[offset + 2]; target[3] = bytes[offset + 3];
target[4] = bytes[offset + 4]; target[5] = bytes[offset + 5]; target[6] = bytes[offset + 6]; target[7] = bytes[offset + 7];
}
return float64[0];
}The effect shows most on fresh input, where every message is a new buffer. From BENCHMARK.md, decoding from a fresh buffer:
| Workload | pure-cbor | cbor-x | cborg | vs best other |
|---|---|---|---|---|
| uint small † | 34 ns | 455 ns | 426 ns | 12.60× |
| float64 † | 38 ns | 504 ns | 465 ns | 12.15× |
| ASCII 32 | 81 ns | 447 ns | 418 ns | 5.19× |
| object: row | 236 ns | 567 ns | 820 ns | 2.40× |
Floats in arrays are the exception, handled deliberately. An input over 64 bytes is already off-heap, so the array decoder builds one DataView, lazily, on the first float64 element, and shares it for the rest of the decode:
if (token === Token.Float64) {
readable(bytes, position, 8);
// DataView.getFloat64 is an intrinsic and the fastest path, but building
// a DataView over a small on-heap buffer is costly. Inputs over 64 bytes
// are already off-heap, so one view is shared by the whole decode.
if (state.floatView === undefined && bytes.length > 64) {
state.floatView = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
}
values[index] = state.floatView !== undefined
? state.floatView.getFloat64(position)
: NumberCodec.readFloat64(bytes, position);
position += 8;
continue;
}Encoding float64 uses an unrolled byte copy, because a loop measured slower:
// Unrolled: a byte loop here was ~1.6x slower in array benchmarks.
function writeFloat64(bytes: Uint8Array, offset: number, value: number): number {
float64[0] = value;
const source = float64Bytes;
bytes[offset] = 0xfb;
if (LITTLE_ENDIAN) {
bytes[offset + 1] = source[7]; bytes[offset + 2] = source[6]; bytes[offset + 3] = source[5]; bytes[offset + 4] = source[4];
bytes[offset + 5] = source[3]; bytes[offset + 6] = source[2]; bytes[offset + 7] = source[1]; bytes[offset + 8] = source[0];
} else {
bytes[offset + 1] = source[0]; bytes[offset + 2] = source[1]; bytes[offset + 3] = source[2]; bytes[offset + 4] = source[3];
bytes[offset + 5] = source[4]; bytes[offset + 6] = source[5]; bytes[offset + 7] = source[6]; bytes[offset + 8] = source[7];
}
return offset + 9;
}Shaping code for the inliner
Several functions are spelled out where a shared helper would read better, because V8 declined to inline the helper into a hot loop:
- Array and map loops keep the cursor in a local variable and write scalars inline. A shared helper measured 10–20% slower (README).
- The object decode loop stays inside
MapCodec.read. Moving it one call deeper made small-object decoding bimodal (principles, 6). - Number writing has separate
writeandwriteShortestfunctions, so the default stays small (principles, 2). - Text decoding keeps
readPayloadsmall and moves the native decoder intodecodeNative.
Wire constants are const enums for the same reason. The comment in header.ts records the alternative it replaced:
// Named wire constants. Const enums: the compiler substitutes each value at
// its use site, so hot loops compare against literals. (Imported `const`
// bindings measured ~15% slower in the array decoder.)Objects: enumeration, duplicates, keys
Allocation-free enumeration
Object keys are read with for…in, which goes through V8's enum cache with no allocations: about 3× faster than Object.keys plus Object.values (README). An own-property check is added only if Object.prototype has gained enumerable properties, so a polluted prototype never leaks keys.
/** Own enumerable string keys in Object.keys order; undefined values omitted.
*
* Enumeration: `for...in` reads properties through V8's enum cache with no
* array allocations, ~3x faster than Object.keys + Object.values. For plain
* objects it can only add inherited keys if Object.prototype itself has been
* given enumerable properties, so the own-property check runs only then. */
export function measureObject(object: ValueObject, upper: boolean, depth: number, measureValue: MeasureValue, shortestFloats: boolean): number {
const checkOwn = objectPrototypeHasEnumerableKeys();
let entryCount = 0;
let total = 0;
for (const key in object) {
if (checkOwn && !Object.hasOwn(object, key)) continue;
const value = object[key];
if (value === undefined) continue;
entryCount++;
total += (upper ? StringCodec.maxSize(key) : StringCodec.size(key)) + measureValue(value, upper, depth, shortestFloats);
}
total += argumentSize(entryCount);
if (!Number.isSafeInteger(total)) fail('invalid-length', 0, 'Encoded map size exceeds safe integer range');
return total;
}Counting instead of checking
Duplicate keys are detected by comparing the object's key count with the entry count once per map, about 4× cheaper than checking each key (README). The cost is precision: the duplicate-key error points at the map header, not the repeated key.
The decoded-key cache
A new key string has to be internalized by V8 each time it becomes a property name. A 1,024-slot cache returns the same string for repeated keys of up to 32 bytes (decode, step 7). Its comment records the effect:
/** Decoded map keys, reused across messages. A repeated key skips UTF-8
* decoding and, more importantly, V8 internalizing a brand-new string each
* time it becomes a property name: object construction measured ~2.3x faster
* with cached keys. Hits are confirmed byte for byte, so a hash collision only
* costs a miss. Only keys that decoded as valid UTF-8 are stored, so a hit is
* correct in every decode mode. Holds key text only, never values. */Together with the single-pass, back-patched map writer and small integers decoded inline, these are what BENCHMARK.md credits for the object results: one row decodes in 210 ns against cbor-x's 301 ns, and 100 rows in 21.1 µs against 29.1 µs (reused input).
Arrays and short text
Array decode preallocates the result, measured 1.6× faster than push; holey arrays had no measurable cost for consumers. Scalars are decoded inline with no per-element tuples.
Short ASCII text (up to 32 bytes) is checked 8 bytes at a time, and the tail is built by a single exact-arity fromCharCode call. Short non-ASCII text uses a strict JavaScript UTF-8 decoder that defers to TextDecoder on anything malformed. On reused input, ASCII 32 decodes in 53 ns against cbor-x's 119 ns.
const encoder = new TextEncoder();
// ignoreBOM: true preserves an initial U+FEFF as part of the CBOR string.
const strictDecoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
const lenientDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
const fromCharCode = String.fromCharCode;
// Below this many UTF-16 units, a JS loop beats TextEncoder.encodeInto's call overhead.
const SHORT_ENCODE = 64;
// Up to this many bytes, JS decoding beats TextDecoder's call overhead (~60 ns).
const SHORT_DECODE = 32;Long text is where this stops helping. At 4096 bytes both libraries hand the work to TextDecoder, and pure-cbor's strict decoder is about 0.9× cbor-x's replacing one on a reused buffer.
Byte strings and typed arrays
Typed arrays are copied with one bulk Uint8Array.set; overlapping source and destination views are supported. A 1 MiB Float64Array encodes in 51.9 µs against cbor-x's 119.6 µs, and decodes in 51.1 µs against 116.6 µs.
Byte strings are where the default copy policy costs the most. COSE and WebAuthn messages are mostly byte strings, and each copy over 64 bytes is a separate allocation. Version 0.6.0 added the per-decode arena and inline Map and byte-string encode paths. BENCHMARK.md measured the change in one process against 0.5.0:
| 0.5.0 | 0.6.0 | |
|---|---|---|
WebAuthn, 15 attestations, decode (default copy) | 35–47 µs | 18–21 µs |
— with copy-separate (0.5.0's behaviour) | — | 35–47 µs |
— with borrow | 8–11 µs | 8–11 µs |
| COSE_Key encode (cbor-x: 1,114 ns) | 1,241 ns | 1,029 ns |
Sig_structure encode (cbor-x: 1,151 ns) | 628 ns | 430 ns |
Borrow mode (binaryOwnership: 'borrow') returns views into the input, as cbor-x does by default. It is the fastest, and safe while the input stays unchanged, which is the normal case when verifying a message.
Streams
- Scan ahead near chunk ends. An exception at every chunk boundary cost about 3.7 µs, mostly stack-trace capture. Checking the boundary with the scanner first took 1 KiB chunks from 55 ms to 35 ms per 100,000 rows (streaming).
- Batch mode. Each Web Streams step costs about 1 µs in Node. Moving values as one array per chunk makes batched
decodeStreamwithin 8% of the core decoder. - Lazy sources. Enqueuing many items into a
ReadableStreamup front made Node's stream queue quadratic: 100,000 items took 2.7 s to read back. The README advises building sources that pull lazily, andencodeSequencedoes.
The full tables
These are BENCHMARK.md's main tables, rendered unchanged. They were measured on pure-cbor 0.5.0 (0.6.0 changed only byte-string copying and Map/byte-string encoding), Node v22.19.0 on macOS arm64, with the machine otherwise idle. cbor-x runs as pure JavaScript in standard CBOR mode; cborg uses its defaults, which sort map keys and write floats at their smallest exact width, extra work pure-cbor and cbor-x don't do. Each workload runs in its own process, median of 5 × 80 ms rounds.
Read with the noise in mind
A run is one sample. Across repeated runs, workloads near 1.0× moved by about ±10%: for example, mixed[] 128 encode ranged from 0.85× to 1.16× against cbor-x. Treat anything within about ±10% of 1.0 as level. Ratios below 1.0 are marked in orange.
Encode (owned output)
| Workload | pure-cbor | cbor-x | cborg | vs best other |
|---|---|---|---|---|
| uint small † | 25 ns | 109 ns | 80 ns | 3.26× |
| mixed integers | 29 ns | 120 ns | 94 ns | 3.29× |
| timestamp † | 30 ns | 114 ns | 135 ns | 3.84× |
| float64 † | 26 ns | 113 ns | 252 ns | 4.28× |
| boolean/null † | 19 ns | 116 ns | 84 ns | 4.54× |
| ASCII 8 | 55 ns | 137 ns | 106 ns | 1.92× |
| ASCII 32 | 114 ns | 179 ns | 152 ns | 1.34× |
| ASCII 64 | 424 ns | 448 ns | 388 ns | 0.92× |
| Unicode 32 | 391 ns | 442 ns | 456 ns | 1.13× |
| ASCII 4096 | 660 ns | 913 ns | 1314 ns | 1.38× |
| number[] 128 | 556 ns | 899 ns | 1418 ns | 1.61× |
| string[] 128 † | 2388 ns | 2715 ns | 3487 ns | 1.14× |
| mixed[] 128 | 1050 ns | 1201 ns | 1636 ns | 1.14× |
| number[] 10000 | 43.9 µs | 55.2 µs | 121.2 µs | 1.26× |
| Float64Array 1 KiB | 392 ns | 844 ns | – | 2.15× |
| Float64Array 1 MiB | 51.9 µs | 119.6 µs | – | 2.30× |
| object: row | 208 ns | 291 ns | 497 ns | 1.40× |
| object: 100 rows | 18.2 µs | 18.9 µs | 43.8 µs | 1.04× |
| object: nested config | 1453 ns | 1269 ns | 2448 ns | 0.87× |
| corpus: cbor-x example4 | 16.7 µs | 17.3 µs | 50.0 µs | 1.04× |
| corpus: msgpack sample-large | 12.0 µs | 14.8 µs | 21.2 µs | 1.24× |
| corpus: bluesky records 100 | 47.3 µs | 56.5 µs | 66.7 µs | 1.20× |
| corpus: float mesh 1000 | 214.8 µs | 228.7 µs | 2306.8 µs | 1.06× |
| corpus: float[] 10000 | 74.3 µs | 111.5 µs | 1566.1 µs | 1.50× |
Decode (reused input)
| Workload | pure-cbor | cbor-x | cborg | vs best other |
|---|---|---|---|---|
| uint small † | 10 ns | 22 ns | 73 ns | 2.14× |
| mixed integers | 16 ns | 24 ns | 157 ns | 1.50× |
| timestamp † | 15 ns | 24 ns | 104 ns | 1.59× |
| float64 † | 15 ns | 24 ns | 114 ns | 1.58× |
| boolean/null † | 13 ns | 24 ns | 80 ns | 1.88× |
| ASCII 8 | 24 ns | 35 ns | 137 ns | 1.49× |
| ASCII 32 | 53 ns | 119 ns | 137 ns | 2.23× |
| ASCII 64 | 75 ns | 223 ns | 159 ns | 2.10× |
| Unicode 32 | 247 ns | 245 ns | 329 ns | 0.99× |
| ASCII 4096 | 366 ns | 343 ns | 391 ns | 0.94× |
| number[] 128 | 451 ns | 566 ns | 1761 ns | 1.25× |
| string[] 128 † | 2316 ns | 2187 ns | 5191 ns | 0.94× |
| mixed[] 128 | 951 ns | 904 ns | 1840 ns | 0.95× |
| number[] 10000 | 45.9 µs | 47.3 µs | 145.0 µs | 1.03× |
| Float64Array 1 KiB | 410 ns | 735 ns | – | 1.79× |
| Float64Array 1 MiB | 51.1 µs | 116.6 µs | – | 2.28× |
| object: row | 210 ns | 301 ns | 614 ns | 1.44× |
| object: 100 rows | 21.1 µs | 29.1 µs | 50.5 µs | 1.38× |
| object: nested config | 1259 ns | 1309 ns | 3313 ns | 1.04× |
| corpus: cbor-x example4 | 19.4 µs | 22.4 µs | 40.4 µs | 1.16× |
| corpus: msgpack sample-large | 12.0 µs | 20.5 µs | 27.8 µs | 1.71× |
| corpus: bluesky records 100 | 46.6 µs | 71.2 µs | 86.2 µs | 1.53× |
| corpus: float mesh 1000 | 183.7 µs | 301.3 µs | 845.3 µs | 1.64× |
| corpus: float[] 10000 | 34.0 µs | 51.7 µs | 454.3 µs | 1.52× |
Decode (fresh input)
| Workload | pure-cbor | cbor-x | cborg | vs best other |
|---|---|---|---|---|
| uint small † | 34 ns | 455 ns | 426 ns | 12.60× |
| mixed integers | 45 ns | 448 ns | 561 ns | 9.92× |
| timestamp † | 40 ns | 501 ns | 478 ns | 12.03× |
| float64 † | 38 ns | 504 ns | 465 ns | 12.15× |
| boolean/null † | 36 ns | 401 ns | 485 ns | 11.10× |
| ASCII 8 | 49 ns | 453 ns | 487 ns | 9.29× |
| ASCII 32 | 81 ns | 447 ns | 418 ns | 5.19× |
| ASCII 64 | 456 ns | 530 ns | 445 ns | 0.98× |
| Unicode 32 | 503 ns | 550 ns | 689 ns | 1.09× |
| ASCII 4096 | 722 ns | 822 ns | 743 ns | 1.03× |
| number[] 128 | 685 ns | 904 ns | 1948 ns | 1.32× |
| string[] 128 † | 2499 ns | 2422 ns | 5487 ns | 0.97× |
| mixed[] 128 | 1131 ns | 1145 ns | 2009 ns | 1.01× |
| number[] 10000 | 46.8 µs | 48.4 µs | 143.8 µs | 1.03× |
| Float64Array 1 KiB | 806 ns | 1140 ns | – | 1.41× |
| object: row | 236 ns | 567 ns | 820 ns | 2.40× |
| object: 100 rows | 21.3 µs | 29.8 µs | 51.5 µs | 1.40× |
| object: nested config | 1475 ns | 1536 ns | 3028 ns | 1.04× |
| corpus: cbor-x example4 | 19.4 µs | 23.2 µs | 41.1 µs | 1.19× |
| corpus: msgpack sample-large | 12.4 µs | 21.0 µs | 28.4 µs | 1.70× |
† In the full run these five workloads hit system noise (float64 decode took 34 ns there, against 15 ns in 0.4.0 and in five repeats), so their rows are the median of three further fresh-process runs.
Real-world flows: WebAuthn, COSE, CWT, mdoc
Before timing, every library must produce the same result as pure-cbor, and pure-cbor is checked against the specs. These were measured on 0.5.0; see the 0.6.0 comparison above for the default copy mode since then.
| Flow | pure-cbor | pure-cbor (borrow) | cbor-x | cborg | tiny-cbor | cbor (node-cbor) | cbor2 |
|---|---|---|---|---|---|---|---|
| WebAuthn: parse 15 attestations, extract each COSE key | 21.7 µs | 7.6 µs | 7.9 µs | 24.4 µs | 90.8 µs | 153.9 µs | 75.0 µs |
COSE_Sign1: decode + build Sig_structure (7 messages) | 11.7 µs | 5.5 µs | 6.3 µs | 8.2 µs | 39.2 µs | 57.9 µs | 32.5 µs |
| CWT: token + claims (RFC 8392 A.3, A.4) | 1.43 µs | 1.00 µs | 0.95 µs | 2.08 µs | 8.5 µs | 13.4 µs | 7.2 µs |
| mdoc: device response + items + MSO | 8.5 µs | 6.0 µs | 6.5 µs | 14.2 µs | 69.0 µs | 59.9 µs | 43.9 µs |
| COSE_Key: encode | 692 ns | 686 ns | 474 ns | 862 ns | 6.3 µs | 3.4 µs | 9.7 µs |
| Flow | pure-cbor (default) | pure-cbor (borrow) |
|---|---|---|
| WebAuthn | 0.37× | 1.04× |
| COSE_Sign1 | 0.54× | 1.15× |
| CWT | 0.66× | 0.95× |
| mdoc | 0.76× | 1.07× |
| COSE_Key encode | 0.69× | 0.69× |
The libraries WebAuthn and COSE packages actually use (tiny-cbor, node-cbor, cbor2) are 5–20× slower than pure-cbor in every flow.
Where cbor-x is level or ahead, and why
- Arrays of 3–7 character strings, decoded (0.92–0.97×). The time is dominated by allocating many tiny strings, which every library pays.
- Long text decoded from a reused buffer (ASCII 4096, about 0.9×). pure-cbor's
TextDecoderis strict; cbor-x's silently replaces invalid UTF-8. With fresh input they are level. - Mixed and tiny-object encoding (
mixed[], nested config): level within noise. - Encoding 64-byte strings: cborg is 8% faster (0.92×). At that size every library pays one off-heap allocation for the output.
- cbor-x records mode is not in the tables: it is a non-standard wire format both ends must speak. Measured separately, it decodes 100 rows in about 8.6 µs, 2.6× faster than pure-cbor, and halves the bytes, by generating object readers with
new Function.
Wire size
pure-cbor writes preferred (smallest) map headers; cbor-x's standard encoder always writes a 3-byte map header unless variableMapSize: true. One object row is 57 bytes against 59; 100 rows are 5,868 against 6,068. cborg writes smaller floats, so it produces the smallest output for float-heavy data.
Reproduce
npm install --no-save --package-lock=false cbor-x cborg
BENCH_MS=80 BENCH_ROUNDS=5 npm run bench:isolatedPart 6
How we know it's correct
Speed is only worth having on top of correct output. The test suite checks pure-cbor against the RFC's own examples, against the published vectors of the formats that use CBOR for security, and against other libraries, and it feeds it hostile input on purpose.
One error type, one contract
Every validation failure is a CborError with a code and a byte offset. The hostile-input tests rely on this contract: malformed input may only produce a value or a CborError, never a RangeError from a blown stack or an out-of-bounds read.
export type ErrorCode =
| 'truncated' | 'capacity' | 'invalid-offset' | 'invalid-header'
| 'invalid-length' | 'invalid-utf8' | 'integer-overflow'
| 'array-limit' | 'map-limit' | 'depth-limit' | 'item-limit' | 'duplicate-key'
| 'unsupported-type' | 'unsupported-tag' | 'invalid-tag-content' | 'trailing-data' | 'invalid-buffer';
/** Error construction is cold-path only; no per-byte Result allocations. */
export class CborError extends Error {
constructor(readonly code: ErrorCode, readonly offset: number, message: string) {
super(message);
this.name = 'CborError';
}
}
export type Result<T> =
| { readonly ok: true; readonly value: T }
| { readonly ok: false; readonly error: CborError };
export function fail(code: ErrorCode, offset: number, message: string): never {
throw new CborError(code, offset, message);
}tryDecode turns that into a discriminated result. It catches library validation errors only, not arbitrary programmer or runtime errors:
export function tryDecode(bytes: Uint8Array, options?: DecodeOptions): Result<Value> {
try {
return { ok: true, value: decode(bytes, options) };
} catch (error) {
if (error instanceof CborError) return { ok: false, error };
throw error;
}
}RFC 8949 Appendix A
Every example in RFC 8949 Appendix A decodes. Every example JavaScript can represent exactly also encodes back to the same bytes. (Integral floats such as 1.0 are JavaScript integers, so they encode as integers.) Further golden vectors cover integer and float widths, text and UTF-8 header boundaries, and non-preferred argument widths, which are accepted when decoding.
Real-world vectors
The vectors in test/vectors are public, openly licensed examples from the specifications and projects where CBOR carries security-sensitive data:
| Format | Source | What is checked |
|---|---|---|
| COSE | The COSE working group's examples (RFC 8152/9052) | All 63 example messages decode and re-encode byte for byte, and 31 rebuilt Sig_structure/MAC_structures match the signed bytes exactly. |
| CWT | RFC 8392 | The claims decode as expected from the signed and MACed tokens. |
| WebAuthn | W3C Web Authentication Level 3 test vectors | All 15 attestations parse, with the correct COSE keys (ES256/384/512, RS256, Ed25519, Ed448). Truncated and padded authenticator data are detected. |
| mdoc | ISO/IEC 18013-5 Annex D (mobile driving licence) | The device response decodes, including embedded CBOR (tag 24), and every Annex D message re-encodes byte for byte when date tags are kept as written. |
"Kept as written" uses a custom tag decoder, a feature that exists for exactly this: re-encoding signed data byte for byte.
// Keep tags exactly as written (e.g. to re-encode signed data byte for byte):
decode(bytes, { tags: { 0: content => tagged(0, content) } });Differential and round-trip tests
- Interoperability. 2,000 random trees are checked both ways against cbor-x. The public corpus is checked both ways against cbor-x and cborg, including cborg's half-precision floats and sorted keys. Dates, bigints,
Mapandundefinedare checked against cbor-x in both directions, and the stream encoder and decoder against cbor-x'sEncoderStreamandDecoderStream. - Deterministic encoding. The RFC 8949 §4.2.1 key order is reproduced regardless of insertion order, and deterministic output equals cborg's canonical output byte for byte on the public corpus.
- Round trips. 2,000 seeded random nested trees go through owned, prepared and slab encoding; 20,000 seeded scalar round trips; the public and generated corpus. Random trees with every value kind (bigint,
Date,Mapwith byte-string keys,Tagged, simple values) round-trip in all three encode modes, andencodedSizeagrees with the output. - Text. 20,000 short-text cases are checked against
TextDecoderin strict and replace modes, since the JavaScript fast path must agree with the native decoder exactly. - Inline fast paths for
Mapand byte strings are checked against the general paths, and float arrays decode identically through the byte path and the DataView path.
The comparison libraries are optional. Install them to run the differential tests:
npm install --no-save --package-lock=false cbor-x cborg @levischuck/tiny-cbor cbor cbor2 cbor-js msgpackr @msgpack/msgpack
npm testStreaming under every chunking
- Every split point of a mixed sequence, every chunk size from 1 to 64 bytes, and 200 random chunkings decode to the same values.
- A linear-time check: 4× the data takes about 4× the time, so quadratic rescanning would fail.
- Malformed input gives the same error code under every chunking.
- Limits, absolute offsets, cancellation, lazy pulling and both batch modes; borrowed values stay valid as later chunks arrive.
Hostile input
- 30,000 random and container-heavy malformed inputs, which may only produce values or
CborErrors. - Depth bombs and nested allocation bombs: limits are checked before allocating.
- Every truncation point fails without reading outside the supplied view.
- Prototype pollution in both directions: a
__proto__key decodes as an own data property, and a pollutedObject.prototypenever leaks keys into encoded objects. - Capacity errors never partially write the destination, for nested values too, and an exotic input that re-enters
encode()still gets correct output.
Where the tests live
| File | Covers |
|---|---|
| codec.test.mjs | Golden integer, float and text vectors; malformed UTF-8; typed arrays and byte order; truncation; capacity; seeded property checks |
| array-and-pool.test.mjs | Arrays, simple values, allocation limits, the slab encoder |
| objects.test.mjs | Maps, nesting, __proto__, duplicates, depth limits, the key cache, cbor-x interop on random trees |
| coverage.test.mjs | RFC 8949 Appendix A, tags, bigints, dates, indefinite lengths, shortest floats, deterministic encoding |
| stream.test.mjs | Sequences and Web Streams under every chunking |
| vectors.test.mjs | COSE, CWT, WebAuthn and mdoc vectors |
| corpus.test.mjs | The public and generated corpus, both ways with cbor-x and cborg |
| interoperability.test.mjs | Bidirectional cbor-x interoperability (optional reference package) |
| foreign.test.mjs | Rejection vectors from other decoders: RFC 8949 Appendix F, ciborium, cbor2 and Jackson |
| strict.test.mjs | Strict decoding: mapKeys, 'tagged' and 'reject' tag entries, tag 55799, and STRICT_DECODE |
| security.test.mjs | Equal object keys under last-wins; strings split into thousands of chunks; chunked text and split characters |
| portable/suite.mjs | The portable conformance suite, with no Node APIs: Appendix A, every value kind, errors, ownership, sequences and Web Streams. Run in Node, Deno, Bun, workerd, and Chromium, Firefox and WebKit on the page and in web workers |
Every runtime, every push
CI runs the whole suite on Node 22, 24 and latest and on Deno, and the portable suite on Bun, workerd, and Chromium, Firefox and WebKit, both on the page and in a web worker. The benchmarks were taken on Node 22 only; performance elsewhere is not yet measured.
Part 7
Module map
Twenty-three files, one job each. The dependency graph is acyclic: container codecs receive the item dispatcher as a parameter instead of importing it, and no codec depends on the allocation policy.
Layers
Each module imports only from its own layer or the layers below. The modules highlighted in blue are the ones the tour spends most time in. Select a module to open its source.
Scroll sideways to see the whole diagram.
sequence.ts uses allocation.ts's encode, and map.ts uses keys.ts). Nothing below codec.ts imports it: array.ts and map.ts receive readValue and writeValue as arguments.That last point is visible in the signatures. The dispatcher types are declared next to the state they act on:
/** The item dispatcher, passed to container codecs so they need not import it. */
export type ReadValue = (state: DecodeState) => Value;/** Dispatchers passed to container codecs so they need not import codec.ts.
* depth is the nesting level of the value's container. */
export type WriteValue = (writer: Writer, value: Value, depth: number) => void;
export type MeasureValue = (value: Value, upper: boolean, depth: number, shortestFloats: boolean) => number;Every file
| Module | Role | In the tour |
|---|---|---|
| Public API | ||
| index.ts | The public API: re-exports, plus write, encodeInto, encodedSize, maxEncodedSize, decode and tryDecode. | Decode |
| Policies and adapters | ||
| allocation.ts | Allocation policies: owned encode() through a staging buffer copied out once, and the opt-in slab encoder. | Encode |
| sequence.ts | CBOR sequences: the resumable boundary scanner, the incremental decoder and the sequence encoder. | Streaming |
| stream.ts | Web Streams and async-iterator adapters over sequence.ts. | Streaming |
| Dispatch | ||
| codec.ts | Major-type dispatch. Writing: writeValue, writeRareValue, optionsWriter, writerFor, writeBytes. Reading: readItem, readValue, readTag. Sizing: measure. | Encode, Decode |
| Containers | ||
| array.ts | Arrays: hot loops with a local cursor and inline scalars, in both directions; nested items through the dispatcher. | Encode, Decode |
| map.ts | Plain objects and Map: enumeration, key writing, decode modes, duplicate detection, sorted entries for deterministic encoding, and __proto__ safety. | Encode, Decode |
| keys.ts | The decoded-key cache: 1,024 slots for keys of up to 32 bytes, confirmed byte for byte. | Decode |
| Values | ||
| number.ts | Integers and floats: preferred widths, shortest floats, and float conversion through a scratch array instead of a DataView. | Encode, Performance |
| string.ts | UTF-8: sizing, single-pass writes with a back-patched header, short ASCII and short UTF-8 decode paths, strict TextDecoder fallback. | Encode, Decode |
| simple.ts | Major type 7: false, true, null, undefined, the SimpleValue variant, and float dispatch. | Decode |
| tag.ts | The Tagged variant, dates, and built-in and custom tag decoding. | Principles, Decode |
| bignum.ts | bigint to and from 64-bit integers and bignums (tags 2 and 3). | |
| indefinite.ts | Indefinite-length byte and text strings. Decode only; the library always encodes definite lengths. | |
| typed-array.ts | RFC 8746 typed-array tags, payload ownership (copy or borrow) and byte order; byte strings. | Decode |
| scalar.ts | The shared scalar writer used by the dispatcher. | Encode |
| arena.ts | The per-decode arena for byte strings over 64 bytes. | Decode |
| Foundation | ||
| header.ts | The wire vocabulary: Major, MajorBits, Info and Token const enums, plus argument read and write. | Principles |
| binary.ts | The Binary view descriptor, bounds checks, the typed-array kind lookup and the endianness constant. | Decode |
| writer.ts | The Writer cursor record (growable or fixed) and EncodeProfile. | Encode |
| state.ts | DecodeState, the explicit per-decode state record, and its limits. | Decode |
| error.ts | Error codes, CborError (the only class) and Result. | Correctness |
| types.ts | The value and option types. | Principles |
Get started
npm install pure-cborimport { encode, decode } from 'pure-cbor';
const bytes = encode({ id: 7, name: 'Ada', tags: ['x', 'y'], active: true, manager: null });
console.log(decode(bytes)); // { id: 7, name: 'Ada', tags: ['x', 'y'], active: true, manager: null }
console.log(decode(encode(new Float64Array([1.25, -0, Math.PI])))); // Float64Arrayencode returns an exactly sized Uint8Array that you own. decode reads exactly one item and rejects trailing bytes. It needs only ES2023 and TextEncoder/TextDecoder, and is tested on Node 22, 24 and 26, Deno, Bun, workerd, and Chromium, Firefox and WebKit, both on the page and in web workers.