-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularBuffer.hpp
More file actions
37 lines (32 loc) · 983 Bytes
/
CircularBuffer.hpp
File metadata and controls
37 lines (32 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#pragma once
template<class T, size_t size>
class CircularBuffer {
private:
T buf[size];
size_t oldestIndex;
public:
CircularBuffer(const T& initValue);
void push(const T& element);
T& operator[](size_t index);
void clear();
};
template<class T, size_t size>
inline CircularBuffer<T, size>::CircularBuffer(const T& initValue) : oldestIndex(0) {
for (size_t i = 0; i < size; i++) {
buf[i] = initValue;
}
}
template<class T, size_t size>
inline void CircularBuffer<T, size>::push(const T& element) {
this->buf[this->oldestIndex] = element;
this->oldestIndex = ++this->oldestIndex % size;
}
template<class T, size_t size>
inline T& CircularBuffer<T, size>::operator[](size_t index) {
return this->buf[(this->oldestIndex - index - 1 + size) % size];
}
template<class T, size_t size>
inline void CircularBuffer<T, size>::clear(){
memset(this->buf, T(0), size);
this->oldestIndex = 0;
}