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
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
100 bool TryPop(T& item) {
101 if (Empty()) {
102 return false;
103 }
104 item = std::move(Data[Head]);
105 Head = (Head + 1) & LastIndex;
106 return true;
107 }
108
113 size_t Size() const {
114 return (Data.size() + Tail - Head) & LastIndex;
115 }
116
121 bool Empty() const {
122 return Head == Tail;
123 }
124
125private:
126 static size_t RoundUpToPowerOfTwo(size_t value) {
127 size_t power = 1;
128 while (power < value) {
129 power <<= 1;
130 }
131 return power;
132 }
133
134 void EnsureCapacity() {
135 if (Size() == Data.size() - 1) [[unlikely]] {
136 std::vector<T> newData(Data.size() * 2);
137 auto size = Size();
138 for (size_t i = 0; i < size; ++i) {
139 newData[i] = std::move(Data[(Head + i) & LastIndex]);
140 }
141 Data = std::move(newData);
142 Head = 0;
143 Tail = size;
144 LastIndex = Data.size() - 1;
145 }
146 }
147
148 std::vector<T> Data;
149 size_t Head = 0;
150 size_t Tail = 0;
151 size_t LastIndex = 0;
152};
153
154} // namespace NActors
155} // namespace NNet
Unbounded queue with automatic capacity growth.
Definition queue.hpp:63
size_t Size() const
Get current number of elements in the queue.
Definition queue.hpp:113
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:121