1 //===-- esan_circular_buffer.h ----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of EfficiencySanitizer, a family of performance tuners.
12 // Circular buffer data structure.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_common.h"
19 // A circular buffer for POD data whose memory is allocated using mmap.
20 // There are two usage models: one is to use initialize/free (for global
21 // instances) and the other is to use placement new with the
22 // constructor and to call the destructor or free (they are equivalent).
24 class CircularBuffer {
26 // To support global instances we cannot initialize any field in the
27 // default constructor.
28 explicit CircularBuffer() {}
29 CircularBuffer(uptr BufferCapacity) {
30 initialize(BufferCapacity);
31 WasConstructed = true;
34 if (WasConstructed) // Else caller will call free() explicitly.
37 void initialize(uptr BufferCapacity) {
38 Capacity = BufferCapacity;
39 // MmapOrDie rounds up to the page size for us.
40 Data = (T *)MmapOrDie(Capacity * sizeof(T), "CircularBuffer");
43 WasConstructed = false;
46 UnmapOrDie(Data, Capacity * sizeof(T));
48 T &operator[](uptr Idx) {
50 uptr ArrayIdx = (StartIdx + Idx) % Capacity;
51 return Data[ArrayIdx];
53 const T &operator[](uptr Idx) const {
55 uptr ArrayIdx = (StartIdx + Idx) % Capacity;
56 return Data[ArrayIdx];
58 void push_back(const T &Item) {
59 CHECK_GT(Capacity, 0);
60 uptr ArrayIdx = (StartIdx + Count) % Capacity;
61 Data[ArrayIdx] = Item;
65 StartIdx = (StartIdx + 1) % Capacity;
69 uptr ArrayIdx = (StartIdx + Count - 1) % Capacity;
70 return Data[ArrayIdx];
83 bool empty() const { return size() == 0; }
86 CircularBuffer(const CircularBuffer&);
87 void operator=(const CircularBuffer&);