确保 capacity ispow2

This commit is contained in:
2026-08-10 12:05:34 +08:00
parent d6d3800830
commit d2323a8f3b
2 changed files with 18 additions and 3 deletions
+16 -2
View File
@@ -22,14 +22,28 @@ c_size_t round_up_to_pow2(c_size_t v) {
return 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) { c_err_t c_FastByteRingBuffer_Init(c_FastByteRingBuffer_t* self, c_size_t capacity) {
if (!self || capacity == 0) return C_ERR_PARAM; if (!self || capacity == 0) return C_ERR_PARAM;
if (!c_FastByteRingBuffer_IsPow2(capacity)) {
return C_ERR_PARAM;
}
// 自動向上對齊,確保符合 Power of Two // 自動向上對齊,確保符合 Power of Two
self->capacity = round_up_to_pow2(capacity); self->capacity = capacity;
self->mask = self->capacity - 1; // 建立遮罩 self->mask = self->capacity - 1; // 建立遮罩
self->head = 0; self->head = 0;
self->tail = 0; self->tail = 0;
+2 -1
View File
@@ -244,8 +244,9 @@ static void test_conditional_is_validator(void) {
static void test_ring_buffer_memcmp(void) { static void test_ring_buffer_memcmp(void) {
c_FastByteRingBuffer_t ring; 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}; uint8_t payload[] = {0x00, 0x11, 0x22, 0x33};
c_FastByteRingBuffer_WriteBuffer(&ring, payload, 4); c_FastByteRingBuffer_WriteBuffer(&ring, payload, 4);