Skip to content

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

import {
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
} from 'knotkit/bitset'
const
const rows: {
id: number;
}[]
rows
= [{
id: number
id
: 7 }, {
id: number
id
: 4 }, {
id: number
id
: 7 }]
const
const seen: Bitset
seen
=
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
()
const
const unique: any[]
unique
= []
for (const
const row: {
id: number;
}
row
of
const rows: {
id: number;
}[]
rows
) {
if (
const seen: Bitset
seen
.
Bitset.has: (id: number) => boolean

Whether id is stored. Total: returns false for any value that is not an id (-1, 1.5, NaN, a string, 2 ** 32), as Set.prototype.has does for a value it does not hold. O(1) for dense; O(log c + log n) for a roaring array container and O(log c) for a bitmap container, where c is the number of occupied chunks and n a container's cardinality.

has
(
const row: {
id: number;
}
row
.
id: number
id
)) {
continue
}
const seen: Bitset
seen
.
Bitset.add: (id: number) => boolean

Add id. O(1) amortized for dense; O(log c + n) for a roaring array container, which shifts its tail.

@returns ― Whether the id was absent.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when id is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a dense bitset cannot grow its bitmap.

add
(
const row: {
id: number;
}
row
.
id: number
id
)
const unique: any[]
unique
.
Array<any>.push(...items: any[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@param ― items New elements to add to the array.

push
(
const row: {
id: number;
}
row
)
}
const seen: Bitset
seen
.
Bitset.size: number

Number of stored ids. O(1). The bitset is empty when this is 0.

size
// 2, exact and O(1)
bitset.ts
import {
function denseBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over one flat bitmap.

One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when the bitmap the items span cannot be allocated.

@example

const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2

denseBitset
} from 'knotkit/bitset'
const
const todayIds: number[]
todayIds
= [40, 41, 42, 43, 44]
const
const yesterdayIds: number[]
yesterdayIds
= [42, 43, 44, 45]
const
const today: Bitset
today
=
function denseBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over one flat bitmap.

One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when the bitmap the items span cannot be allocated.

@example

const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2

denseBitset
({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
:
const todayIds: number[]
todayIds
})
const
const yesterday: Bitset
yesterday
=
function denseBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over one flat bitmap.

One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when the bitmap the items span cannot be allocated.

@example

const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2

denseBitset
({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
:
const yesterdayIds: number[]
yesterdayIds
})
const today: Bitset
today
.
Bitset.addAll: (ids: Iterable<number>) => number

Add every id of ids.

The operand is read completely and validated before anything is added, so the call applies completely or not at all. An operand that is this package's own Bitset is copied container by container, which makes set.addAll(set) a no-op.

A generic operand is sorted and applied a chunk at a time, so input order does not change the cost: O(k log k) to stage plus one merge per touched chunk.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when the operand yields a value outside 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a dense bitset cannot grow its bitmap.

addAll
(
const yesterday: Bitset
yesterday
) // union: ids added
const today: Bitset
today
.
Bitset.retainAll: (ids: Iterable<number>) => number

Keep only the ids ids contains. The operand is read completely first, so the call applies completely or not at all.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when the operand yields a value outside 0 … BITSET_MAX_ID.

retainAll
(
const yesterday: Bitset
yesterday
) // intersection: ids deleted
const today: Bitset
today
.
Bitset.deleteAll: (ids: Iterable<number>) => number

Remove every id of ids.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when the operand yields a value outside 0 … BITSET_MAX_ID.

deleteAll
(
const yesterday: Bitset
yesterday
) // difference: ids deleted
const today: Bitset
today
.
Bitset.intersectionSize: (other: BitsetOperand) => number

The number of ids this bitset shares with other, without allocating a third set. A generic set-like is walked from whichever side is smaller.

@throws ― {BitsetInvalidInputError} With code INVALID_OPERAND when other is not a set-like.

intersectionSize
(
const yesterday: Bitset
yesterday
) // |A ∩ B|, allocating nothing
import {
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
} from 'knotkit/bitset'
const
const ids: Bitset
ids
=
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
: [2, 5, 9] })
const ids: Bitset
ids
.
Bitset.at: (position: number) => number

Return the id at position: the position-th smallest for 0 <= position < size, and the -position-th largest for -size <= position < 0, so at(0) is the smallest id and at(-1) the largest. The walk starts from the nearer end, so both are cheap; the cost grows with the distance from that end.

@throws ― {BitsetInvalidInputError} With code INVALID_INDEX when position is not an integer or falls outside -size … size - 1.

at
(0) // 2, the smallest
const ids: Bitset
ids
.
Bitset.at: (position: number) => number

Return the id at position: the position-th smallest for 0 <= position < size, and the -position-th largest for -size <= position < 0, so at(0) is the smallest id and at(-1) the largest. The walk starts from the nearer end, so both are cheap; the cost grows with the distance from that end.

@throws ― {BitsetInvalidInputError} With code INVALID_INDEX when position is not an integer or falls outside -size … size - 1.

at
(-1) // 9, the largest
const ids: Bitset
ids
.
Bitset.rank: (id: number) => number

Return the number of stored ids at or below id, matching Roaring's convention: rank(BITSET_MAX_ID) === size, and at(rank(id) - 1) === id for every stored id.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when id is not in 0 … BITSET_MAX_ID.

rank
(3) // 1, ids at or below 3
const ids: Bitset
ids
.
Bitset.ceiling: (bound: number) => number | undefined

Return the smallest stored id at or above bound, or undefined when none exists. Accepts the whole bound domain, so ceiling(2 ** 32) is always undefined and the scan idiom ceiling(id + 1) never throws.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when bound is not in 0 … 2 ** 32.

ceiling
(3) // 5, the next id at or above 3
const ids: Bitset
ids
.
Bitset.ceiling: (bound: number) => number | undefined

Return the smallest stored id at or above bound, or undefined when none exists. Accepts the whole bound domain, so ceiling(2 ** 32) is always undefined and the scan idiom ceiling(id + 1) never throws.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when bound is not in 0 … 2 ** 32.

ceiling
(10) // undefined
const ids: Bitset
ids
.
Bitset.floor: (id: number) => number | undefined

Return the largest stored id at or below id, or undefined when none exists: the mirror of

ceiling

. floor(BITSET_MAX_ID) is the largest id.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when id is not in 0 … BITSET_MAX_ID.

floor
(8) // 5, the previous id at or below 8
const ids: Bitset
ids
.
Bitset.floor: (id: number) => number | undefined

Return the largest stored id at or below id, or undefined when none exists: the mirror of

ceiling

. floor(BITSET_MAX_ID) is the largest id.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when id is not in 0 … BITSET_MAX_ID.

floor
(1) // undefined
const ids: Bitset
ids
.
Bitset.countRange: (start: number, end: number) => number

Count the stored ids in [start, end), over the same bound domain as

addRange

, so countRange(0, 2 ** 32) is size and an empty range is 0. O((end - start) / 32) for dense; O(log c + chunks in span) for roaring.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an argument is not in 0 … 2 ** 32, or INVALID_RANGE when start > end.

countRange
(0, 6) // 2, ids in [0, 6)
import {
function denseBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over one flat bitmap.

One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when the bitmap the items span cannot be allocated.

@example

const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2

denseBitset
} from 'knotkit/bitset'
const
const slots: Bitset
slots
=
function denseBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over one flat bitmap.

One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when the bitmap the items span cannot be allocated.

@example

const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2

denseBitset
()
const slots: Bitset
slots
.
Bitset.addRange: (start: number, end: number) => number

Add every id in [start, end). O((end - start) / 32) for dense; O(chunks in span) for roaring.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an argument is not in 0 … 2 ** 32, or INVALID_RANGE when start > end.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a dense bitset cannot grow its bitmap.

addRange
(0, 1_000) // 1,000 ids added
const slots: Bitset
slots
.
Bitset.deleteRange: (start: number, end: number) => number

Remove every id in [start, end), as

addRange

costs.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an argument is not in 0 … 2 ** 32, or INVALID_RANGE when start > end.

deleteRange
(500, 600) // 100 ids deleted
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
import {
const __BITSET_LAYOUTS: Readonly<Record<"roaring" | "dense", BitsetFactory>>

Every container layout this package constructs, keyed by the kind it reports.

Exported so a caller, a test, or a benchmark can sweep every layout without naming one, which is how the property suites prove the two containers agree. roaring is first for the same reason it is first in BITSET_KINDS.

__BITSET_LAYOUTS
,
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
} from 'knotkit/bitset'
const
const a: Bitset
a
=
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
: [1, 2] })
const
const b: Bitset
b
=
function roaringBitset(options?: BitsetOptions): Bitset

A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.

This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make isDisjointFrom and intersectionSize stop at the first chunk that decides them.

@param ― options - Optional items, added as if by add.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when an item is not in 0 … BITSET_MAX_ID.

@example

const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2

roaringBitset
({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
: [2, 3] })
const
const union: Bitset
union
=
const __BITSET_LAYOUTS: Readonly<Record<"roaring" | "dense", BitsetFactory>>

Every container layout this package constructs, keyed by the kind it reports.

Exported so a caller, a test, or a benchmark can sweep every layout without naming one, which is how the property suites prove the two containers agree. roaring is first for the same reason it is first in BITSET_KINDS.

__BITSET_LAYOUTS
[
const a: Bitset
a
.
Bitset.kind: "roaring" | "dense"

The container layout this bitset uses: 'roaring' or 'dense'.

kind
]({
BitsetOptions.items?: Iterable<number> | undefined

Ids to add in iteration order as the bitset is built, as if by add.

A Bitset from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.

items
:
const a: Bitset
a
})
const union: Bitset
union
.
Bitset.addAll: (ids: Iterable<number>) => number

Add every id of ids.

The operand is read completely and validated before anything is added, so the call applies completely or not at all. An operand that is this package's own Bitset is copied container by container, which makes set.addAll(set) a no-op.

A generic operand is sorted and applied a chunk at a time, so input order does not change the cost: O(k log k) to stage plus one merge per touched chunk.

@returns ― The number of ids whose membership changed.

@throws ― {BitsetInvalidInputError} With code INVALID_ID when the operand yields a value outside 0 … BITSET_MAX_ID.

@throws ― {BitsetInvalidInputError} With code MAX_CAPACITY_EXCEEDED when a dense bitset cannot grow its bitmap.

addAll
(
const b: Bitset
b
) // a ∪ b; a and b are untouched
  • 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
FactoryChoose whenCost
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 idtwo 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 mixone 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

{"v":1,"box":[73.5556,94.1597,1043,437.3555],"x":{"s":"log","lim":[0.607097442198,107949.721815],"inv":false,"g":0,"t":"IDs present in a span of 65,536","tk":[[1,"1"],[16,"16"],[256,"256"],[4096,"4,096"],[65536,"65,536"]],"b":10},"y":{"s":"log","lim":[1.37554181814,11910.9428619],"inv":false,"g":0,"tk":[[2,"2"],[8,"8"],[32,"32"],[128,"128"],[512,"512"],[2048,"2,048"],[8192,"8,192"]],"b":10},"ti":"Roaring stays smaller than dense until 4,096 IDs, then matches it","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,8192,65536,8192],"p":[113.58,423.19,224.75,370.71,335.93,318.23,447.1,265.76,558.28,213.28,669.45,160.8,780.63,108.33,891.8,108.33,1002.98,108.33]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 1 16 256 4,096 65,536 IDs present in a span of 65,536 2 8 32 128 512 2,048 8,192 Dense bitset: 8,192 bytes at every count Array becomes a bitmap 2 bytes, 4,096× less than dense Roaring payload model (bytes) Roaring stays smaller than dense until 4,096 IDs, then matches it
{"v":1,"box":[73.5556,122.3921,587.256,437.3555],"x":{"s":"log","lim":[0.607097442198,107949.721815],"inv":false,"g":0,"t":"IDs present in a span of 65,536","tk":[[1,"1"],[16,"16"],[256,"256"],[4096,"4,096"],[65536,"65,536"]],"b":10},"y":{"s":"log","lim":[1.37554181814,11910.9428619],"inv":false,"g":0,"tk":[[2,"2"],[8,"8"],[32,"32"],[128,"128"],[512,"512"],[2048,"2,048"],[8192,"8,192"]],"b":10},"ti":"Roaring stays smaller than dense until\n4,096 IDs, then matches it","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,8192,65536,8192],"p":[94.76,424.35,153.67,376.19,212.58,328.03,271.5,279.87,330.41,231.71,389.32,183.55,448.23,135.4,507.14,135.4,566.05,135.4]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 1 16 256 4,096 65,536 IDs present in a span of 65,536 2 8 32 128 512 2,048 8,192 Dense bitset: 8,192 bytes at every count Array becomes a bitmap 2 bytes, 4,096× less than dense Roaring payload model (bytes) Roaring stays smaller than dense until 4,096 IDs, then matches it
  • 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 against knotkit/bitset in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
roaringBitsetBitsetBitset 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.
denseBitsetBitsetBitset 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
MemberCost
sizeO(1)
hasO(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
addO(log c + n) array container, O(log c) bitmap container
deleteO(log c + n) array container, O(log c) bitmap container
addRangeO(chunks in span)
deleteRangeO(chunks in span)
countRangeO(log c + chunks in span)
addAllO(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
deleteAllO(k log k) to stage a generic operand, then one pass per touched chunk
retainAllO(c + k log k)
equalsO(min c)
isSubsetOfO(min c)
isDisjointFromO(min c), stops at the first shared chunk
intersectionSizeO(min c)
atO(c), from the nearer end
rankO(c), from the nearer end
ceilingO(c)
floorO(log c)
valuesO(size), O(1) per step
keysO(size), O(1) per step
[Symbol.iterator]O(size), O(1) per step
clearO(1)
denseBitset 22 members
MemberCost
sizeO(1)
hasO(1)
addO(1) amortized
deleteO(1); the trailing-word trim is deferred to the next read that walks the span
addRangeO((end - start) / 32)
deleteRangeO((end - start) / 32)
countRangeO((end - start) / 32)
addAllO(k)
deleteAllO(k)
retainAllO(maxId / 32 + k log k)
equalsO(min maxId / 32)
isSubsetOfO(min maxId / 32)
isDisjointFromO(min maxId / 32), stops at the first shared word
intersectionSizeO(min maxId / 32)
atO(maxId / 32), from the nearer end
rankO(maxId / 32), from the nearer end
ceilingO(maxId / 32)
floorO(maxId / 32)
valuesO(maxId / 32), O(1) per step
keysO(maxId / 32), O(1) per step
[Symbol.iterator]O(maxId / 32), O(1) per step
clearO(1)

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

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
If you need to…Use instead
a plain set over arbitrary keys, or over ids beyond 2^32 - 1Set or Map
membership over unbounded values where a small false-positive rate is acceptableknotkit/scalar-sketch
read a set as it was at an earlier point while it keeps changingknotkit/snapshot-set
a boolean flag per vertex you already index by number, where membership is the only questiona pre-sized Uint8Array, as problems/mst and problems/tsp do
track which elements are connected and merge groupsknotkit/disjoint-set
persist the set in a format another implementation readsyour own encoder: the binary artifact is Knotkit's own and is not RoaringFormatSpec-compatible

Measured by the suite in 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.

Prompt · knotkit/bitset
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/