typescript / expert
Snippet
Type-Safe Bitwise Mask Generation for High-Speed Audit Logging
Combines nominal type branding with raw binary bitwise bitmasks. This delivers nanosecond-level privilege evaluation performance while preventing arbitrary un-branded numbers from being passed into security audits.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type FlagBitmask<N extends number> = number & { readonly __brand: N };enum AuditFlags {READ = 1 << 0,WRITE = 1 << 1,DELETE = 1 << 2,ADMIN = 1 << 3,}function combineFlags<F extends AuditFlags[]>(...flags: F): FlagBitmask<number> {return flags.reduce((acc, flag) => acc | flag, 0) as FlagBitmask<number>;}function hasPermission(mask: FlagBitmask<number>, flag: AuditFlags): boolean {return (mask & flag) === flag;}
Breakdown
1
type FlagBitmask<N extends number> = number & { readonly __brand: N };
Creates a nominal brand wrapper around primitive numbers for bitmask type safety.
2
return flags.reduce((acc, flag) => acc | flag, 0) as ...
Performs fast bitwise OR aggregation of flags into a single integer representation.
3
return (mask & flag) === flag;
Executes CPU-native bitwise AND mask verification for sub-nanosecond access evaluation.