blob: 12b2ef23cd31a52de75bf444e5161c7a8bd3c1b1 (
plain)
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
83
84
85
86
87
|
#pragma once
#include <cstdint>
#include <klibc/string.hpp>
#include <generic/lock/spinlock.hpp>
#include <atomic>
namespace utils {
template <typename T>
struct buffer_obj_t {
std::uint32_t cycle;
T data;
};
template <typename T>
class ring_buffer {
private:
buffer_obj_t<T>* objs;
int tail;
int size;
int cycle;
locks::preempt_spinlock lock;
public:
explicit ring_buffer(std::size_t size_elements) {
size = static_cast<int>(size_elements);
objs = new buffer_obj_t<T>[size];
tail = 0;
cycle = 1;
klibc::memset(objs, 0, sizeof(buffer_obj_t<T>) * size);
}
~ring_buffer() {
delete[] objs;
}
ring_buffer(const ring_buffer&) = delete;
ring_buffer& operator=(const ring_buffer&) = delete;
void send(const T& item) {
bool state = lock.lock();
objs[tail].cycle = cycle;
objs[tail].data = item;
if (++tail == size) {
tail = 0;
cycle = !cycle;
}
lock.unlock(state);
}
bool is_not_empty(int reader_queue, int reader_cycle) const {
return objs[reader_queue].cycle == (std::uint32_t)reader_cycle;
}
int receive(T* out, int max, int* c_io, int* q_io) {
bool state = lock.lock();
int count = 0;
int q = *q_io;
int c = *c_io;
while (count < max && objs[q].cycle == (std::uint32_t)c) {
out[count] = objs[q].data;
if (++q == size) {
q = 0;
c = !c;
}
count += sizeof(T);
}
*q_io = q;
*c_io = c;
lock.unlock(state);
return count;
}
};
}
|