Line data Source code
1 : // Copyright 2016 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef V8_BASE_RING_BUFFER_H_
6 : #define V8_BASE_RING_BUFFER_H_
7 :
8 : #include "src/base/macros.h"
9 :
10 : namespace v8 {
11 : namespace base {
12 :
13 : template <typename T>
14 : class RingBuffer {
15 : public:
16 437095 : RingBuffer() { Reset(); }
17 : static const int kSize = 10;
18 : void Push(const T& value) {
19 456339 : if (count_ == kSize) {
20 239061 : elements_[start_++] = value;
21 239061 : if (start_ == kSize) start_ = 0;
22 : } else {
23 : DCHECK_EQ(start_, 0);
24 217280 : elements_[count_++] = value;
25 : }
26 : }
27 :
28 : int Count() const { return count_; }
29 :
30 : template <typename Callback>
31 661361 : T Sum(Callback callback, const T& initial) const {
32 669879 : int j = start_ + count_ - 1;
33 669879 : if (j >= kSize) j -= kSize;
34 661361 : T result = initial;
35 7145215 : for (int i = 0; i < count_; i++) {
36 29130 : result = callback(result, elements_[j]);
37 3237668 : if (--j == -1) j += kSize;
38 : }
39 661361 : return result;
40 : }
41 :
42 437124 : void Reset() { start_ = count_ = 0; }
43 :
44 : private:
45 : T elements_[kSize];
46 : int start_;
47 : int count_;
48 : DISALLOW_COPY_AND_ASSIGN(RingBuffer);
49 : };
50 :
51 : } // namespace base
52 : } // namespace v8
53 :
54 : #endif // V8_BASE_RING_BUFFER_H_
|