-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcircular_buffer.cc
More file actions
91 lines (79 loc) · 1.79 KB
/
Copy pathcircular_buffer.cc
File metadata and controls
91 lines (79 loc) · 1.79 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// A circular buffer remove or add items both at the begin and end sides.
#include "common/assert.h"
#include <vector>
template <typename ItemType>
class CircularBuffer {
public:
CircularBuffer(int size) : data_(size) {}
ItemType front() {
return data_[begin_];
}
void push_front(ItemType v) {
--begin_;
++size_;
if (begin_ < 0) {
begin_ = data_.size() - 1;
}
data_[begin_] = v;
}
ItemType pop_front() {
ItemType result = front();
begin_ = (begin_ + 1) % data_.size();
--size_;
return result;
}
ItemType back() {
return data_[end_-1];
}
ItemType pop_back() {
ItemType result = back();
--end_;
--size_;
if (end_ == 0) {
end_ = size_;
}
return result;
}
void push_back(ItemType v) {
++size_;
++end_;
if (end_ > data_.size()) {
end_ = 1;
}
data_[end_-1] = v;
}
int size() {
return size_;
}
int capacity() {
return data_.size();
}
private:
std::vector<ItemType> data_;
int begin_ = 0;
int end_ = 0;
int size_ = 0;
};
void test_CircularBuffer() {
CircularBuffer<int> buffer(2);
EXPECT_EQ(0, buffer.size());
buffer.push_back(12345);
EXPECT_EQ(1, buffer.size());
EXPECT_EQ(12345, buffer.front());
EXPECT_EQ(12345, buffer.back());
EXPECT_EQ(12345, buffer.pop_front());
EXPECT_EQ(0, buffer.size());
buffer.push_front(54321);
EXPECT_EQ(1, buffer.size());
EXPECT_EQ(54321, buffer.pop_back());
EXPECT_EQ(0, buffer.size());
buffer.push_back(13);
buffer.push_back(37);
EXPECT_EQ(2, buffer.size());
EXPECT_EQ(13, buffer.pop_front());
EXPECT_EQ(37, buffer.pop_front());
EXPECT_EQ(0, buffer.size());
}
int main() {
test_CircularBuffer();
}