aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--libs/kstd/kstd/ring_buffer.hpp17
-rw-r--r--libs/kstd/kstd/ring_buffer.tests.cpp20
2 files changed, 26 insertions, 11 deletions
diff --git a/libs/kstd/kstd/ring_buffer.hpp b/libs/kstd/kstd/ring_buffer.hpp
index 92605fc2..48f4da0d 100644
--- a/libs/kstd/kstd/ring_buffer.hpp
+++ b/libs/kstd/kstd/ring_buffer.hpp
@@ -186,7 +186,7 @@ namespace kstd
}
std::ranges::for_each(std::views::iota(0uz, count), [&](auto i) { m_storage.construct(i); });
- m_write_index = count % capacity();
+ m_size = count;
}
//! Construct a ring buffer with a given number of copies of a given value.
@@ -201,7 +201,7 @@ namespace kstd
}
std::ranges::for_each(std::views::iota(0uz, count), [&](auto i) { m_storage.construct(i, value); });
- m_write_index = count % capacity();
+ m_size = count;
}
//! @}
@@ -314,7 +314,7 @@ namespace kstd
//! @return @p true iff. this ring buffer is empty, @p false otherwise.
[[nodiscard]] constexpr auto empty() const noexcept -> bool
{
- return m_write_index == m_read_index;
+ return m_size == 0;
}
//! Get the size of this ring buffer.
@@ -322,12 +322,7 @@ namespace kstd
//! @return The number of elements currently stored in this ring buffer.
[[nodiscard]] constexpr auto size() const noexcept -> size_type
{
- if (m_write_index >= m_read_index)
- {
- return m_write_index - m_read_index;
- }
-
- return capacity() - (m_read_index - m_write_index);
+ return m_size;
}
//! Get the maximum number of elements this ring buffer can hold.
@@ -375,8 +370,8 @@ namespace kstd
//! The underlying storage for the elements of this ring buffer.
bits::basic_storage<value_type, Capacity> m_storage{};
- //! The index of the next element to be written.
- size_type m_write_index{};
+ //! The current number of elements in the buffer.
+ size_type m_size{};
//! The index of the first element to be read.
size_type m_read_index{};
};
diff --git a/libs/kstd/kstd/ring_buffer.tests.cpp b/libs/kstd/kstd/ring_buffer.tests.cpp
index a118c2c3..bff8f804 100644
--- a/libs/kstd/kstd/ring_buffer.tests.cpp
+++ b/libs/kstd/kstd/ring_buffer.tests.cpp
@@ -204,6 +204,26 @@ SCENARIO("Ring Buffer initialization and construction", "[kstd][ring_buffer]")
}
}
+ GIVEN("A full buffer")
+ {
+ auto buffer = kstd::ring_buffer<int, 5>{5};
+
+ THEN("the capacity is 5")
+ {
+ REQUIRE(buffer.capacity() == 5);
+ }
+
+ THEN("the buffer is not empty")
+ {
+ REQUIRE_FALSE(buffer.empty());
+ }
+
+ THEN("the size is equal to the capacity")
+ {
+ REQUIRE(buffer.size() == buffer.capacity());
+ }
+ }
+
WHEN("constructing by n-value-initialized constructor using a capacity of 5")
{
auto buffer = kstd::ring_buffer<int, 5>{3};