From 058136e4e99b99dfa932941fc632b776ff1b590b Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 2 Oct 2026 12:59:43 +0200 Subject: kstd: ring_buffer: implement try_push_back() --- libs/kstd/kstd/ring_buffer.hpp | 18 ++++++++++++++++++ libs/kstd/kstd/ring_buffer.tests.cpp | 10 ++++++++++ 2 files changed, 28 insertions(+) diff --git a/libs/kstd/kstd/ring_buffer.hpp b/libs/kstd/kstd/ring_buffer.hpp index 755ebbf6..af70e991 100644 --- a/libs/kstd/kstd/ring_buffer.hpp +++ b/libs/kstd/kstd/ring_buffer.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -516,6 +517,23 @@ namespace kstd m_read_index = (m_read_index + 1) % capacity(); } + //! Try to add an element to the end of this ring buffer. + //! + //! @param value The value to ad dto the end of this ring buffer. + //! @return @p true iff. the buffer had space for the value, @p false otherwise. + template + requires(std::same_as>) + constexpr auto try_push_back(PushedType && value) -> bool + { + if (m_size >= capacity()) + { + return false; + } + + push_back(std::forward(value)); + return true; + } + //! @} private: diff --git a/libs/kstd/kstd/ring_buffer.tests.cpp b/libs/kstd/kstd/ring_buffer.tests.cpp index 3da3f7ea..0b332494 100644 --- a/libs/kstd/kstd/ring_buffer.tests.cpp +++ b/libs/kstd/kstd/ring_buffer.tests.cpp @@ -1100,6 +1100,11 @@ SCENARIO("Ring Buffer modifiers", "[kstd][ring_buffer]") REQUIRE_THAT(buffer, Catch::Matchers::RangeEquals({5, 6, 7, 8, 9})); } } + + THEN("trying to push an element is successful") + { + REQUIRE(buffer.try_push_back(1)); + } } GIVEN("A ring buffer with a capacity of 5 containing 3 elements") @@ -1292,5 +1297,10 @@ SCENARIO("Ring Buffer modifiers", "[kstd][ring_buffer]") REQUIRE(kstd::tests::static_copy_move_tracker::move_assignment_call_count == 1); } } + + THEN("trying to push an element fails") + { + REQUIRE_FALSE(buffer.try_push_back(kstd::tests::static_copy_move_tracker{})); + } } } \ No newline at end of file -- cgit v1.2.3