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 <uv.h>
7
8#include "uvco/exception.h"
9
10#include <boost/assert.hpp>
11#include <utility>
12#include <vector>
13
14namespace uvco {
15
17
23template <typename T> class BoundedQueue {
24public:
25 explicit BoundedQueue(unsigned capacity) { queue_.reserve(capacity); }
26
28 template <typename U>
29 void put(U &&elem)
30 requires std::convertible_to<U, T>
31 {
32 if (!hasSpace()) {
33 throw UvcoException(UV_EBUSY, "queue is full");
34 }
35 if (queue_.size() < capacity()) {
37 queue_.push_back(std::forward<U>(elem));
38 } else {
39 queue_.at(head_) = std::forward<U>(elem);
40 }
41 head_ = (head_ + 1) % capacity();
42 ++size_;
43 }
45 T get() {
46 if (empty()) [[unlikely]] {
47 throw UvcoException(UV_EAGAIN, "queue is empty");
48 }
49 T element = std::move(queue_.at(tail_++));
50 tail_ = tail_ % capacity();
51 --size_;
52 return element;
53 }
55 [[nodiscard]] unsigned size() const { return size_; }
57 [[nodiscard]] unsigned capacity() const { return queue_.capacity(); }
59 [[nodiscard]] bool empty() const { return size() == 0; }
61 [[nodiscard]] bool hasSpace() const { return size() < capacity(); }
62
63private:
64 std::vector<T> queue_{};
65 // Point to next-filled element.
66 unsigned head_ = 0;
67 // Points to next-popped element.
68 unsigned tail_ = 0;
69 unsigned size_ = 0;
70};
71
73
74} // namespace uvco
Definition bounded_queue.h:23
T get()
Pop an item from the queue.
Definition bounded_queue.h:45
BoundedQueue(unsigned capacity)
Definition bounded_queue.h:25
void put(U &&elem)
Push an item to the queue.
Definition bounded_queue.h:29
unsigned size_
Definition bounded_queue.h:69
bool empty() const
size() == 0
Definition bounded_queue.h:59
bool hasSpace() const
size() < capacity()
Definition bounded_queue.h:61
unsigned head_
Definition bounded_queue.h:66
std::vector< T > queue_
Definition bounded_queue.h:64
unsigned capacity() const
Maximum number of contained items.
Definition bounded_queue.h:57
unsigned tail_
Definition bounded_queue.h:68
unsigned size() const
Current number of contained items.
Definition bounded_queue.h:55
Definition async_work.cc:17
Definition exception.h:19