• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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:
RingBuffer()16   RingBuffer() { Reset(); }
17   RingBuffer(const RingBuffer&) = delete;
18   RingBuffer& operator=(const RingBuffer&) = delete;
19 
20   static const int kSize = 10;
21 
Push(const T & value)22   void Push(const T& value) {
23     if (count_ == kSize) {
24       elements_[start_++] = value;
25       if (start_ == kSize) start_ = 0;
26     } else {
27       DCHECK_EQ(start_, 0);
28       elements_[count_++] = value;
29     }
30   }
31 
Count()32   int Count() const { return count_; }
33 
34   template <typename Callback>
Sum(Callback callback,const T & initial)35   T Sum(Callback callback, const T& initial) const {
36     int j = start_ + count_ - 1;
37     if (j >= kSize) j -= kSize;
38     T result = initial;
39     for (int i = 0; i < count_; i++) {
40       result = callback(result, elements_[j]);
41       if (--j == -1) j += kSize;
42     }
43     return result;
44   }
45 
Reset()46   void Reset() { start_ = count_ = 0; }
47 
48  private:
49   T elements_[kSize];
50   int start_;
51   int count_;
52 };
53 
54 }  // namespace base
55 }  // namespace v8
56 
57 #endif  // V8_BASE_RING_BUFFER_H_
58