V8 API Reference, 7.2.502.16 (for Deno 0.2.4)
ring-buffer.h
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  RingBuffer() { Reset(); }
17  static const int kSize = 10;
18  void Push(const T& value) {
19  if (count_ == kSize) {
20  elements_[start_++] = value;
21  if (start_ == kSize) start_ = 0;
22  } else {
23  DCHECK_EQ(start_, 0);
24  elements_[count_++] = value;
25  }
26  }
27 
28  int Count() const { return count_; }
29 
30  template <typename Callback>
31  T Sum(Callback callback, const T& initial) const {
32  int j = start_ + count_ - 1;
33  if (j >= kSize) j -= kSize;
34  T result = initial;
35  for (int i = 0; i < count_; i++) {
36  result = callback(result, elements_[j]);
37  if (--j == -1) j += kSize;
38  }
39  return result;
40  }
41 
42  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_
Definition: libplatform.h:13