-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathring_buffer.h
More file actions
49 lines (39 loc) · 1.07 KB
/
Copy pathring_buffer.h
File metadata and controls
49 lines (39 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// ring_buffer.h - 简单的循环缓冲区实现
#pragma once
#include <array>
#include <cstddef>
template <typename T, std::size_t Capacity> class RingBuffer {
public:
bool push(const T& value) {
if (full()) {
return false; // 缓冲区满了
}
buffer_[head_] = value;
head_ = (head_ + 1) % Capacity;
return true;
}
bool pop(T& out) {
if (empty()) {
return false; // 没数据
}
out = buffer_[tail_];
tail_ = (tail_ + 1) % Capacity;
return true;
}
bool empty() const { return head_ == tail_; }
bool full() const { return (head_ + 1) % Capacity == tail_; }
std::size_t size() const {
if (head_ >= tail_) {
return head_ - tail_;
}
return Capacity - (tail_ - head_);
}
std::size_t capacity() const {
return Capacity - 1; // 实际可用容量
}
void clear() { head_ = tail_ = 0; }
private:
std::array<T, Capacity> buffer_{};
std::size_t head_ = 0;
std::size_t tail_ = 0;
};