@@ -11,29 +11,20 @@ class RingBuffer {
11
11
back_index_(0 ),
12
12
front_index_(0 ) {}
13
13
14
+ size_t capacity () const { return capacity_; }
14
15
bool full () const { return size_ == capacity_; }
15
16
bool empty () const { return size_ == 0 ; }
16
17
size_t size () const { return size_; }
17
18
18
19
T& front () { return buffer[front_index_]; }
19
-
20
20
const T& front () const { return buffer[front_index_]; }
21
21
22
- template <typename T2>
23
- void push_back (T2&& t) {
24
- if (full ()) {
25
- if (empty ()) {
26
- return ;
27
- }
28
- // overwrite buffer head
29
- buffer[back_index_] = std::forward<T2>(t);
30
- increment (back_index_);
31
- // move buffer head
32
- front_index_ = back_index_;
33
- } else {
34
- buffer[back_index_] = std::forward<T2>(t);
35
- increment (back_index_);
36
- ++size_;
22
+ void push_back (const T& t) { push_back_ (t); }
23
+ void push_back (T&& t) { push_back_ (std::move (t)); }
24
+
25
+ void clear () {
26
+ while (!empty ()) {
27
+ pop_front ();
37
28
}
38
29
}
39
30
@@ -45,6 +36,24 @@ class RingBuffer {
45
36
}
46
37
47
38
private:
39
+ template <typename U>
40
+ void push_back_ (U&& t) {
41
+ const bool is_full = full ();
42
+
43
+ if (is_full && empty ()) {
44
+ return ;
45
+ }
46
+ buffer[back_index_] = std::forward<U>(t);
47
+ increment (back_index_);
48
+
49
+ if (is_full) {
50
+ // move buffer head
51
+ front_index_ = back_index_;
52
+ } else {
53
+ ++size_;
54
+ }
55
+ }
56
+
48
57
void increment (size_t & idx) const {
49
58
idx = idx + 1 == capacity_ ? 0 : idx + 1 ;
50
59
}
0 commit comments