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