forked from membase/ep-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ringbuffer.hh
78 lines (66 loc) · 1.48 KB
/
ringbuffer.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef RINGBUFFER_HH
#define RINGBUFFER_HH
#include <cassert>
#include <vector>
#include <algorithm>
#include "common.hh"
/**
* A RingBuffer holds a fixed number of elements of type T.
*/
template <typename T>
class RingBuffer {
public:
/**
* Construct a RingBuffer to hold the given number of elements.
*/
explicit RingBuffer(size_t s) : pos(0), max(s), wrapped(false) {
storage = new T[max];
}
~RingBuffer() {
delete[] storage;
}
/**
* How many elements are currently stored in this ring buffer?
*/
size_t size() {
return wrapped ? max : pos;
}
/**
* Add an object to the RingBuffer.
*/
void add(T ob) {
if (pos == max) {
wrapped = true;
pos = 0;
}
storage[pos++] = ob;
}
/**
* Remove all items.
*/
void reset() {
pos = 0;
wrapped = 0;
}
/**
* Copy out the contents of this RingBuffer into the a vector.
*/
std::vector<T> contents() {
std::vector<T> rv;
rv.resize(size());
size_t copied(0);
if (wrapped && pos != max) {
std::copy(storage + pos, storage + max, rv.begin());
copied = max - pos;
}
std::copy(storage, storage + pos, rv.begin() + copied);
return rv;
}
private:
T *storage;
size_t pos;
size_t max;
bool wrapped;
DISALLOW_COPY_AND_ASSIGN(RingBuffer);
};
#endif /* RINGBUFFER_HH */