Formula Student Autonomous Systems
The code for the main driverless system
Loading...
Searching...
No Matches
circular_buffer.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <stdexcept>
5#include <vector>
6
7template <typename T>
9public:
10 explicit CircularBuffer(size_t capacity = 0)
12
13 void set_capacity(size_t capacity) {
15 buffer_.resize(capacity);
16 clear();
17 }
18
19 void clear() {
20 head_ = 0;
21 size_ = 0;
22 }
23
24 inline size_t size() const { return size_; }
25 inline size_t capacity() const { return capacity_; }
26 inline bool empty() const { return size_ == 0; }
27 inline bool full() const { return size_ == capacity_; }
28
30 void push(const T& item) {
31 if (capacity_ == 0) return;
32
33 buffer_[head_] = item;
34 head_ = (head_ + 1) % capacity_;
35
36 if (size_ < capacity_) size_++;
37 }
38
40 const T& latest() const {
41 if (size_ == 0) throw std::out_of_range("CircularBuffer::latest - buffer empty");
42
43 size_t index = (head_ + capacity_ - 1) % capacity_;
44 return buffer_[index];
45 }
46
48 const T& from_end(size_t i) const {
49 if (i >= size_) throw std::out_of_range("CircularBuffer::from_end - index too large");
50
51 size_t index = (head_ + capacity_ - 1 - i) % capacity_;
52 return buffer_[index];
53 }
54
56 const T& operator[](size_t index) const {
57 if (index >= size_) throw std::out_of_range("CircularBuffer::operator[] - index too large");
58
59 size_t real_index = (head_ + capacity_ - size_ + index) % capacity_;
60 return buffer_[real_index];
61 }
62
63private:
64 size_t capacity_;
65 size_t head_;
66 size_t size_;
67 std::vector<T> buffer_;
68};
void set_capacity(size_t capacity)
const T & from_end(size_t i) const
Access i-th element from the end (0 = latest, 1 = previous, ...)
bool full() const
CircularBuffer(size_t capacity=0)
void push(const T &item)
Add item into circular buffer.
size_t size() const
bool empty() const
std::vector< T > buffer_
const T & operator[](size_t index) const
Iterate raw access.
const T & latest() const
Access the most recent item.
size_t capacity() const