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 436955 : RingBuffer() { Reset(); }
17 : static const int kSize = 10;
18 : void Push(const T& value) {
19 450004 : if (count_ == kSize) {
20 231576 : elements_[start_++] = value;
21 231576 : if (start_ == kSize) start_ = 0;
22 : } else {
23 : DCHECK_EQ(start_, 0);
24 218430 : elements_[count_++] = value;
25 : }
26 : }
27 :
28 : int Count() const { return count_; }
29 :
30 : template <typename Callback>
31 656183 : T Sum(Callback callback, const T& initial) const {
32 664681 : int j = start_ + count_ - 1;
33 664681 : if (j >= kSize) j -= kSize;
34 656183 : T result = initial;
35 6994019 : for (int i = 0; i < count_; i++) {
36 29089 : result = callback(result, elements_[j]);
37 3164669 : if (--j == -1) j += kSize;
38 : }
39 656183 : return result;
40 : }
41 :
42 436984 : 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_
|