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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
An implementation of the WHATWG Encoding StandardTextDecoder API.
Supports every encoding label the standard defines, except the labels of the
replacement encoding.
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.
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(
constada:Uint8Array<ArrayBufferLike>
ada,
constgrace: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.
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.
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.
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
constkey: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.
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([[
constkey: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.
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([[
constkey: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.
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
constentry:SortedBlockEntry
entryof
entries: Iterable<SortedBlockEntry>
entries) {
if (
let previous:Uint8Array<ArrayBufferLike> |undefined
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,
constentry:SortedBlockEntry
entry[0]) !==0) {
let previous:Uint8Array<ArrayBufferLike> |undefined
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.
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.
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.
the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built
three 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
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.
Cost per member. Open a row for every operation.
restartPointSortedBlock8 members
Member
Cost
build
O(total key and value bytes)
size
O(1)
firstKey
O(k)
lastKey
O(k)
get
O(k log(n / r) + r k + v), including v returned value bytes
has
O(k log(n / r) + r k)
ceiling
O(k log(n / r) + r k + v), including v returned value bytes
entries
O(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.
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.
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/