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.
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.
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.
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.
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.
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.
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]
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.
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.
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.
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).
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.
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.
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.
Unsigned lexicographic order over Uint8Array keys, a proper prefix first; an Order<Uint8Array> for sorting and comparator-based structures. Does not validate its arguments.
Bitwise complement of every byte as a new array, reversing the order of keys of one length; a variable-length descending field needs encodeDescendingBytesKey.
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.
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.
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/