@piyawasin/byte-flags
Version:
A lightweight, type-safe utility library for efficiently storing and managing boolean flags in compact numeric values (8, 16, or 32 bits). Perfect for permission systems, feature flags, status tracking, and any scenario requiring compact boolean storage w
60 lines (59 loc) • 2.29 kB
TypeScript
import { BaseFlags } from "./BaseFlags";
import type { FlagsWithFlags } from "./types";
/**
* Efficiently stores and manages up to 8 boolean flags in a single byte (8-bit value).
*
* Ideal for permission systems, feature flags, or status tracking where compact
* serialization is needed. Flag names are fixed at creation for type safety.
*
* @example
* // Recommended usage with type safety:
* const flags = createByteFlags('read', 'write', 'execute', 'admin', 'guest');
* flags.admin = true; // TypeScript knows this is a boolean
*
* @see {@link createByteFlags} for better TypeScript support
*/
export declare class ByteFlags extends BaseFlags {
private static readonly _MAX_FLAGS;
private static readonly _MAX_VALUE;
protected readonly MAX_FLAGS = 8;
protected readonly MAX_VALUE = 255;
/**
* Create a new ByteFlags instance with the specified flag names
* @param flagNames Names of flags to initialize (1-8 flags)
* @throws Error if more than 8 flags are provided or if flag names are invalid
*/
constructor(...flagNames: string[]);
/**
* Convert the flags to a byte value (0-255)
* @returns Byte representation of all flags
*/
toByte(): number;
/**
* Load flags from a byte value
* @param b Byte value to load (0-255)
* @returns This instance for chaining
* @throws Error if the byte value is invalid
*/
fromByte(b: number): this;
/**
* Create a ByteFlags instance from a JSON string
* @param json JSON string or object from toJSON()
* @returns New ByteFlags instance
* @throws Error if JSON is invalid or flags don't match
*/
static fromJSON(json: string | object): ByteFlags;
}
/**
* Creates a type-safe ByteFlags instance with the specified flag names
* @example
* // Basic usage
* const flags = createByteFlags('read', 'write', 'admin', 'guest');
* flags.admin = true; // TypeScript knows this is a boolean
*
* // With explicit type
* type AppFlags = 'darkMode' | 'notifications' | 'analytics';
* const features = createByteFlags<AppFlags>('darkMode', 'notifications', 'analytics');
* features.darkMode = true; // OK
*/
export declare function createByteFlags<T extends string>(...flagNames: T[]): FlagsWithFlags<T, ByteFlags>;