uvco 0.1
Loading...
Searching...
No Matches
bounded_queue.h
Go to the documentation of this file.
1// uvco (c) 2024 Lewin Bormann. See LICENSE for specific terms.
2
3#pragma once
4
5#include <concepts>
6#include <functional>
7#include <uv.h>
8
9#include "uvco/exception.h"
10
11#include <boost/assert.hpp>
12#include <utility>
13#include <vector>
14
15namespace uvco {
16
18
24template <typename T> class BoundedQueue {
25public:
26 explicit BoundedQueue(size_t capacity) { queue_.reserve(capacity); }
27
29 template <typename U>
30 void put(U &&elem)
31 requires std::convertible_to<U, T>;
33 T get();
35 [[nodiscard]] unsigned size() const { return size_; }
37 [[nodiscard]] unsigned capacity() const { return queue_.capacity(); }
39 [[nodiscard]] bool empty() const { return size() == 0; }
41 [[nodiscard]] bool hasSpace() const { return size() < capacity(); }
42
43 void forEach(std::function<void(T &)> function);
44
45private:
46 std::vector<T> queue_{};
47 // Point to next-filled element.
48 unsigned head_ = 0;
49 // Points to next-popped element.
50 unsigned tail_ = 0;
51 unsigned size_ = 0;
52};
53
54template <typename T>
55template <typename U>
56inline void BoundedQueue<T>::put(U &&elem)
57 requires std::convertible_to<U, T>
58{
59 if (!hasSpace()) {
60 throw UvcoException(UV_EBUSY, "queue is full");
61 }
62 if (queue_.size() < capacity()) {
63 BOOST_ASSERT(tail_ <= head_);
64 queue_.push_back(std::forward<U>(elem));
65 } else {
66 queue_.at(head_) = std::forward<U>(elem);
67 }
68 head_ = (head_ + 1) % capacity();
69 ++size_;
70}
71
72template <typename T> inline T BoundedQueue<T>::get() {
73 if (empty()) [[unlikely]] {
74 throw UvcoException(UV_EAGAIN, "queue is empty");
75 }
76 T element = std::move(queue_.at(tail_++));
77 tail_ = tail_ % capacity();
78 --size_;
79 return element;
80}
81
82template <typename T>
83void BoundedQueue<T>::forEach(std::function<void(T &)> function) {
84 unsigned idx = tail_;
85 for (unsigned i = 0; i < size_; ++i) {
86 function(queue_.at(idx));
87 idx = (idx + 1) % capacity();
88 }
89}
90
92
93} // namespace uvco
BoundedQueue(size_t capacity)
Definition bounded_queue.h:26
T get()
Pop an item from the queue.
Definition bounded_queue.h:72
void put(U &&elem)
Push an item to the queue.
Definition bounded_queue.h:56
unsigned size_
Definition bounded_queue.h:51
bool empty() const
size() == 0
Definition bounded_queue.h:39
void forEach(std::function< void(T &)> function)
Definition bounded_queue.h:83
bool hasSpace() const
size() < capacity()
Definition bounded_queue.h:41
unsigned head_
Definition bounded_queue.h:48
std::vector< T > queue_
Definition bounded_queue.h:46
unsigned capacity() const
Maximum number of contained items.
Definition bounded_queue.h:37
unsigned tail_
Definition bounded_queue.h:50
unsigned size() const
Current number of contained items.
Definition bounded_queue.h:35
Definition async_work.cc:18
Definition exception.h:19