Skip to content

Commit

Permalink
Fix CircularBuffer::reserve() to preserve front/back indices (#85)
Browse files Browse the repository at this point in the history
Android errors should be unrelated.
  • Loading branch information
dskyle authored and jredmondson committed Sep 19, 2018
1 parent c30ecaf commit 6092f49
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
10 changes: 6 additions & 4 deletions include/madara/utility/CircularBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,17 @@ class CircularBuffer
* be held at once. If more than that many elements are added to the back of
* the buffer, elements from the front will silently be removed.
**/
explicit CircularBuffer(size_t capacity)
: data_((T *)operator new(sizeof(T) * capacity)),
explicit CircularBuffer(size_t capacity, size_t initial_index = 0)
: front_(initial_index),
back_(initial_index),
data_((T *)operator new(sizeof(T) * capacity)),
cap_(capacity) {}

/**
* Copy constructor. Abides by typical semantics.
**/
CircularBuffer(const CircularBuffer &other)
: CircularBuffer(other.size())
: CircularBuffer(other.size(), other.front_)
{
for (const T &cur : other) {
emplace_back(cur);
Expand Down Expand Up @@ -111,7 +113,7 @@ class CircularBuffer
**/
void reserve(size_t size)
{
CircularBuffer tmp(size);
CircularBuffer tmp(size, front_);
while (!empty()) {
tmp.emplace_back(std::move(pop_front()));
}
Expand Down
21 changes: 19 additions & 2 deletions tests/test_circular_buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ void test_record_buffer()
{{0, 20}, {2, 22}});
test_history_vector<int>(rec.get_history(-5, 4),
{{0, 22}, {2, 24}});

LOG("Resized buffer to 6");
rec.set_history_capacity(6);
test_history_vector<int>(rec.get_history(),
{{3, 24}, {0, 21}, {1, 22}});

LOG("Resized buffer to 10");
rec.set_history_capacity(10);
test_history_vector<int>(rec.get_history(),
{{3, 24}, {0, 21}, {1, 22}});
}

template<typename Key>
Expand Down Expand Up @@ -231,8 +241,15 @@ void test_container()
v = buf.inspect(2,3);
test_consume_earliest<int>(v,{ {0,25},{1,26},{2,27} });

kb.set_history_capacity(key, 5);

v = buf.inspect(2,3);
test_consume_earliest<int>(v,{ {0,28},{1,29},{2,30} });

kb.set_history_capacity(key, 10);

v = buf.consume_many(1);
test_consume_earliest<int>(v,{ {0,23} });
test_consume_earliest<int>(v,{ {0,26} });

for (int i = 32; i < 45; ++i) {
kb.set(key, i);
Expand All @@ -241,7 +258,7 @@ void test_container()
size_t mydropped;
v = buf.consume_many(2,mydropped);

TEST_EQ(mydropped, 10UL);
TEST_EQ(mydropped, 7UL);
test_consume_earliest<int>(v,{ {0,35}, {1,36} });

std::vector<KnowledgeRecord> krvec;
Expand Down

0 comments on commit 6092f49

Please sign in to comment.