Skip to content

knotkit/key-encoding

Encodes integers, doubles, byte strings, strings, and tuples of them as byte keys whose unsigned byte order matches the values' order

import {
function bytesPrefixEnd(prefix: Uint8Array): Uint8Array | undefined

The smallest byte string greater than every key that starts with prefix, the exclusive upper bound of a prefix range scan: a key starts with prefix exactly when prefix <= key < bytesPrefixEnd(prefix).

Drops trailing 0xff bytes and increments the last remaining byte, returning a new array. Returns undefined when prefix is empty or every byte is 0xff, because then no finite bound exists and the scan runs to the end.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when prefix is not a Uint8Array.

bytesPrefixEnd
,
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
,
function decodeKeyTuple(bytes: Uint8Array): readonly KeyTuplePart[]

Decode an encodeKeyTuple key back into its parts. Every decoded part carries an explicit direction.

Accepts exactly the bytes encodeKeyTuple writes: re-encoding the result reproduces the input byte for byte. An empty array decodes to an empty tuple.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when bytes is not a Uint8Array.

@throws ― {KeyEncodingParseError} UNKNOWN_PART_TAG for a tag that names no kind; TRUNCATED_KEY when a payload or terminator is cut off; INVALID_ESCAPE_SEQUENCE for a 0x00 not followed by 0xff or 0x00; INVALID_UTF8 for a string payload that is not well-formed UTF-8; NON_CANONICAL_FLOAT64 for a NaN or -0 bit pattern.

decodeKeyTuple
,
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'
// (user key ascending, sequence number descending): the newest version of each key sorts first.
const
const rows: [userKey: string, sequence: bigint][]
rows
: [
string
userKey
: string,
bigint
sequence
: bigint][] = [
['b', 1n],
['a', 2n],
['a', 7n],
]
const
const keys: Uint8Array<ArrayBufferLike>[]
keys
=
const rows: [userKey: string, sequence: bigint][]
rows
.
Array<[userKey: string, sequence: bigint]>.map<Uint8Array<ArrayBufferLike>>(callbackfn: (value: [userKey: string, sequence: bigint], index: number, array: [userKey: string, sequence: bigint][]) => Uint8Array<ArrayBufferLike>, thisArg?: any): Uint8Array<ArrayBufferLike>[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(([
userKey: string
userKey
,
sequence: bigint
sequence
]) =>
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
:
userKey: string
userKey
},
{
kind: "uint64"
kind
: 'uint64',
value: bigint
value
:
sequence: bigint
sequence
,
direction?: KeyDirection | undefined
direction
: 'descending' },
]),
)
const
const order: (string | number | bigint | Uint8Array<ArrayBufferLike>)[][]
order
=
const keys: Uint8Array<ArrayBufferLike>[]
keys
.
Array<Uint8Array<ArrayBufferLike>>.toSorted(compareFn?: ((a: Uint8Array<ArrayBufferLike>, b: Uint8Array<ArrayBufferLike>) => number) | undefined): Uint8Array<ArrayBufferLike>[]

Returns a copy of an array with its elements sorted.

@param ―

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]

toSorted
(
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
).
Array<Uint8Array<ArrayBufferLike>>.map<(string | number | bigint | Uint8Array<ArrayBufferLike>)[]>(callbackfn: (value: Uint8Array<ArrayBufferLike>, index: number, array: Uint8Array<ArrayBufferLike>[]) => (string | number | bigint | Uint8Array<ArrayBufferLike>)[], thisArg?: any): (string | number | bigint | Uint8Array<ArrayBufferLike>)[][]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
key: Uint8Array<ArrayBufferLike>
key
) =>
function decodeKeyTuple(bytes: Uint8Array): readonly KeyTuplePart[]

Decode an encodeKeyTuple key back into its parts. Every decoded part carries an explicit direction.

Accepts exactly the bytes encodeKeyTuple writes: re-encoding the result reproduces the input byte for byte. An empty array decodes to an empty tuple.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when bytes is not a Uint8Array.

@throws ― {KeyEncodingParseError} UNKNOWN_PART_TAG for a tag that names no kind; TRUNCATED_KEY when a payload or terminator is cut off; INVALID_ESCAPE_SEQUENCE for a 0x00 not followed by 0xff or 0x00; INVALID_UTF8 for a string payload that is not well-formed UTF-8; NON_CANONICAL_FLOAT64 for a NaN or -0 bit pattern.

decodeKeyTuple
(
key: Uint8Array<ArrayBufferLike>
key
).
ReadonlyArray<KeyTuplePart>.map<string | number | bigint | Uint8Array<ArrayBufferLike>>(callbackfn: (value: KeyTuplePart, index: number, array: readonly KeyTuplePart[]) => string | number | bigint | Uint8Array<ArrayBufferLike>, thisArg?: any): (string | number | bigint | Uint8Array<ArrayBufferLike>)[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
part: KeyTuplePart
part
) =>
part: KeyTuplePart
part
.
value: string | number | bigint | Uint8Array<ArrayBufferLike>
value
))
// [['a', 7n], ['a', 2n], ['b', 1n]]
// Every key under user 'a' lies in [prefix, end).
const
const prefix: Uint8Array<ArrayBufferLike>
prefix
=
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
: 'a' }])
const
const end: Uint8Array<ArrayBufferLike> | undefined
end
=
function bytesPrefixEnd(prefix: Uint8Array): Uint8Array | undefined

The smallest byte string greater than every key that starts with prefix, the exclusive upper bound of a prefix range scan: a key starts with prefix exactly when prefix <= key < bytesPrefixEnd(prefix).

Drops trailing 0xff bytes and increments the last remaining byte, returning a new array. Returns undefined when prefix is empty or every byte is 0xff, because then no finite bound exists and the scan runs to the end.

@throws ― {KeyEncodingInvalidInputError} INVALID_KEY_VALUE when prefix is not a Uint8Array.

bytesPrefixEnd
(
const prefix: Uint8Array<ArrayBufferLike>
prefix
)
key-encoding.ts
  • build a composite key such as (user id, timestamp) that a byte-ordered store sorts field by field
  • sort one field of a composite key descending, such as newest version first, without a custom comparator
  • store signed integers or doubles as keys that sort numerically rather than by their raw bytes
  • scan every key that starts with a prefix by computing the range's exclusive upper bound
  • compare or sort Uint8Array keys in the order memcmp, LevelDB, or IndexedDB uses
FactoryChoose whenCost
encodeBytesKey
kind bytes
the field is a Uint8Array whose keys must sort by the raw bytes, with a byte string sorting before every longer string it prefixeslength + 2 bytes, plus one byte per 0x00 in the value
encodeStringKey
kind string
the field is a JavaScript string without unpaired surrogates and Unicode code point order is the order the caller needsUTF-8 length + 2 bytes, plus one byte per U+0000; one TextEncoder pass per encode
encodeUint32Key
kind uint32
the field is an integer in 0 .. 2^32 - 14 bytes
encodeInt32Key
kind int32
the field is an integer in -2^31 .. 2^31 - 1 that can be negative4 bytes
encodeUint64Key
kind uint64
the field is a bigint in 0n .. 2n ** 64n - 1n, such as a sequence number or a 64-bit id8 bytes
encodeInt64Key
kind int64
the field is a bigint in -(2n ** 63n) .. 2n ** 63n - 1n that can be negative8 bytes
encodeFloat64Key
kind float64
the field is a non-NaN number that is fractional or beyond the safe integers, and -0 and 0 may share one key8 bytes

Performance and benchmarks for this module

ExportReturnsDoes
encodeKeyTupleUint8ArrayComposite key over bytes, string, 32- and 64-bit integer, and float64 parts, each ascending or descending, ordered part by part under compareBytes with a prefix tuple first.
decodeKeyTuplereadonly KeyTuplePart[]Parts of an encodeKeyTuple key, each with an explicit direction; accepts exactly the bytes encodeKeyTuple writes.
compareBytes-1 | 0 | 1Unsigned lexicographic order over Uint8Array keys, a proper prefix first; an Order<Uint8Array> for sorting and comparator-based structures. Does not validate its arguments.
commonPrefixLengthnumberCount of leading bytes two keys share, from 0 through the shorter length. Does not validate its arguments.
bytesPrefixEndUint8Array | undefinedSmallest key greater than every key that starts with a prefix, the exclusive end of a prefix scan; undefined when the prefix is empty or all 0xff.
invertKeyBytesUint8ArrayBitwise complement of every byte as a new array, reversing the order of keys of one length; a variable-length descending field needs encodeDescendingBytesKey.

Cost per member. Open a row for every operation.

encodeKeyTuple 1 members
MemberCost
encodeO(total key bytes), one allocation
decodeKeyTuple 1 members
MemberCost
decodeO(total key bytes)
compareBytes 1 members
MemberCost
compareO(shared prefix length + 1)
commonPrefixLength 1 members
MemberCost
computeO(result)
bytesPrefixEnd 1 members
MemberCost
computeO(prefix length), one allocation
invertKeyBytes 1 members
MemberCost
computeO(length), one allocation

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

KeyEncodingInvalidInputError
INVALID_KEY_VALUE TRUNCATED_KEY INVALID_ESCAPE_SEQUENCE UNKNOWN_PART_TAG INVALID_UTF8 NON_CANONICAL_FLOAT64
KeyEncodingParseError
INVALID_OFFSET TRAILING_BYTES
If you need to…Use instead
persist a whole data structure and read it back laterthe structure package's serialize function, over knotkit/wire
fingerprint or shard keys where only equality matters, not orderknotkit/hash
sort strings by human language rules, case-insensitively, or with accents foldedIntl.Collator
keep keys in comparator order in memory and query rank or rangesknotkit/ordered-map
encode arbitrary nested JSON values or schema-evolving recordsa general serializer such as JSON, CBOR, or MessagePack, which does not preserve order

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

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

Exports:
- `encodeKeyTuple` → `Uint8Array`: Composite key over bytes, string, 32- and 64-bit integer, and float64 parts, each ascending or descending, ordered part by part under compareBytes with a prefix tuple first.
- `decodeKeyTuple` → `readonly KeyTuplePart[]`: Parts of an encodeKeyTuple key, each with an explicit direction; accepts exactly the bytes encodeKeyTuple writes.
- `compareBytes` → `-1 | 0 | 1`: Unsigned lexicographic order over Uint8Array keys, a proper prefix first; an Order<Uint8Array> for sorting and comparator-based structures. Does not validate its arguments.
- `commonPrefixLength` → `number`: Count of leading bytes two keys share, from 0 through the shorter length. Does not validate its arguments.
- `bytesPrefixEnd` → `Uint8Array | undefined`: Smallest key greater than every key that starts with a prefix, the exclusive end of a prefix scan; undefined when the prefix is empty or all 0xff.
- `invertKeyBytes` → `Uint8Array`: Bitwise complement of every byte as a new array, reversing the order of keys of one length; a variable-length descending field needs encodeDescendingBytesKey.

Pick the layout by these rules:
- `encodeBytesKey` (kind 'bytes') when the field is a Uint8Array whose keys must sort by the raw bytes, with a byte string sorting before every longer string it prefixes
- `encodeStringKey` (kind 'string') when the field is a JavaScript string without unpaired surrogates and Unicode code point order is the order the caller needs
- `encodeUint32Key` (kind 'uint32') when the field is an integer in 0 .. 2^32 - 1
- `encodeInt32Key` (kind 'int32') when the field is an integer in -2^31 .. 2^31 - 1 that can be negative
- `encodeUint64Key` (kind 'uint64') when the field is a bigint in 0n .. 2n ** 64n - 1n, such as a sequence number or a 64-bit id
- `encodeInt64Key` (kind 'int64') when the field is a bigint in -(2n ** 63n) .. 2n ** 63n - 1n that can be negative
- `encodeFloat64Key` (kind 'float64') when the field is a non-NaN number that is fractional or beyond the safe integers, and -0 and 0 may share one key

Use something else when:
- persist a whole data structure and read it back later → the structure package's serialize function, over knotkit/wire
- fingerprint or shard keys where only equality matters, not order → knotkit/hash
- sort strings by human language rules, case-insensitively, or with accents folded → Intl.Collator
- keep keys in comparator order in memory and query rank or ranges → knotkit/ordered-map
- encode arbitrary nested JSON values or schema-evolving records → a general serializer such as JSON, CBOR, or MessagePack, which does not preserve order

Errors are KeyEncodingInvalidInputError or KeyEncodingParseError with a `code` property. Branch on `error.code`, never on the message.

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