diff --git a/cKit/Foundation/c_FastByteRingBuffer.c b/cKit/Foundation/c_FastByteRingBuffer.c index e7dffe3..27820a9 100644 --- a/cKit/Foundation/c_FastByteRingBuffer.c +++ b/cKit/Foundation/c_FastByteRingBuffer.c @@ -22,14 +22,28 @@ c_size_t round_up_to_pow2(c_size_t v) { return v; } +C_STATIC_FORCE_INLINE +c_bool_t c_FastByteRingBuffer_IsPow2(c_size_t capacity) { + // A power of 2 must be greater than zero. + // The bitwise trick (capacity & (capacity - 1)) works because a power of 2 + // has exactly one bit set (e.g., 01000). Subtracting 1 flips all bits up to + // that set bit (e.g., 00111). Performing a bitwise AND yields exactly 0. + if (capacity == 0) { + return C_FALSE; + } + return ((capacity & (capacity - 1)) == 0) ? C_TRUE : C_FALSE; +} + /* ------------------------------------------------------------------------------------------------------------------ */ /* */ c_err_t c_FastByteRingBuffer_Init(c_FastByteRingBuffer_t* self, c_size_t capacity) { if (!self || capacity == 0) return C_ERR_PARAM; - + if (!c_FastByteRingBuffer_IsPow2(capacity)) { + return C_ERR_PARAM; + } // 自動向上對齊,確保符合 Power of Two - self->capacity = round_up_to_pow2(capacity); + self->capacity = capacity; self->mask = self->capacity - 1; // 建立遮罩 self->head = 0; self->tail = 0; diff --git a/cKit/Foundation/c_FastByteRingBuffer.t.c b/cKit/Foundation/c_FastByteRingBuffer.t.c index 63e0189..0444190 100644 --- a/cKit/Foundation/c_FastByteRingBuffer.t.c +++ b/cKit/Foundation/c_FastByteRingBuffer.t.c @@ -244,8 +244,9 @@ static void test_conditional_is_validator(void) { static void test_ring_buffer_memcmp(void) { c_FastByteRingBuffer_t ring; - assert(c_FastByteRingBuffer_Init(&ring, 6) == C_SUCCESS); // Capacity = 6 + assert(c_FastByteRingBuffer_Init(&ring, 6) == C_ERR_INVALID_PARAM); // Capacity = 6 + assert(c_FastByteRingBuffer_Init(&ring, 8) == C_SUCCESS); // Capacity = 6 uint8_t payload[] = {0x00, 0x11, 0x22, 0x33}; c_FastByteRingBuffer_WriteBuffer(&ring, payload, 4);