blob: be13873e64a0ed6aef320360ab479f4fa537dd6e [file] [log] [blame]
Szymon Dompke3eb56862021-09-20 15:32:04 +02001#include <vector>
2
3template <class T>
4class CircularVector
5{
6 public:
Krzysztof Grobelny493e62e2022-02-14 10:55:50 +01007 explicit CircularVector(std::vector<T>& externalVec, size_t maxSizeIn) :
8 vec(externalVec), maxSize(maxSizeIn)
Szymon Dompke3eb56862021-09-20 15:32:04 +02009 {}
10
11 template <class... Args>
12 void emplace(Args&&... args)
13 {
14 if (maxSize == 0)
15 {
16 return;
17 }
18 if (vec.size() == maxSize)
19 {
20 vec.at(idx) = T(std::forward<Args>(args)...);
21 }
22 else
23 {
24 vec.emplace_back(std::forward<Args>(args)...);
25 }
26 idx = (idx + 1) == maxSize ? 0 : (idx + 1);
27 }
28
29 void clear()
30 {
31 vec.clear();
32 idx = 0;
33 }
34
35 void clearAndResize(size_t newMaxSize)
36 {
37 clear();
38 maxSize = newMaxSize;
39 }
40
41 bool isFull() const
42 {
43 return vec.size() == maxSize;
44 }
45
46 typename std::vector<T>::const_iterator begin() const
47 {
48 return vec.begin();
49 }
50
51 typename std::vector<T>::const_iterator end() const
52 {
53 return vec.end();
54 }
55
Krzysztof Grobelnya8182be2022-07-04 11:26:20 +020056 size_t size() const
57 {
58 return maxSize;
59 }
60
Szymon Dompke3eb56862021-09-20 15:32:04 +020061 private:
Krzysztof Grobelny493e62e2022-02-14 10:55:50 +010062 std::vector<T>& vec;
Szymon Dompke3eb56862021-09-20 15:32:04 +020063 size_t maxSize = 0;
64 size_t idx = 0;
Szymon Dompke3eb56862021-09-20 15:32:04 +020065};