blob: 293c8170dd367b3702e062a309b3cc0b08eaa041 [file] [log] [blame]
Parker Schuhecd057f2017-03-11 20:03:01 -08001#ifndef AOS_COMMON_RING_BUFFER_H_
2#define AOS_COMMON_RING_BUFFER_H_
3
4#include <array>
5
6namespace aos {
7
8// This is a helper to keep track of some amount of recent data. As you push
9// data into the ring buffer, it gets stored. If the buffer becomes full, it
10// will start overwriting the oldest data.
11template <typename Data, size_t buffer_size>
12class RingBuffer {
13 public:
14 RingBuffer() {}
15
16 // Add an item to the RingBuffer, overwriting the oldest element if necessary
17 void Push(const Data &data) {
18 if (full()) {
19 data_[oldest_] = data;
20 oldest_ = (oldest_ + 1) % buffer_size;
21 } else {
22 data_[(oldest_ + size_) % buffer_size] = data;
23 ++size_;
24 }
25 }
26
27 // Return the value of the index requested, adjusted so that the RingBuffer
28 // contians the oldest element first and the newest last.
29 Data &operator[](size_t index) {
30 return data_[(oldest_ + index) % buffer_size];
31 }
32
33 const Data &operator[](size_t index) const {
34 return data_[(oldest_ + index) % buffer_size];
35 }
36
37 // Returns the capacity of the RingBuffer
38 size_t capacity() const { return buffer_size; }
39
40 // Returns the number of elements stored in the RingBuffer
41 size_t size() const { return size_; }
42
43 // Is the RingBuffer empty or full?
44 bool empty() const { return size_ == 0; }
45
46 bool full() const { return size_ == buffer_size; }
47
48 private:
49 ::std::array<Data, buffer_size> data_;
50
51 // Oldest contains the oldest item added to the RingBuffer which will be the
52 // next one to be overwritten
53 size_t oldest_ = 0;
54 size_t size_ = 0;
55};
56
57} // namespace aos
58
59#endif // AOS_COMMON_RING_BUFFER_H_