From 2a0e244b0af72a444e0a8caff6b86819fba1ed3a Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Mon, 18 Mar 2024 20:44:54 +0100 Subject: ring: add simple statically sized ring buffer --- test/ring.cc | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 test/ring.cc (limited to 'test') diff --git a/test/ring.cc b/test/ring.cc new file mode 100644 index 0000000..a42efaa --- /dev/null +++ b/test/ring.cc @@ -0,0 +1,93 @@ +#include + +#include + +#define LOG \ + if (false) { \ + } else \ + puts(__PRETTY_FUNCTION__) + +/// A helper sruct to count instances, copy- and move constructions. +struct m { + m() { + LOG; + ++cnt; + } + ~m() { + LOG; + --cnt; + } + m(const m&) { + LOG; + ++cnt; + ++cpy; + } + m(m&&) noexcept { + LOG; + ++cnt; + ++mov; + } + m& operator=(const m&) = delete; + m& operator=(m&&) = delete; + + static std::size_t cnt; + static std::size_t mov; + static std::size_t cpy; +}; + +std::size_t m::cnt = 0; +std::size_t m::mov = 0; +std::size_t m::cpy = 0; + +int main() { + { + ring r; + + assert(r.size() == 0); + assert(r.is_empty()); + assert(!r.is_full()); + + for (int i = 0; i < 10; ++i) { + bool ok = r.emplace(); + i < 8 ? assert(ok) : assert(!ok); + } + + assert(r.size() == 8); + assert(!r.is_empty()); + assert(r.is_full()); + +#if __cplusplus >= 201703L + auto v = r.take(); + assert(v.has_value()); + + assert(r.size() == 7); + assert(!r.is_empty()); + assert(!r.is_full()); +#endif + + assert(m::cnt == 8); + } + + assert(m::cnt == 0); + + m::mov = 0; + m::cpy = 0; + { + ring r; + + // Move construct m from an m rvalue reference. + assert(m::mov == 0); + r.push(m{}); + assert(m::mov == 1); + + // Copy construct m from an m lvalue reference. + m m; + assert(m::cpy == 0); + r.push(m); + assert(m::cpy == 1); + + assert(m::cnt == 3); + } + + assert(m::cnt == 0); +} -- cgit v1.2.3