# knotkit/key-encoding

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

## Use

```ts
import { bytesPrefixEnd, compareBytes, decodeKeyTuple, encodeKeyTuple } from 'knotkit/key-encoding'

// (user key ascending, sequence number descending): the newest version of each key sorts first.
const rows: [userKey: string, sequence: bigint][] = [
  ['b', 1n],
  ['a', 2n],
  ['a', 7n],
]
const keys = rows.map(([userKey, sequence]) =>
  encodeKeyTuple([
    { kind: 'string', value: userKey },
    { kind: 'uint64', value: sequence, direction: 'descending' },
  ]),
)

const order = keys.toSorted(compareBytes).map((key) => decodeKeyTuple(key).map((part) => part.value))
// [['a', 7n], ['a', 2n], ['b', 1n]]

// Every key under user 'a' lies in [prefix, end).
const prefix = encodeKeyTuple([{ kind: 'string', value: 'a' }])
const end = bytesPrefixEnd(prefix)
```

## What it solves

* 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

## Choose a layout

| Factory                          | Choose when                                                                                                                        | Cost                                                                              |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `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 prefixes | length + 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 needs            | UTF-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 - 1                                                                                           | 4 bytes                                                                           |
| `encodeInt32Key`kind `int32`     | the field is an integer in -2^31 .. 2^31 - 1 that can be negative                                                                  | 4 bytes                                                                           |
| `encodeUint64Key`kind `uint64`   | the field is a bigint in 0n .. 2n \*\* 64n - 1n, such as a sequence number or a 64-bit id                                          | 8 bytes                                                                           |
| `encodeInt64Key`kind `int64`     | the field is a bigint in -(2n \*\* 63n) .. 2n \*\* 63n - 1n that can be negative                                                   | 8 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 key                       | 8 bytes                                                                           |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/key-encoding/README.md#performance)

## API

| Export                                                                                | Returns                   | Does                                                                                                                                                                          |
| ------------------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`encodeKeyTuple`](/reference/knotkit/key-encoding/functions/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`](/reference/knotkit/key-encoding/functions/decodekeytuple/)         | `readonly KeyTuplePart[]` | Parts of an encodeKeyTuple key, each with an explicit direction; accepts exactly the bytes encodeKeyTuple writes.                                                             |
| [`compareBytes`](/reference/knotkit/key-encoding/functions/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`](/reference/knotkit/key-encoding/functions/commonprefixlength/) | `number`                  | Count of leading bytes two keys share, from 0 through the shorter length. Does not validate its arguments.                                                                    |
| [`bytesPrefixEnd`](/reference/knotkit/key-encoding/functions/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`](/reference/knotkit/key-encoding/functions/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.                |

Cost per member. Open a row for every operation.

`encodeKeyTuple` 1 members

| Member   | Cost                               |
| -------- | ---------------------------------- |
| `encode` | O(total key bytes), one allocation |

`decodeKeyTuple` 1 members

| Member   | Cost               |
| -------- | ------------------ |
| `decode` | O(total key bytes) |

`compareBytes` 1 members

| Member    | Cost                        |
| --------- | --------------------------- |
| `compare` | O(shared prefix length + 1) |

`commonPrefixLength` 1 members

| Member    | Cost      |
| --------- | --------- |
| `compute` | O(result) |

`bytesPrefixEnd` 1 members

| Member    | Cost                             |
| --------- | -------------------------------- |
| `compute` | O(prefix length), one allocation |

`invertKeyBytes` 1 members

| Member    | Cost                      |
| --------- | ------------------------- |
| `compute` | O(length), one allocation |

## Errors

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`

## When not to use it

| If you need to…                                                                  | Use instead                                                                            |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| 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`](/modules/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`](/modules/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 |

## Performance

Measured by the suite in [`packages/key-encoding/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/key-encoding/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/key-encodingCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/key-encoding/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/key-encoding/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/key-encoding/knotkit.capability.json)suggest a change to the source record
