Skip to content

Commit

Permalink
Ring buffer: Add index operator and tests (#99)
Browse files Browse the repository at this point in the history
Adds a new [] operator to access data at a specified index.
  • Loading branch information
pickledgator authored Jun 14, 2024
1 parent 9702424 commit cc14018
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions trellis/containers/ring_buffer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class RingBuffer {
}
}

const T& operator[](size_t index) const { return data_[(begin_ + index) % kArraySize]; }

class ConstIterator {
public:
using iterator_category = std::random_access_iterator_tag;
Expand Down
18 changes: 18 additions & 0 deletions trellis/containers/test/ring_buffer_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,22 @@ TEST(RingBuffer, PopFront) {
ASSERT_THAT(ring, IsEmpty());
}

TEST(RingBuffer, IndexOperator) {
auto ring = RingBuffer<int, 5>{};
ring.push_back(1);
ring.push_back(2);
ring.push_back(3);

// Test non-const access
EXPECT_EQ(ring[0], 1);
EXPECT_EQ(ring[1], 2);
EXPECT_EQ(ring[2], 3);

// Test const access
const auto& const_ring = ring;
EXPECT_EQ(const_ring[0], 1);
EXPECT_EQ(const_ring[1], 2);
EXPECT_EQ(const_ring[2], 3);
}

} // namespace trellis::containers

0 comments on commit cc14018

Please sign in to comment.