| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include <array> |
| 7 |
#include <cstddef> |
| 8 |
#include <type_traits> |
| 9 |
#include <utility> |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
namespace Common |
| 17 |
{ |
| 18 |
template <class T, int N> |
| 19 |
class FixedSizeQueue |
| 20 |
{ |
| 21 |
public: |
| 22 |
void clear() |
| 23 |
{ |
| 24 |
if constexpr (!std::is_trivial_v<T>) |
| 25 |
{ |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
while (count > 0) |
| 30 |
pop(); |
| 31 |
} |
| 32 |
|
| 33 |
head = 0; |
| 34 |
tail = 0; |
| 35 |
count = 0; |
| 36 |
} |
| 37 |
|
| 38 |
void push(T t) |
| 39 |
{ |
| 40 |
if (count == N) |
| 41 |
head = (head + 1) % N; |
| 42 |
else |
| 43 |
count++; |
| 44 |
|
| 45 |
storage[tail] = std::move(t); |
| 46 |
tail = (tail + 1) % N; |
| 47 |
} |
| 48 |
|
| 49 |
template <class... Args> |
| 50 |
void emplace(Args&&... args) |
| 51 |
{ |
| 52 |
if (count == N) |
| 53 |
head = (head + 1) % N; |
| 54 |
else |
| 55 |
count++; |
| 56 |
|
| 57 |
storage[tail] = T(std::forward<Args>(args)...); |
| 58 |
tail = (tail + 1) % N; |
| 59 |
} |
| 60 |
|
| 61 |
void pop() |
| 62 |
{ |
| 63 |
if constexpr (!std::is_trivial_v<T>) |
| 64 |
storage[head] = {}; |
| 65 |
|
| 66 |
head = (head + 1) % N; |
| 67 |
count--; |
| 68 |
} |
| 69 |
|
| 70 |
T pop_front() |
| 71 |
{ |
| 72 |
T temp = std::move(front()); |
| 73 |
pop(); |
| 74 |
return temp; |
| 75 |
} |
| 76 |
|
| 77 |
T& front() noexcept { return storage[head]; } |
| 78 |
const T& front() const noexcept { return storage[head]; } |
| 79 |
size_t size() const noexcept { return count; } |
| 80 |
bool empty() const noexcept { return size() == 0; } |
| 81 |
|
| 82 |
private: |
| 83 |
std::array<T, N> storage{}; |
| 84 |
int head = 0; |
| 85 |
int tail = 0; |
| 86 |
|
| 87 |
int count = 0; |
| 88 |
}; |
| 89 |
} |