# knotkit/bitset

> Provides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks

## Use

```ts
import { roaringBitset } from 'knotkit/bitset'

const rows = [{ id: 7 }, { id: 4 }, { id: 7 }]
const seen = roaringBitset()
const unique = []

for (const row of rows) {
  if (seen.has(row.id)) {
    continue
  }
  seen.add(row.id)
  unique.push(row)
}

seen.size // 2, exact and O(1)
```

```ts
import { denseBitset } from 'knotkit/bitset'

const todayIds = [40, 41, 42, 43, 44]
const yesterdayIds = [42, 43, 44, 45]
const today = denseBitset({ items: todayIds })
const yesterday = denseBitset({ items: yesterdayIds })

today.addAll(yesterday) // union: ids added
today.retainAll(yesterday) // intersection: ids deleted
today.deleteAll(yesterday) // difference: ids deleted
today.intersectionSize(yesterday) // |A ∩ B|, allocating nothing
```

```ts
import { roaringBitset } from 'knotkit/bitset'

const ids = roaringBitset({ items: [2, 5, 9] })

ids.at(0) // 2, the smallest
ids.at(-1) // 9, the largest
ids.rank(3) // 1, ids at or below 3
ids.ceiling(3) // 5, the next id at or above 3
ids.ceiling(10) // undefined
ids.floor(8) // 5, the previous id at or below 8
ids.floor(1) // undefined
ids.countRange(0, 6) // 2, ids in [0, 6)
```

```ts
import { denseBitset } from 'knotkit/bitset'

const slots = denseBitset()

slots.addRange(0, 1_000) // 1,000 ids added
slots.deleteRange(500, 600) // 100 ids deleted
```

```ts
import { roaringBitset } from 'knotkit/bitset'

const cached = roaringBitset({ items: [1, 2, 3] })
const requested = new Set([2, 3, 9])

// A native Set, built from the bitset, without materializing its ids first.
new Set(requested.union(cached)) // Set { 2, 3, 9, 1 }
requested.isSubsetOf(cached) // false
new Set(cached) // Set { 1, 2, 3 }

// And the other way round: a bitset compares against any set-like.
cached.isSubsetOf(requested) // false
cached.intersectionSize(requested) // 2
```

```ts
import { __BITSET_LAYOUTS, roaringBitset } from 'knotkit/bitset'

const a = roaringBitset({ items: [1, 2] })
const b = roaringBitset({ items: [2, 3] })

const union = __BITSET_LAYOUTS[a.kind]({ items: a })
union.addAll(b) // a ∪ b; a and b are untouched
```

## What it solves

* filter membership over millions of non-negative integer ids without paying a byte per possible id
* combine two id sets by union, intersection, or difference without allocating a third set
* ask how many ids are at or below a value or inside a range, which id is the k-th smallest, or which id comes next or before
* walk a set of ids in ascending order without sorting them
* hold ids scattered across a wide range, such as row or document ids, without allocating the whole range

## Choose a layout

| Factory                       | Choose when                                                                                                              | Cost                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `roaringBitset`kind `roaring` | you cannot name the largest id you will store, or fewer than one id in 64 of the range you can name holds a stored id    | two bytes per stored id while a chunk is an array and one bit per possible id once it becomes a bitmap, plus a directory entry per occupied chunk and, once the set holds at least as many ids as its highest chunk key, a two-byte key-table entry per key; about 1.7 times slower than dense on has at half density of a 2^24 universe and about 4.7 times slower at one id in 16, and the only layout that stays small when one id is far from the rest |
| `denseBitset`kind `dense`     | you can name the largest id, it sits within 64 MiB of bitmap, and per-id has and add traffic dominates the operation mix | one bit per possible id up to the largest id it has held until clear, so a single far id pays for the whole span; measured about 1.7 times faster than roaring on has at half density of a 2^24 universe, about 4.7 times faster at one id in 16, and faster at every density measured                                                                                                                                                                     |

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

## Worked example

ID span65,53616Reset

* Two exact sets share 3 IDs. The third recent ID is 7.
* One far ID needs 8192 dense bitmap bytes or 2 bytes of Roaring array payload in this model.
* Roaring converts its array container to a bitmap above 4,096 IDs. The model excludes headers and directory entries.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/bitset/demo.ts) against `knotkit/bitset` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                | Returns  | Does                                                                                                                                                                                 |
| --------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`roaringBitset`](/reference/knotkit/bitset/functions/roaringbitset/) | `Bitset` | Bitset over 65,536-id chunks, each a sorted Uint16Array below the Roaring crossover and an 8 KB bitmap above it, so storage follows the ids stored rather than the span they occupy. |
| [`denseBitset`](/reference/knotkit/bitset/functions/densebitset/)     | `Bitset` | Bitset over one flat Uint32Array bitmap that doubles on growth and keeps its high-water capacity until clear, so its storage follows the largest id it has held.                     |

Cost per member. Open a row for every operation.

`roaringBitset` 22 members

| Member              | Cost                                                                                                                                         |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `size`              | O(1)                                                                                                                                         |
| `has`               | O(log c + log n) array container, O(log c) bitmap container; the O(log c) lookup is one indexed read once the key table is built             |
| `add`               | O(log c + n) array container, O(log c) bitmap container                                                                                      |
| `delete`            | O(log c + n) array container, O(log c) bitmap container                                                                                      |
| `addRange`          | O(chunks in span)                                                                                                                            |
| `deleteRange`       | O(chunks in span)                                                                                                                            |
| `countRange`        | O(log c + chunks in span)                                                                                                                    |
| `addAll`            | O(k log k) to stage a generic operand, skipped when it ascends, then one merge per touched chunk; O(min c) chunk copies for a Bitset operand |
| `deleteAll`         | O(k log k) to stage a generic operand, then one pass per touched chunk                                                                       |
| `retainAll`         | O(c + k log k)                                                                                                                               |
| `equals`            | O(min c)                                                                                                                                     |
| `isSubsetOf`        | O(min c)                                                                                                                                     |
| `isDisjointFrom`    | O(min c), stops at the first shared chunk                                                                                                    |
| `intersectionSize`  | O(min c)                                                                                                                                     |
| `at`                | O(c), from the nearer end                                                                                                                    |
| `rank`              | O(c), from the nearer end                                                                                                                    |
| `ceiling`           | O(c)                                                                                                                                         |
| `floor`             | O(log c)                                                                                                                                     |
| `values`            | O(size), O(1) per step                                                                                                                       |
| `keys`              | O(size), O(1) per step                                                                                                                       |
| `[Symbol.iterator]` | O(size), O(1) per step                                                                                                                       |
| `clear`             | O(1)                                                                                                                                         |

`denseBitset` 22 members

| Member              | Cost                                                                          |
| ------------------- | ----------------------------------------------------------------------------- |
| `size`              | O(1)                                                                          |
| `has`               | O(1)                                                                          |
| `add`               | O(1) amortized                                                                |
| `delete`            | O(1); the trailing-word trim is deferred to the next read that walks the span |
| `addRange`          | O((end - start) / 32)                                                         |
| `deleteRange`       | O((end - start) / 32)                                                         |
| `countRange`        | O((end - start) / 32)                                                         |
| `addAll`            | O(k)                                                                          |
| `deleteAll`         | O(k)                                                                          |
| `retainAll`         | O(maxId / 32 + k log k)                                                       |
| `equals`            | O(min maxId / 32)                                                             |
| `isSubsetOf`        | O(min maxId / 32)                                                             |
| `isDisjointFrom`    | O(min maxId / 32), stops at the first shared word                             |
| `intersectionSize`  | O(min maxId / 32)                                                             |
| `at`                | O(maxId / 32), from the nearer end                                            |
| `rank`              | O(maxId / 32), from the nearer end                                            |
| `ceiling`           | O(maxId / 32)                                                                 |
| `floor`             | O(maxId / 32)                                                                 |
| `values`            | O(maxId / 32), O(1) per step                                                  |
| `keys`              | O(maxId / 32), O(1) per step                                                  |
| `[Symbol.iterator]` | O(maxId / 32), O(1) per step                                                  |
| `clear`             | O(1)                                                                          |

## Errors

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

* `BitsetInvalidInputError`

  `INVALID_ID` `INVALID_RANGE` `INVALID_INDEX` `FOREIGN_BITSET` `INVALID_OPERAND` `MAX_CAPACITY_EXCEEDED` `MODIFIED_DURING_ITERATION` `SERIALIZATION_LIMIT_EXCEEDED`

* `BitsetParseError`

  `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `INVALID_ID_SEQUENCE` `CARDINALITY_MISMATCH` `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`

## Save and restore

Serialization lives in a separate entrypoint, `knotkit/bitset/wire`, so code that never saves a structure never loads a parser.

* Functions

  `serializeBitset`, `deserializeBitset`

* Formats

  binary

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                                              | Use instead                                                                                    |
| -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| a plain set over arbitrary keys, or over ids beyond 2^32 - 1                                 | Set or Map                                                                                     |
| membership over unbounded values where a small false-positive rate is acceptable             | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)                                             |
| read a set as it was at an earlier point while it keeps changing                             | [`knotkit/snapshot-set`](/modules/snapshot-set/)                                               |
| a boolean flag per vertex you already index by number, where membership is the only question | a pre-sized Uint8Array, as problems/mst and problems/tsp do                                    |
| track which elements are connected and merge groups                                          | [`knotkit/disjoint-set`](/modules/disjoint-set/)                                               |
| persist the set in a format another implementation reads                                     | your own encoder: the binary artifact is Knotkit's own and is not RoaringFormatSpec-compatible |

## Performance

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

## Prompt an agent

Prompt · knotkit/bitsetCopy prompt

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

Exports:
- `roaringBitset` → `Bitset`: Bitset over 65,536-id chunks, each a sorted Uint16Array below the Roaring crossover and an 8 KB bitmap above it, so storage follows the ids stored rather than the span they occupy.
- `denseBitset` → `Bitset`: Bitset over one flat Uint32Array bitmap that doubles on growth and keeps its high-water capacity until clear, so its storage follows the largest id it has held.

Pick the layout by these rules:
- `roaringBitset` (kind 'roaring') when you cannot name the largest id you will store, or fewer than one id in 64 of the range you can name holds a stored id
- `denseBitset` (kind 'dense') when you can name the largest id, it sits within 64 MiB of bitmap, and per-id has and add traffic dominates the operation mix

Use something else when:
- a plain set over arbitrary keys, or over ids beyond 2^32 - 1 → Set or Map
- membership over unbounded values where a small false-positive rate is acceptable → knotkit/scalar-sketch
- read a set as it was at an earlier point while it keeps changing → knotkit/snapshot-set
- a boolean flag per vertex you already index by number, where membership is the only question → a pre-sized Uint8Array, as problems/mst and problems/tsp do
- track which elements are connected and merge groups → knotkit/disjoint-set
- persist the set in a format another implementation reads → your own encoder: the binary artifact is Knotkit's own and is not RoaringFormatSpec-compatible

Errors are BitsetInvalidInputError or BitsetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/bitset/wire` (serializeBitset, deserializeBitset).

Full page: https://knotkit.jkomyno.dev/modules/bitset.md
Types: node_modules/knotkit/bitset/ and https://knotkit.jkomyno.dev/reference/knotkit/bitset/
```

## See also

* [API reference](/reference/knotkit/bitset/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/bitset/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/bitset/knotkit.capability.json)suggest a change to the source record
