1
+ /*
2
+ * Copyright 2023 Datadog, Inc
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
1
17
#pragma once
2
18
3
19
namespace dd {
@@ -11,29 +27,20 @@ class RingBuffer {
11
27
back_index_(0 ),
12
28
front_index_(0 ) {}
13
29
30
+ size_t capacity () const { return capacity_; }
14
31
bool full () const { return size_ == capacity_; }
15
32
bool empty () const { return size_ == 0 ; }
16
33
size_t size () const { return size_; }
17
34
18
35
T& front () { return buffer[front_index_]; }
19
-
20
36
const T& front () const { return buffer[front_index_]; }
21
37
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_;
38
+ void push_back (const T& t) { push_back_ (t); }
39
+ void push_back (T&& t) { push_back_ (std::move (t)); }
40
+
41
+ void clear () {
42
+ while (!empty ()) {
43
+ pop_front ();
37
44
}
38
45
}
39
46
@@ -45,6 +52,24 @@ class RingBuffer {
45
52
}
46
53
47
54
private:
55
+ template <typename U>
56
+ void push_back_ (U&& t) {
57
+ const bool is_full = full ();
58
+
59
+ if (is_full && empty ()) {
60
+ return ;
61
+ }
62
+ buffer[back_index_] = std::forward<U>(t);
63
+ increment (back_index_);
64
+
65
+ if (is_full) {
66
+ // move buffer head
67
+ front_index_ = back_index_;
68
+ } else {
69
+ ++size_;
70
+ }
71
+ }
72
+
48
73
void increment (size_t & idx) const {
49
74
idx = idx + 1 == capacity_ ? 0 : idx + 1 ;
50
75
}
0 commit comments