确保 capacity ispow2
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user