nndeploy C++ API  0.2.0
nndeploy C++ API
ring_queue.h
Go to the documentation of this file.
1 
2 #ifndef _NNDEPLOY_BASE_RING_QUEUE_H_
3 #define _NNDEPLOY_BASE_RING_QUEUE_H_
4 
5 #include <cstddef>
6 #include <utility>
7 #include <vector>
8 
9 namespace nndeploy {
10 namespace base {
11 
12 template <typename T>
13 class RingQueue {
14  public:
15  RingQueue() = default;
16  ~RingQueue() = default;
17 
18  void reserve(size_t min_capacity) {
19  if (min_capacity == 0 || capacity_ >= min_capacity) {
20  return;
21  }
22  size_t new_capacity = nextPowerOfTwo(min_capacity);
23  std::vector<T> new_data(new_capacity);
24  if (capacity_ != 0) {
25  for (size_t i = 0; i < size_; ++i) {
26  new_data[i] = std::move(data_[(head_ + i) & mask_]);
27  }
28  }
29  data_.swap(new_data);
30  head_ = 0;
31  capacity_ = new_capacity;
32  mask_ = capacity_ - 1;
33  }
34 
35  void pushBack(T value) {
36  reserve(size_ + 1);
37  if (capacity_ == 0) {
38  return;
39  }
40  size_t tail = (head_ + size_) & mask_;
41  data_[tail] = std::move(value);
42  ++size_;
43  }
44 
45  T popFront() {
46  if (size_ == 0 || capacity_ == 0) {
47  return T{};
48  }
49  T value = std::move(data_[head_]);
50  data_[head_] = T{};
51  head_ = (head_ + 1) & mask_;
52  --size_;
53  return value;
54  }
55 
56  T front() const {
57  if (size_ == 0 || capacity_ == 0) {
58  return T{};
59  }
60  return data_[head_];
61  }
62 
63  T back() const {
64  if (size_ == 0 || capacity_ == 0) {
65  return T{};
66  }
67  size_t tail = (head_ + size_ - 1) & mask_;
68  return data_[tail];
69  }
70 
71  T at(size_t index) const {
72  if (index >= size_ || capacity_ == 0) {
73  return T{};
74  }
75  size_t real_index = (head_ + index) & mask_;
76  return data_[real_index];
77  }
78 
79  size_t size() const { return size_; }
80 
81  bool empty() const { return size_ == 0; }
82 
83  void clear() {
84  if (capacity_ == 0) {
85  return;
86  }
87  for (size_t i = 0; i < size_; ++i) {
88  data_[(head_ + i) & mask_] = T{};
89  }
90  head_ = 0;
91  size_ = 0;
92  }
93 
94  private:
95  static size_t nextPowerOfTwo(size_t value) {
96  size_t capacity = 1;
97  while (capacity < value) {
98  capacity <<= 1;
99  }
100  return capacity;
101  }
102 
103  private:
104  std::vector<T> data_;
105  size_t head_ = 0;
106  size_t size_ = 0;
107  size_t capacity_ = 0;
108  size_t mask_ = 0;
109 };
110 
111 } // namespace base
112 } // namespace nndeploy
113 
114 #endif
size_t size() const
Definition: ring_queue.h:79
void reserve(size_t min_capacity)
Definition: ring_queue.h:18
void pushBack(T value)
Definition: ring_queue.h:35
T at(size_t index) const
Definition: ring_queue.h:71