Skip to content

knotkit/sorted-block

Packs byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans

import {
function encodeKeyTuple(parts: readonly KeyTuplePart[]): Uint8Array

Encode a composite key so that compareBytes orders encoded tuples lexicographically by part, each part in its own direction: the first part decides, the second breaks ties, and a tuple sorts before every longer tuple it is a prefix of.

Each part is a one-byte tag naming its kind and direction, then its payload: the fixed-width scalar encoding, or the escaped encoding for bytes and string. A descending part writes the bitwise complement of its ascending payload; because every payload is self-delimiting, that reverses its order exactly, including between byte strings of different lengths. Two tuples compare meaningfully only part by part over the same kinds, as in one index schema.

Runs in O(total payload bytes) and allocates the result once.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when parts is not an array, a part's kind or direction is unknown, or its value is outside the kind's domain, as the matching encode*Key would report.

encodeKeyTuple
} from 'knotkit/key-encoding'
import {
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
} from 'knotkit/sorted-block'
const
const encoder: TextEncoder
encoder
= new
var TextEncoder: new () => TextEncoder

The TextEncoder interface takes a stream of code points as input and emits a stream of UTF-8 bytes.

MDN Reference

An implementation of the WHATWG Encoding Standard TextEncoder API. All instances of TextEncoder only support UTF-8 encoding.

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');

TextEncoder
()
const
const key: (user: string, version: bigint) => Uint8Array
key
= (
user: string
user
: string,
version: bigint
version
: bigint):
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
=>
function encodeKeyTuple(parts: readonly KeyTuplePart[]): Uint8Array

Encode a composite key so that compareBytes orders encoded tuples lexicographically by part, each part in its own direction: the first part decides, the second breaks ties, and a tuple sorts before every longer tuple it is a prefix of.

Each part is a one-byte tag naming its kind and direction, then its payload: the fixed-width scalar encoding, or the escaped encoding for bytes and string. A descending part writes the bitwise complement of its ascending payload; because every payload is self-delimiting, that reverses its order exactly, including between byte strings of different lengths. Two tuples compare meaningfully only part by part over the same kinds, as in one index schema.

Runs in O(total payload bytes) and allocates the result once.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when parts is not an array, a part's kind or direction is unknown, or its value is outside the kind's domain, as the matching encode*Key would report.

encodeKeyTuple
([
{
kind: "string"
kind
: 'string',
value: string
value
:
user: string
user
},
{
kind: "uint64"
kind
: 'uint64',
value: bigint
value
:
version: bigint
version
,
direction?: KeyDirection | undefined
direction
: 'descending' },
])
// Entries must already ascend under compareBytes: here, each user's newest version first.
const
const block: SortedBlock
block
=
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
(
[
[
const key: (user: string, version: bigint) => Uint8Array
key
('ada', 2n),
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
('engineer')],
[
const key: (user: string, version: bigint) => Uint8Array
key
('ada', 1n),
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
('student')],
[
const key: (user: string, version: bigint) => Uint8Array
key
('grace', 1n),
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
('admiral')],
],
{
RestartPointSortedBlockOptions.restartInterval?: number | undefined

Entries between two restart points, a positive safe integer; 16 when omitted. A restart point stores its key whole, so a smaller interval spends more bytes on keys and on the restart table and scans fewer entries per read.

restartInterval
: 16 },
)
const block: SortedBlock
block
.
SortedBlock.size: number

Number of entries.

size
// 3
const block: SortedBlock
block
.
SortedBlock.get: (key: Uint8Array) => Uint8Array | undefined

A copy of the value stored under key, or undefined when the block holds no such key.

@throws ― {SortedBlockInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

get
(
const key: (user: string, version: bigint) => Uint8Array
key
('ada', 1n)) // the bytes of 'student'
const block: SortedBlock
block
.
SortedBlock.has: (key: Uint8Array) => boolean

Whether the block holds key.

@throws ― {SortedBlockInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

has
(
const key: (user: string, version: bigint) => Uint8Array
key
('ada', 3n)) // false
// A user's key prefix sorts before every one of its versions, so the ceiling is the newest one.
const
const ada: Uint8Array<ArrayBufferLike>
ada
=
function encodeKeyTuple(parts: readonly KeyTuplePart[]): Uint8Array

Encode a composite key so that compareBytes orders encoded tuples lexicographically by part, each part in its own direction: the first part decides, the second breaks ties, and a tuple sorts before every longer tuple it is a prefix of.

Each part is a one-byte tag naming its kind and direction, then its payload: the fixed-width scalar encoding, or the escaped encoding for bytes and string. A descending part writes the bitwise complement of its ascending payload; because every payload is self-delimiting, that reverses its order exactly, including between byte strings of different lengths. Two tuples compare meaningfully only part by part over the same kinds, as in one index schema.

Runs in O(total payload bytes) and allocates the result once.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when parts is not an array, a part's kind or direction is unknown, or its value is outside the kind's domain, as the matching encode*Key would report.

encodeKeyTuple
([{
kind: "string"
kind
: 'string',
value: string
value
: 'ada' }])
const [,
const latest: Uint8Array<ArrayBufferLike> | undefined
latest
] =
const block: SortedBlock
block
.
SortedBlock.ceiling: (key: Uint8Array) => SortedBlockEntry | undefined

A copy of the smallest entry whose key is at or above key under compareBytes, or undefined when every key sorts below it.

@throws ― {SortedBlockInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

ceiling
(
const ada: Uint8Array<ArrayBufferLike>
ada
) ?? []
new
var TextDecoder: new (label?: string, options?: TextDecoderOptions) => TextDecoder

The TextDecoder interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, KOI8-R, GBK, etc.

MDN Reference

An implementation of the WHATWG Encoding Standard TextDecoder API. Supports every encoding label the standard defines, except the labels of the replacement encoding.

const decoder = new TextDecoder();
const text = decoder.decode(new Uint8Array([104, 105])); // "hi"

TextDecoder
().
TextDecoder.decode(input?: AllowSharedBufferSource, options?: TextDecodeOptions): string

The TextDecoder.decode() method returns a string containing text decoded from the buffer passed as a parameter.

MDN Reference

decode
(
const latest: Uint8Array<ArrayBufferLike> | undefined
latest
) // 'engineer'
// Every entry from user 'ada' up to, not including, user 'grace'.
const
const grace: Uint8Array<ArrayBufferLike>
grace
=
function encodeKeyTuple(parts: readonly KeyTuplePart[]): Uint8Array

Encode a composite key so that compareBytes orders encoded tuples lexicographically by part, each part in its own direction: the first part decides, the second breaks ties, and a tuple sorts before every longer tuple it is a prefix of.

Each part is a one-byte tag naming its kind and direction, then its payload: the fixed-width scalar encoding, or the escaped encoding for bytes and string. A descending part writes the bitwise complement of its ascending payload; because every payload is self-delimiting, that reverses its order exactly, including between byte strings of different lengths. Two tuples compare meaningfully only part by part over the same kinds, as in one index schema.

Runs in O(total payload bytes) and allocates the result once.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when parts is not an array, a part's kind or direction is unknown, or its value is outside the kind's domain, as the matching encode*Key would report.

encodeKeyTuple
([{
kind: "string"
kind
: 'string',
value: string
value
: 'grace' }])
const
const versions: number
versions
= [...
const block: SortedBlock
block
.
SortedBlock.entries: (...bounds: [] | [start: Uint8Array] | [start: Uint8Array, end: Uint8Array]) => IterableIterator<SortedBlockEntry>

Walk entries in ascending key order: every entry, the open range [start, +∞), or the half-open range [start, end). Bounds are checked when the call is made, not on the first step.

@throws ― {SortedBlockInvalidInputError} With INVALID_KEY when a bound is not a Uint8Array, or INVALID_RANGE when end sorts before start.

entries
(
const ada: Uint8Array<ArrayBufferLike>
ada
,
const grace: Uint8Array<ArrayBufferLike>
grace
)].
Array<SortedBlockEntry>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
// 2
sorted-block.ts
import {
function compareBytes(left: Uint8Array, right: Uint8Array): -1 | 0 | 1

Compare two byte strings in unsigned lexicographic order, the order an encoded key sorts in.

A proper prefix sorts before every longer string that extends it. The result is -1, 0, or 1, so the function is an Order<Uint8Array> for knotkit/heap, knotkit/ordered-map, knotkit/sorted-merge, or Array.prototype.sort.

Runs in O(min(left.byteLength, right.byteLength)) and does not validate its arguments, because it sits on the hot path of every comparison-based structure; pass Uint8Array values.

compareBytes
} from 'knotkit/key-encoding'
import {
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
, type
type SortedBlockEntry = readonly [key: Uint8Array<ArrayBufferLike>, value: Uint8Array<ArrayBufferLike>]

One key-value pair of a block. Keys are compared by compareBytes from knotkit/key-encoding.

SortedBlockEntry
} from 'knotkit/sorted-block'
import {
function mergeSorted<A>(order: Order<A>, sources: Iterable<Iterable<A>>): Generator<A, void, unknown>

Lazily merge a finite collection of independently iterable sorted sources under the same total order. Keeps duplicates. Equal items retain their order within each source, with earlier sources winning ties. Supply a stable order and keep compared values unchanged while the merge is active.

The first advance calls next() once on each source. Each subsequent advance pulls only from the source of the last emitted value. With k sources, setup takes O(k) time and space, and each output after setup takes O(log(k + 1)) time, excluding input reads and comparator cost. Individual sources may be infinite.

On early return or failure, calls return() once on each opened, unfinished iterator that exposes it. Errors from the order and input iterators propagate. A cleanup error surfaces if the merge was otherwise returning normally. When several iterators fail during cleanup, the first error surfaces after all are tried.

mergeSorted
} from 'knotkit/sorted-merge'
const
const key: Uint8Array<ArrayBuffer>
key
=
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(1)
const
const newest: SortedBlock
newest
=
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
([[
const key: Uint8Array<ArrayBuffer>
key
,
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(20)]])
const
const oldest: SortedBlock
oldest
=
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
([[
const key: Uint8Array<ArrayBuffer>
key
,
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(10)]])
function*
function firstPerKey(entries: Iterable<SortedBlockEntry>): Generator<SortedBlockEntry, void, unknown>
firstPerKey
(
entries: Iterable<SortedBlockEntry>
entries
:
interface Iterable<T, TReturn = any, TNext = any>
Iterable
<
type SortedBlockEntry = readonly [key: Uint8Array<ArrayBufferLike>, value: Uint8Array<ArrayBufferLike>]

One key-value pair of a block. Keys are compared by compareBytes from knotkit/key-encoding.

SortedBlockEntry
>) {
let
let previous: Uint8Array<ArrayBufferLike> | undefined
previous
:
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
| undefined
for (const
const entry: SortedBlockEntry
entry
of
entries: Iterable<SortedBlockEntry>
entries
) {
if (
let previous: Uint8Array<ArrayBufferLike> | undefined
previous
===
var undefined
undefined
||
function compareBytes(left: Uint8Array, right: Uint8Array): -1 | 0 | 1

Compare two byte strings in unsigned lexicographic order, the order an encoded key sorts in.

A proper prefix sorts before every longer string that extends it. The result is -1, 0, or 1, so the function is an Order<Uint8Array> for knotkit/heap, knotkit/ordered-map, knotkit/sorted-merge, or Array.prototype.sort.

Runs in O(min(left.byteLength, right.byteLength)) and does not validate its arguments, because it sits on the hot path of every comparison-based structure; pass Uint8Array values.

compareBytes
(
let previous: Uint8Array<ArrayBufferLike>
previous
,
const entry: SortedBlockEntry
entry
[0]) !== 0) {
let previous: Uint8Array<ArrayBufferLike> | undefined
previous
=
const entry: SortedBlockEntry
entry
[0]
yield
const entry: SortedBlockEntry
entry
}
}
}
const
const merged: Generator<SortedBlockEntry, void, unknown>
merged
=
mergeSorted<SortedBlockEntry>(order: Order<SortedBlockEntry>, sources: Iterable<Iterable<SortedBlockEntry>>): Generator<SortedBlockEntry, void, unknown>

Lazily merge a finite collection of independently iterable sorted sources under the same total order. Keeps duplicates. Equal items retain their order within each source, with earlier sources winning ties. Supply a stable order and keep compared values unchanged while the merge is active.

The first advance calls next() once on each source. Each subsequent advance pulls only from the source of the last emitted value. With k sources, setup takes O(k) time and space, and each output after setup takes O(log(k + 1)) time, excluding input reads and comparator cost. Individual sources may be infinite.

On early return or failure, calls return() once on each opened, unfinished iterator that exposes it. Errors from the order and input iterators propagate. A cleanup error surfaces if the merge was otherwise returning normally. When several iterators fail during cleanup, the first error surfaces after all are tried.

mergeSorted
<
type SortedBlockEntry = readonly [key: Uint8Array<ArrayBufferLike>, value: Uint8Array<ArrayBufferLike>]

One key-value pair of a block. Keys are compared by compareBytes from knotkit/key-encoding.

SortedBlockEntry
>((
a: SortedBlockEntry
a
,
b: SortedBlockEntry
b
) =>
function compareBytes(left: Uint8Array, right: Uint8Array): -1 | 0 | 1

Compare two byte strings in unsigned lexicographic order, the order an encoded key sorts in.

A proper prefix sorts before every longer string that extends it. The result is -1, 0, or 1, so the function is an Order<Uint8Array> for knotkit/heap, knotkit/ordered-map, knotkit/sorted-merge, or Array.prototype.sort.

Runs in O(min(left.byteLength, right.byteLength)) and does not validate its arguments, because it sits on the hot path of every comparison-based structure; pass Uint8Array values.

compareBytes
(
a: SortedBlockEntry
a
[0],
b: SortedBlockEntry
b
[0]), [
const newest: SortedBlock
newest
,
const oldest: SortedBlock
oldest
])
const
const compacted: SortedBlock
compacted
=
function restartPointSortedBlock(entries: Iterable<SortedBlockEntry>, options?: RestartPointSortedBlockOptions): SortedBlock

Build an immutable restart-point block from entries already in strictly ascending compareBytes key order.

Each key is stored as the bytes it does not share with the previous key, except at every restartInterval-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most restartInterval entries forward. Every input byte is copied into one Uint8Array, so mutating the caller's arrays afterwards cannot change the block. Builds in O(total key and value bytes).

@throws ― {SortedBlockInvalidInputError} With INVALID_RESTART_INTERVAL when restartInterval is not a positive safe integer, INVALID_ENTRY when entries is not iterable or an entry is not a [Uint8Array, Uint8Array] pair, UNSORTED_KEY or DUPLICATE_KEY when keys do not strictly ascend, and MAX_CAPACITY_EXCEEDED when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.

restartPointSortedBlock
(
function firstPerKey(entries: Iterable<SortedBlockEntry>): Generator<SortedBlockEntry, void, unknown>
firstPerKey
(
const merged: Generator<SortedBlockEntry, void, unknown>
merged
))
const compacted: SortedBlock
compacted
.
SortedBlock.get: (key: Uint8Array) => Uint8Array | undefined

A copy of the value stored under key, or undefined when the block holds no such key.

@throws ― {SortedBlockInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

get
(
const key: Uint8Array<ArrayBuffer>
key
) // Uint8Array [20]
  • build the data or index block of a sorted string table from key-value pairs already in key order
  • store many sorted Uint8Array keys that share long prefixes in fewer bytes than an array of pairs
  • look up, seek to the first key at or above a bound, or scan a key range in a block built once
  • persist a sorted run as bytes and reload it with every offset, varint, and key order validated
  • trade block size against lookup cost by choosing how often a key is stored whole
FactoryChoose whenCost
restartPointSortedBlock
kind restart-point
the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is builtthree varints, the unshared key bytes, and the value per entry, 4 bytes per restart point, and an 8-byte trailer; 385,963 bytes at restartInterval 16 for 10,000 23-byte keys with 32-byte values, 550,000 bytes raw

Performance and benchmarks for this module

ExportReturnsDoes
restartPointSortedBlockSortedBlockImmutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole.

Cost per member. Open a row for every operation.

restartPointSortedBlock 8 members
MemberCost
buildO(total key and value bytes)
sizeO(1)
firstKeyO(k)
lastKeyO(k)
getO(k log(n / r) + r k + v), including v returned value bytes
hasO(k log(n / r) + r k)
ceilingO(k log(n / r) + r k + v), including v returned value bytes
entriesO(k log(n / r) + r k) to start, then O(k + v) per entry including v returned value bytes

Every error this module throws is SortedBlockInvalidInputError or SortedBlockParseError, with a code from a closed, exported list. Branch on the code; the message is for people.

SortedBlockInvalidInputError
INVALID_RESTART_INTERVAL INVALID_ENTRY UNSORTED_KEY DUPLICATE_KEY MAX_CAPACITY_EXCEEDED
SortedBlockParseError
INVALID_KEY INVALID_RANGE FOREIGN_SORTED_BLOCK INVALID_PACKAGE_HEADER UNKNOWN_KIND CORRUPT_BLOCK_PAYLOAD INVALID_MAGIC UNSUPPORTED_ENVELOPE_VERSION UNSUPPORTED_PAYLOAD_VERSION INVALID_SECTION_GEOMETRY NONZERO_PADDING MISALIGNED_SECTION TRUNCATED_PAYLOAD INVALID_CODEC_RESULT DECODE_BUDGET_EXCEEDED UNSTABLE_BUFFER WRONG_FORMAT INTEGRITY_MISMATCH

Serialization lives in a separate entrypoint, knotkit/sorted-block/wire, so code that never saves a structure never loads a parser.

Functions
serializeSortedBlock, deserializeSortedBlock
Formats
binary
Compatibility
schema-versioned, envelope v1
If you need to…Use instead
insert, update, or delete keys after the structure is builtknotkit/ordered-map
turn integers, strings, or tuples into byte keys whose order matches the valuesknotkit/key-encoding
merge several sorted runs before building a block (resolve equal keys in the merged stream)knotkit/sorted-merge
look up keys by exact match only, with no order, seek, or range scanMap
a whole persistent store with writes, compaction, and crash recoveryan embedded key-value store such as SQLite, LevelDB, or RocksDB

Measured by the suite in packages/sorted-block/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/sorted-block
Use knotkit/sorted-block for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sorted-block'.

Exports:
- `restartPointSortedBlock` → `SortedBlock`: Immutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole.

Pick the layout by these rules:
- `restartPointSortedBlock` (kind 'restart-point') when the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built

Use something else when:
- insert, update, or delete keys after the structure is built → knotkit/ordered-map
- turn integers, strings, or tuples into byte keys whose order matches the values → knotkit/key-encoding
- merge several sorted runs before building a block (resolve equal keys in the merged stream) → knotkit/sorted-merge
- look up keys by exact match only, with no order, seek, or range scan → Map
- a whole persistent store with writes, compaction, and crash recovery → an embedded key-value store such as SQLite, LevelDB, or RocksDB

Errors are SortedBlockInvalidInputError or SortedBlockParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/sorted-block/wire` (serializeSortedBlock, deserializeSortedBlock).

Full page: https://knotkit.jkomyno.dev/modules/sorted-block.md
Types: node_modules/knotkit/sorted-block/ and https://knotkit.jkomyno.dev/reference/knotkit/sorted-block/