• 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   static const int kSize = 10;
Push(const T & value)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 
Count()28   int Count() const { return count_; }
29 
30   template <typename Callback>
Sum(Callback callback,const T & initial)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 
Reset()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_
55