--- id: wiki-2026-0508-index-masking title: Index Masking category: 10_Wiki/Topics status: verified canonical_id: self aliases: [Bitmask Index, Power-of-Two Masking] duplicate_of: none source_trust_level: A confidence_score: 0.9 verification_status: applied tags: [optimization, low-level, ring-buffer, hash] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: C/C++/Rust/JavaScript framework: General --- # Index Masking ## 매 한 줄 > **"매 capacity 가 power-of-two 일 때 `% N` 의 `& (N-1)` replacement"**. 매 modulo 의 expensive (CPU cycle 10-30) 의 single-cycle `AND` 로 대체. Ring buffer, hash table bucket, fixed-size LRU, lock-free queue 의 hot path 의 universal trick. CPU branch predictor 와 cache line 의 friendly. ## 매 핵심 ### 매 정확성 조건 - N 이 power-of-two: `2^k`. - `index % N == index & (N - 1)` (unsigned 또는 non-negative). - `N - 1` 이 모든 lower bit 의 1 의 mask. ### 매 대표 사용 처 - Ring buffer / circular queue. - Open-addressing hash table bucket index. - Game loop frame index modulo history size. - Hardware register address calc. - Lock-free SPSC/MPMC queue (Disruptor pattern). ### 매 응용 1. LMAX Disruptor (Java) — sequence & ringMask. 2. Linux kernel ringbuffer. 3. Redis hash table — sizemask. 4. V8 hidden class transitions table. ## 💻 패턴 ### Basic ring buffer (C) ```c #define RB_CAP 1024 // must be power of two typedef struct { int data[RB_CAP]; uint32_t head, tail; // free-running counters } RingBuf; static inline void rb_push(RingBuf *r, int v) { r->data[r->head & (RB_CAP - 1)] = v; r->head++; } static inline int rb_pop(RingBuf *r) { int v = r->data[r->tail & (RB_CAP - 1)]; r->tail++; return v; } ``` ### TypeScript fixed-size circular log ```typescript class CircularLog { private buf: (T | undefined)[] private mask: number private head = 0 constructor(capacityPow2: number) { if ((capacityPow2 & (capacityPow2 - 1)) !== 0) throw new Error('capacity must be power of two') this.buf = new Array(capacityPow2) this.mask = capacityPow2 - 1 } push(v: T) { this.buf[this.head & this.mask] = v this.head++ } recent(n: number): T[] { const out: T[] = [] for (let i = 0; i < n; i++) { const v = this.buf[(this.head - 1 - i) & this.mask] if (v !== undefined) out.push(v) } return out } } ``` ### Round-up to next power of two ```c uint32_t next_pow2(uint32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1; } ``` ### Hash table bucket ```rust struct Map { buckets: Vec>, mask: usize, } impl Map { fn bucket(&self, k: &K) -> usize { let mut h = DefaultHasher::new(); k.hash(&mut h); (h.finish() as usize) & self.mask // mask = capacity - 1 } } ``` ### SPSC lock-free (Disruptor-style) ```c // producer void produce(RingBuf *r, int v) { uint32_t h = atomic_load(&r->head); while (h - atomic_load(&r->tail) >= RB_CAP) cpu_relax(); // full r->data[h & (RB_CAP - 1)] = v; atomic_store(&r->head, h + 1); } ``` ### Branch-free wrap (negative-safe) ```c // for signed wrap, use bit-and after cast int idx = ((int)(counter) & ((int)CAP - 1)); // counter must be non-negative ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | Hot path, capacity 가 control 가능 | Power-of-2 + masking | | Capacity 가 user-input arbitrary | `%` (or round up to pow2) | | Capacity 가 dynamic resize | resize 시 `mask` recompute | | Signed counter | unsigned cast 또는 modulo | | Hardware-aligned (cache line) | pow2 + alignment 조합 | **기본값**: 매 ring/hash table 는 power-of-two + bitmask. 매 capacity 의 dynamic 이면 round-up. ## 🔗 Graph - 응용: [[Object Pooling (오브젝트 풀링)]] - Adjacent: [[SharedArrayBuffer로 스레드 간 메모리 공유 효율 높이기]] · [[Pointer Compression]] ## 🤖 LLM 활용 **언제**: 매 high-throughput data structure, lock-free queue, HFT, game engine frame loop. **언제 X**: capacity 의 control 안 되거나 readability priority 인 일반 application code. ## ❌ 안티패턴 - **Non-pow2 size 에 mask 적용**: 매 silent index out-of-range, data corruption. - **Signed negative index 의 masking**: `-1 & (N-1)` 의 N-1 이 됨 → 매 unsigned cast 또는 `((i % N) + N) % N` pattern. - **Capacity 1 의 mask 0**: 매 always index 0, degenerate. - **Premature application**: 매 측정 없이 micro-optimization. 매 hot path 만 의 적용. ## 🧪 검증 / 중복 - Verified (Hacker's Delight Ch.3, LMAX Disruptor paper, Linux kfifo source, Redis dict.c). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — power-of-2 masking patterns + ring/hash applications |