DeutschGitHub
partialpackages/bit-mask/src

Bit Mask

@ralphschuler/bit-mask

Manages validated independent feature bits through a public API.

flagsbitwisecompact state

01 · Problem

What is it for?

A compact mask is useful only if each flag occupies a distinct bit and invalid masks are rejected.

02 · Mental model

How should you think about it?

Enable with OR, disable with AND plus complement, and inspect with AND.

In this repository

Manages validated independent feature bits through a public API. Number bitwise operations support positive single bits through bit 30. Wider masks need BigInt.

03 · Control flow

What happens in which order?

  1. Collect valid powers of two.
  2. Validate a requested flag.
  3. Set or clear that bit.
  4. Read the bit without changing the mask.

04 · Building blocks

The important contracts

BitwiseFeatureFlagsOwn independent declared feature bits.
enableFlag / disableFlag / isFlagEnabledValidate and manipulate one declared single-bit flag.

05 · Build it yourself

Implement a small core

Start with this small independent implementation, then use the steps below to make its contract explicit.

  1. Collect valid powers of two.
  2. Validate a requested flag.
  3. Set or clear that bit.
  4. Read the bit without changing the mask.
Concept sketch · may reference omitted helpers
class Flags {
  private mask = 0;
  constructor(private allowed: ReadonlySet<number>) {}

  private check(flag: number) {
    if (!this.allowed.has(flag)) throw new RangeError("Unknown flag");
  }
  enable(flag: number) { this.check(flag); this.mask |= flag; }
  disable(flag: number) { this.check(flag); this.mask &= ~flag; }
  has(flag: number) { this.check(flag); return (this.mask & flag) === flag; }
  value() { return this.mask; }
}

06 · Verify

What should you test?

  • Test enabling, disabling and independent flags.
  • Reject compound values and enum reverse names.
  • Test the supported highest bit.

Try it yourself

Turn the first verification claim into a failing test, implement the smallest fix, then add a boundary case.

Test enabling, disabling and independent flags.

Compare your approach

Your check should fail when the stated invariant is deliberately broken, and pass again after the fix. Keep setup deterministic and assert an observable result.

07 · Limits

Trade-offs and failure modes

  • JavaScript bitwise Number operations use signed 32-bit integers.
  • Use BigInt for wider masks.
  • A zero mask represents no flags.
Important

Number bitwise operations support positive single bits through bit 30. Wider masks need BigInt.

08 · Keep exploring

Source code and related ideas

yarn tsx packages/bit-mask/examples/basic.ts