diff --git a/src/base/circlebuf.hh b/src/base/circlebuf.hh index bcfa91a277..77a05d7d35 100644 --- a/src/base/circlebuf.hh +++ b/src/base/circlebuf.hh @@ -167,7 +167,9 @@ class CircleBuf } // How much existing data will be overwritten? - const size_t overflow = std::max(0, used + len - maxSize); + const size_t total_bytes = used + len; + const size_t overflow = total_bytes > maxSize ? + total_bytes - maxSize : 0; // The iterator of the next byte to add. auto next_it = buffer.begin() + (start + used) % maxSize; // How much there is to copy to the end of the buffer. diff --git a/src/base/circlebuf.test.cc b/src/base/circlebuf.test.cc index 6b81b61ff9..2e1f6bd183 100644 --- a/src/base/circlebuf.test.cc +++ b/src/base/circlebuf.test.cc @@ -130,3 +130,22 @@ TEST(CircleBufTest, PointerWrapAround) EXPECT_EQ(buf.size(), 0); EXPECT_THAT(subArr(foo, 12), ElementsAreArray(data, 12)); } + +// Consume after produce empties queue +TEST(CircleBufTest, ProduceConsumeEmpty) +{ + CircleBuf buf(8); + char foo[1]; + + // buf is empty to begin with. + EXPECT_TRUE(buf.empty()); + // Produce one element. + buf.write(foo, 1); + EXPECT_FALSE(buf.empty()); + + // Read it back out. + buf.read(foo, 1); + + // Now the buffer should be empty again. + EXPECT_TRUE(buf.empty()); +}