diff options
| -rw-r--r-- | libs/kstd/kstd/ring_buffer.hpp | 14 | ||||
| -rw-r--r-- | libs/kstd/kstd/ring_buffer.tests.cpp | 57 |
2 files changed, 71 insertions, 0 deletions
diff --git a/libs/kstd/kstd/ring_buffer.hpp b/libs/kstd/kstd/ring_buffer.hpp index 10ee334d..34f8a2d8 100644 --- a/libs/kstd/kstd/ring_buffer.hpp +++ b/libs/kstd/kstd/ring_buffer.hpp @@ -549,6 +549,20 @@ namespace kstd --m_size; } + //! Try to remove the first element in the buffer. + //! + //! @return @p true iff. an element was removed, @p false otherwise + [[nodiscard]] constexpr auto try_pop_front() noexcept(std::is_nothrow_destructible_v<value_type>) -> bool + { + if (empty()) + { + return false; + } + + pop_front(); + return true; + } + //! @} private: diff --git a/libs/kstd/kstd/ring_buffer.tests.cpp b/libs/kstd/kstd/ring_buffer.tests.cpp index 767e7422..889a0c36 100644 --- a/libs/kstd/kstd/ring_buffer.tests.cpp +++ b/libs/kstd/kstd/ring_buffer.tests.cpp @@ -1111,6 +1111,11 @@ SCENARIO("Ring Buffer modifiers", "[kstd][ring_buffer]") REQUIRE_THROWS_MATCHES(buffer.pop_front(), kstd::tests::os_panic, Catch::Matchers::Message("[KSTD] Tried to pop an element from an empty ring_buffer!")); } + + THEN("trying to pop an element fails") + { + REQUIRE_FALSE(buffer.try_pop_front()); + } } GIVEN("A ring buffer with a capacity of 5 containing 3 elements") @@ -1280,6 +1285,58 @@ SCENARIO("Ring Buffer modifiers", "[kstd][ring_buffer]") REQUIRE(buffer.empty()); } } + + THEN("trying to pop an element succeeds") + { + REQUIRE(buffer.try_pop_front()); + } + + WHEN("popping an element using try_pop_front") + { + kstd::tests::static_copy_move_tracker::reset(); + REQUIRE(buffer.try_pop_front()); + + THEN("the size is 2") + { + REQUIRE(buffer.size() == 2); + } + + THEN("the buffer is not empty") + { + REQUIRE_FALSE(buffer.empty()); + } + + THEN("there was one destructor call") + { + REQUIRE(kstd::tests::static_copy_move_tracker::dtor_call_count == 1); + REQUIRE(kstd::tests::static_copy_move_tracker::copy_ctor_call_count == 0); + REQUIRE(kstd::tests::static_copy_move_tracker::copy_assignment_call_count == 0); + REQUIRE(kstd::tests::static_copy_move_tracker::move_ctor_call_count == 0); + REQUIRE(kstd::tests::static_copy_move_tracker::move_assignment_call_count == 0); + } + } + + WHEN("popping 3 elements using try_pop_front") + { + CHECK(buffer.try_pop_front()); + CHECK(buffer.try_pop_front()); + CHECK(buffer.try_pop_front()); + + THEN("the size is 0") + { + REQUIRE(buffer.size() == 0); + } + + THEN("the buffer is empty") + { + REQUIRE(buffer.empty()); + } + + THEN("another attempt to pop an element fails") + { + REQUIRE_FALSE(buffer.try_pop_front()); + } + } } GIVEN("A full ring buffer of static operation trackers") |
