Szymon Dompke | daeddc7 | 2022-10-13 18:19:27 +0200 | [diff] [blame] | 1 | #include <cstddef> |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 2 | #include <vector> |
| 3 | |
| 4 | template <class T> |
| 5 | class CircularVector |
| 6 | { |
| 7 | public: |
Krzysztof Grobelny | 493e62e | 2022-02-14 10:55:50 +0100 | [diff] [blame] | 8 | explicit CircularVector(std::vector<T>& externalVec, size_t maxSizeIn) : |
| 9 | vec(externalVec), maxSize(maxSizeIn) |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 10 | {} |
| 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 Grobelny | a8182be | 2022-07-04 11:26:20 +0200 | [diff] [blame] | 57 | size_t size() const |
| 58 | { |
| 59 | return maxSize; |
| 60 | } |
| 61 | |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 62 | private: |
Krzysztof Grobelny | 493e62e | 2022-02-14 10:55:50 +0100 | [diff] [blame] | 63 | std::vector<T>& vec; |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 64 | size_t maxSize = 0; |
| 65 | size_t idx = 0; |
Szymon Dompke | 3eb5686 | 2021-09-20 15:32:04 +0200 | [diff] [blame] | 66 | }; |