diff --git a/lockfree/spsc/ring_buf.hpp b/lockfree/spsc/ring_buf.hpp index 9af6c0b..22b28ac 100755 --- a/lockfree/spsc/ring_buf.hpp +++ b/lockfree/spsc/ring_buf.hpp @@ -62,6 +62,13 @@ template class RingBuf { public: RingBuf(); + + /** + * @brief Clears the ring buffer. + */ + void Clear(); + + /** * @brief Writes data to the ring buffer. * Should only be called from the producer thread. diff --git a/lockfree/spsc/ring_buf_impl.hpp b/lockfree/spsc/ring_buf_impl.hpp index 319d8e7..8f6c8c0 100644 --- a/lockfree/spsc/ring_buf_impl.hpp +++ b/lockfree/spsc/ring_buf_impl.hpp @@ -44,6 +44,12 @@ namespace spsc { template RingBuf::RingBuf() : _r(0U), _w(0U) {} +template +void RingBuf::Clear() { + _r = 0; + _w = 0; +} + template bool RingBuf::Write(const T *data, const size_t cnt) { /* Preload variables with adequate memory ordering */ diff --git a/tests/spsc/ring_buf.cpp b/tests/spsc/ring_buf.cpp index e1901b3..5dd8d7d 100644 --- a/tests/spsc/ring_buf.cpp +++ b/tests/spsc/ring_buf.cpp @@ -7,7 +7,6 @@ TEST_CASE("spsc::RingBuf - Get free with an empty buffer", "[rb_get_free_empty]") { lockfree::spsc::RingBuf const rb; - const float test_data[120] = {2.71828F}; REQUIRE(rb.GetFree() == 1024U - 1U); } @@ -319,6 +318,36 @@ TEST_CASE("spsc::RingBuf - Peek std::array", "[rb_peek_std_array]") { std::equal(test_data.begin(), test_data.end(), test_data_read.begin())); } +TEST_CASE("Get available after clear", "[rb_get_available_after_clear]") { + lockfree::spsc::RingBuf rb; + const std::array test_data = {0xE5U}; + + rb.Write(test_data); + rb.Clear(); + + REQUIRE(rb.GetAvailable() == 0); +} + +TEST_CASE("Get free after clear", "[rb_get_free_after_clear]") { + lockfree::spsc::RingBuf rb; + const std::array test_data = {0xE5U}; + + rb.Write(test_data); + rb.Clear(); + + REQUIRE(rb.GetFree() == 1024U -1U); +} + +TEST_CASE("Try to read after clear", "[rb_read_clear]") { + lockfree::spsc::RingBuf rb; + + uint64_t test_data_read[320] = {0}; + bool const read_success = rb.Read( + test_data_read, sizeof(test_data_read) / sizeof(test_data_read[0])); + + REQUIRE(!read_success); +} + TEST_CASE("spsc::RingBuf - Peek std::span", "[rb_peek_span]") { lockfree::spsc::RingBuf rb; const uint64_t test_data[320] = {0xE5U};