From aaee8cab300311d624a9dc3032f77c89cfaaffc8 Mon Sep 17 00:00:00 2001 From: Yuri D'Elia Date: Sat, 22 Jul 2023 14:54:47 +0200 Subject: [PATCH] CircularIndex: optimize further for non-power-of-two sizes - Improve count() for non-power-of-two sizes by handling wrap-around - Improve full() to use always use count(), which is cheaper in both scenarios now --- src/hal/circular_buffer.h | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/hal/circular_buffer.h b/src/hal/circular_buffer.h index 4e24235..cebc0d5 100644 --- a/src/hal/circular_buffer.h +++ b/src/hal/circular_buffer.h @@ -28,9 +28,7 @@ public: /// @returns true if full inline bool full() const { - // alternative without wrap-around logic: - // return tail != head && mask(tail) == mask(head); - return ((index_t)(head - tail) % (size * 2)) == size; + return count() == size; } /// Reset the indexes to empty @@ -67,13 +65,9 @@ public: if constexpr (size_is_power2) return head - tail; else { - index_t i = tail; - index_t c = 0; - while (i != head) { - i = next(i); - ++c; - } - return c; + return head >= tail + ? (head - tail) + : (size * 2 + head) - tail; } }