-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring_buffer.hpp
More file actions
82 lines (66 loc) · 1.02 KB
/
ring_buffer.hpp
File metadata and controls
82 lines (66 loc) · 1.02 KB
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
79
80
81
82
#ifndef RING_BUFFER_HPP_
#define RING_BUFFER_HPP_
#include <stddef.h>
#include <stdint.h>
template<typename T, size_t count>
class ring_buffer
{
private:
size_t head_ = 0;
size_t tail_ = 0;
bool full_ = 0;
T buffer_[count];
public:
ring_buffer() = default;
void put(T data) noexcept
{
buffer_[head_] = data;
if (full_)
{
tail_ = (tail_ + 1) % count;
}
head_ = (head_ + 1) % count;
full_ = head_ == tail_;
}
T get() noexcept
{
auto value = buffer_[tail_];
full_ = false;
tail_ = (tail_ + 1) % count;
return value;
}
void reset() noexcept
{
head_ = tail_;
full_ = false;
}
bool empty() const noexcept
{
return (!full_ && (head_ == tail_));
}
bool full() const noexcept
{
return full_;
}
size_t capacity() const noexcept
{
return count;
}
size_t size() const noexcept
{
size_t size = count;
if (!full_)
{
if (head_ >= tail_)
{
size = head_ - tail_;
}
else
{
size = count + head_ - tail_;
}
}
return size;
}
};
#endif