aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--libs/kstd/kstd/ring_buffer.hpp18
-rw-r--r--libs/kstd/kstd/ring_buffer.tests.cpp10
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