blob: 693ac959086158e7db69638c41fc87067bd1d48e [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:
Parker Schuhfea48582017-03-11 20:15:32 -080014 static constexpr size_t kBufferSize = buffer_size;
15
Parker Schuhecd057f2017-03-11 20:03:01 -080016 RingBuffer() {}
17
18 // Add an item to the RingBuffer, overwriting the oldest element if necessary
19 void Push(const Data &data) {
20 if (full()) {
21 data_[oldest_] = data;
22 oldest_ = (oldest_ + 1) % buffer_size;
23 } else {
24 data_[(oldest_ + size_) % buffer_size] = data;
25 ++size_;
26 }
27 }
28
Parker Schuh208a58d2017-04-12 20:51:38 -070029 void Shift() {
30 oldest_ = (oldest_ + 1) % buffer_size;
31 --size_;
32 }
33
Parker Schuhecd057f2017-03-11 20:03:01 -080034 // Return the value of the index requested, adjusted so that the RingBuffer
Parker Schuh208a58d2017-04-12 20:51:38 -070035 // contains the oldest element first and the newest last.
Parker Schuhecd057f2017-03-11 20:03:01 -080036 Data &operator[](size_t index) {
37 return data_[(oldest_ + index) % buffer_size];
38 }
39
40 const Data &operator[](size_t index) const {
41 return data_[(oldest_ + index) % buffer_size];
42 }
43
44 // Returns the capacity of the RingBuffer
45 size_t capacity() const { return buffer_size; }
46
47 // Returns the number of elements stored in the RingBuffer
48 size_t size() const { return size_; }
49
50 // Is the RingBuffer empty or full?
51 bool empty() const { return size_ == 0; }
52
53 bool full() const { return size_ == buffer_size; }
54
55 private:
56 ::std::array<Data, buffer_size> data_;
57
58 // Oldest contains the oldest item added to the RingBuffer which will be the
59 // next one to be overwritten
60 size_t oldest_ = 0;
61 size_t size_ = 0;
62};
63
64} // namespace aos
65
66#endif // AOS_COMMON_RING_BUFFER_H_