Files
2nd/10_Wiki/Topic_Programming/Programming & Language/Index Masking.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

4.8 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-index-masking Index Masking 10_Wiki/Topics verified self
Bitmask Index
Power-of-Two Masking
none A 0.9 applied
optimization
low-level
ring-buffer
hash
2026-05-10 pending
language framework
C/C++/Rust/JavaScript 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)

#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

class CircularLog<T> {
  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

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

struct Map<K, V> {
    buckets: Vec<Option<(K, V)>>,
    mask: usize,
}
impl<K: Hash + Eq, V> Map<K, V> {
    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)

// 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)

// 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