-
Notifications
You must be signed in to change notification settings - Fork 2
/
RingBuffer.h
76 lines (73 loc) · 1.71 KB
/
RingBuffer.h
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
#pragma once
#include <algorithm>
#include <vector>
template <class T> class RingBuffer {
public:
/**
* Simple Circular buffer implementation, based on the array
* @param max_size buffer max size
*/
RingBuffer(const size_t capacity) noexcept
: CAPACITY(capacity), buffer_(capacity) {}
/**
* Puts a chunk of data to the buffer
* @param data buffer with the data
* @param size size of the buffer
* @return true on success
*/
bool push(const T *data, const size_t size) noexcept {
if (!data || !size) {
return false;
}
if (size_ + size > CAPACITY) {
return false;
}
for (size_t i(0); i < size; i++) {
buffer_[end_++] = data[i];
if (end_ >= CAPACITY) {
end_ = 0;
}
}
size_ += size;
return true;
}
/**
* Gets a chunk of data from the buffer
* @param data buffer
* @param size size of the buffer
* @return number of elements actually read
*/
size_t pull(T *data, const size_t size) noexcept {
if (!data || !size) {
return 0;
}
if (!size_) {
return 0;
}
const size_t returnCount = std::min(size_, size);
for (size_t i(0); i < returnCount; i++) {
data[i] = buffer_[start_++];
if (start_ >= CAPACITY) {
start_ = 0;
}
}
size_ -= returnCount;
return returnCount;
}
bool hasEnoughSpace(const size_t count) const noexcept {
return (size_ + count <= CAPACITY);
}
size_t size() const { return size_; }
void reset() {
size_ = 0;
start_ = 0;
end_ = 0;
}
size_t capacity() const noexcept { return CAPACITY; }
private:
const size_t CAPACITY;
size_t size_ = 0;
size_t start_ = 0;
size_t end_ = 0;
std::vector<T> buffer_;
};