-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathbitset.ts
More file actions
73 lines (64 loc) · 2.09 KB
/
bitset.ts
File metadata and controls
73 lines (64 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// A packed alternative to Array<boolean>.
// Created with makeBitSet.
// All 32 bits in each array element are utilized, though of course the last
// element is only partially used if the "bit length" is not a multiple of 32.
// The original "bit length" is not remembered.
export type BitSet = Int32Array;
// 2^5 == 32.
export function makeBitSet(length: number): BitSet {
const lastIndex = length - 1;
const lastSlot = lastIndex >> 5;
const slotCount = lastSlot + 1;
return new Int32Array(slotCount);
}
export function setBit(bitSet: BitSet, bitIndex: number) {
const q = bitIndex >> 5;
const r = bitIndex & 0b11111;
if (q >= bitSet.length) {
throw new BitSetOutOfBoundsError(bitIndex);
}
bitSet[q] |= 1 << r;
}
export function clearBit(bitSet: BitSet, bitIndex: number) {
const q = bitIndex >> 5;
const r = bitIndex & 0b11111;
if (q >= bitSet.length) {
throw new BitSetOutOfBoundsError(bitIndex);
}
bitSet[q] &= ~(1 << r);
}
export function checkBit(bitSet: BitSet, bitIndex: number): boolean {
const q = bitIndex >> 5;
const r = bitIndex & 0b11111;
if (q >= bitSet.length) {
throw new BitSetOutOfBoundsError(bitIndex);
}
return (bitSet[q] & (1 << r)) !== 0;
}
export function combineTwoBitSetsWithAnd(a: BitSet, b: BitSet): BitSet {
const slotCount = a.length;
const result = new Int32Array(slotCount);
for (let i = 0; i < slotCount; i++) {
result[i] = a[i] & b[i];
}
return result;
}
export function combineTwoBitSetsWithOr(a: BitSet, b: BitSet): BitSet {
const slotCount = a.length;
const result = new Int32Array(slotCount);
for (let i = 0; i < slotCount; i++) {
result[i] = a[i] | b[i];
}
return result;
}
export class BitSetOutOfBoundsError extends Error {
override name = 'BitSetOutOfBoundsError';
bitIndex: number;
constructor(bitIndex: number) {
super(`Bit index ${bitIndex} is out of bounds`);
this.bitIndex = bitIndex;
}
}