COROIO: coroio/actors/queue.hpp Source File
COROIO
Loading...
Searching...
No Matches
queue.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <vector>
4
47
48namespace NNet {
49namespace NActors {
50
62template<typename T>
68 TUnboundedVectorQueue(size_t capacity = 16)
69 : Data(RoundUpToPowerOfTwo(capacity))
70 , LastIndex(Data.size() - 1)
71 { }
72
77 void Push(T&& item) {
78 EnsureCapacity();
79 Data[Tail] = std::move(item);
80 Tail = (Tail + 1) & LastIndex;
81 }
82
88 T& Front() {
89 return Data[Head];
90 }
91
96 void Pop() {
97 Head = (Head + 1) & LastIndex;
98 }
99
104 size_t Size() const {
105 return (Data.size() + Tail - Head) & LastIndex;
106 }
107
112 bool Empty() const {
113 return Head == Tail;
114 }
115
116private:
117 static size_t RoundUpToPowerOfTwo(size_t value) {
118 size_t power = 1;
119 while (power < value) {
120 power <<= 1;
121 }
122 return power;
123 }
124
125 void EnsureCapacity() {
126 if (Size() == Data.size() - 1) [[unlikely]] {
127 std::vector<T> newData(Data.size() * 2);
128 auto size = Size();
129 for (size_t i = 0; i < size; ++i) {
130 newData[i] = std::move(Data[(Head + i) & LastIndex]);
131 }
132 Data = std::move(newData);
133 Head = 0;
134 Tail = size;
135 LastIndex = Data.size() - 1;
136 }
137 }
138
139 std::vector<T> Data;
140 size_t Head = 0;
141 size_t Tail = 0;
142 size_t LastIndex = 0;
143};
144
145} // namespace NActors
146} // namespace NNet
size_t Size() const
Get current number of elements in the queue.
Definition queue.hpp:104
T & Front()
Get reference to the front element.
Definition queue.hpp:88
void Push(T &&item)
Add element to the back of the queue.
Definition queue.hpp:77
TUnboundedVectorQueue(size_t capacity=16)
Construct queue with initial capacity.
Definition queue.hpp:68
void Pop()
Remove the front element from the queue.
Definition queue.hpp:96
bool Empty() const
Check if the queue is empty.
Definition queue.hpp:112