From 3d2b027d86ca65975c19a26968851dc50e142849 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Wed, 30 Sep 2026 15:42:50 +0200 Subject: kstd: ring_buffer: implement size() --- libs/kstd/kstd/ring_buffer.hpp | 13 +++++++++++++ libs/kstd/kstd/ring_buffer.tests.cpp | 5 +++++ 2 files changed, 18 insertions(+) (limited to 'libs/kstd') diff --git a/libs/kstd/kstd/ring_buffer.hpp b/libs/kstd/kstd/ring_buffer.hpp index a25e37b7..0e54c070 100644 --- a/libs/kstd/kstd/ring_buffer.hpp +++ b/libs/kstd/kstd/ring_buffer.hpp @@ -34,6 +34,19 @@ namespace kstd return m_head == m_tail; } + //! Get the size of this ring buffer. + //! + //! @return The number of elements currently stored in this ring buffer. + [[nodiscard]] constexpr auto size() const noexcept -> size_type + { + if (m_head >= m_tail) + { + return m_head - m_tail; + } + + return capacity() - m_tail + m_head; + } + //! Get the maximum number of elements this ring buffer can hold. //! //! Due to ring_buffer being a fixed-size container, this function will return the same value as capacity. This diff --git a/libs/kstd/kstd/ring_buffer.tests.cpp b/libs/kstd/kstd/ring_buffer.tests.cpp index 37243014..6e936248 100644 --- a/libs/kstd/kstd/ring_buffer.tests.cpp +++ b/libs/kstd/kstd/ring_buffer.tests.cpp @@ -20,6 +20,11 @@ SCENARIO("Ring Buffer initialization and construction", "[ring_buffer]") REQUIRE(buffer.empty()); } + THEN("the size is 0") + { + REQUIRE(buffer.size() == 0); + } + THEN("the maximum size is equal to the capacity") { REQUIRE(buffer.max_size() == buffer.capacity()); -- cgit v1.2.3