diff options
| author | Felix Morgner <felix.morgner@ost.ch> | 2026-10-02 12:59:43 +0200 |
|---|---|---|
| committer | Felix Morgner <felix.morgner@ost.ch> | 2026-10-02 12:59:43 +0200 |
| commit | 058136e4e99b99dfa932941fc632b776ff1b590b (patch) | |
| tree | 459bb72e75deb9a645d981ff81c55a8115e159df | |
| parent | 555c181c042be054fb9574d8fc77d2663bd39d4f (diff) | |
| download | kernel-058136e4e99b99dfa932941fc632b776ff1b590b.tar.xz kernel-058136e4e99b99dfa932941fc632b776ff1b590b.zip | |
kstd: ring_buffer: implement try_push_back()
| -rw-r--r-- | libs/kstd/kstd/ring_buffer.hpp | 18 | ||||
| -rw-r--r-- | libs/kstd/kstd/ring_buffer.tests.cpp | 10 |
2 files changed, 28 insertions, 0 deletions
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 <algorithm> #include <compare> +#include <concepts> #include <cstddef> #include <iterator> #include <memory> @@ -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<typename PushedType> + requires(std::same_as<ValueType, std::remove_cvref_t<PushedType>>) + constexpr auto try_push_back(PushedType && value) -> bool + { + if (m_size >= capacity()) + { + return false; + } + + push_back(std::forward<PushedType>(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 |
