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+
117#pragma once
218
319namespace dd {
@@ -11,29 +27,20 @@ class RingBuffer {
1127 back_index_(0 ),
1228 front_index_(0 ) {}
1329
30+ size_t capacity () const { return capacity_; }
1431 bool full () const { return size_ == capacity_; }
1532 bool empty () const { return size_ == 0 ; }
1633 size_t size () const { return size_; }
1734
1835 T& front () { return buffer[front_index_]; }
19-
2036 const T& front () const { return buffer[front_index_]; }
2137
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 ();
3744 }
3845 }
3946
@@ -45,6 +52,24 @@ class RingBuffer {
4552 }
4653
4754 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+
4873 void increment (size_t & idx) const {
4974 idx = idx + 1 == capacity_ ? 0 : idx + 1 ;
5075 }
0 commit comments