In high-frequency single-producer single-consumer (SPSC) lock-free ring buffers, converting a 64-bit monotonic sequence number into a physical buffer index via the integer modulo operator S % C introduces hardware divide latency (up to 20–40 CPU cycles).
When the queue capacity is strictly constrained to be a power of two (), the expensive modulo instruction can be replaced with a single-cycle bitwise AND:
Your Task
next_power_of_two(capacity: int) -> int that calculates the smallest power of two greater than or equal to capacity using branchless bitwise operations (for ).RingBufferIndexMapper class:
__init__(requested_capacity: int): rounds requested_capacity up to the next power of two and initializes the bitmask.get_index(sequence_number: int) -> int: maps sequence number to circular buffer index in time.Constraints
Examples
next_power_of_two(100) # returns 128
next_power_of_two(64) # returns 64
mapper = RingBufferIndexMapper(100) # capacity 128
mapper.get_index(130) # returns 130 & 127 = 2