-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular_buffer.h
More file actions
106 lines (85 loc) · 2.03 KB
/
circular_buffer.h
File metadata and controls
106 lines (85 loc) · 2.03 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#pragma once
#include <cstdio>
#include <mutex>
#include <optional>
template<class T>
class circular_buffer
{
public:
explicit circular_buffer(const std::size_t iSize)
{
_buffer = new T[iSize];
_write_index = 0;
_read_index = 0;
_count_elements = iSize;
_isfull = false;
};
std::size_t size() const;
std::size_t size_buffer() const { return _count_elements; };
bool empty() { return !_isfull && _read_index == _write_index; };
void push(T element);
T pop();
T& operator[](const std::size_t index);
const T& operator[](const std::size_t index) const;
~circular_buffer() { delete[] _buffer; };
private:
T *_buffer;
std::size_t _write_index;
std::size_t _read_index;
std::size_t _count_elements;
std::mutex _lock;
bool _isfull;
};
template <class T>
std::size_t circular_buffer<T>::size() const
{
if (_isfull)
return _count_elements;
return (_write_index + _count_elements - _read_index) % _count_elements;
}
template <class T>
void circular_buffer<T>::push(T element)
{
std::lock_guard<std::mutex> lock(_lock);
if (_isfull && _write_index == _read_index)
{
_read_index = (_read_index + 1)%_count_elements;
}
_buffer[_write_index++] = element;
if (_write_index == _count_elements)
_write_index = 0;
if (_write_index == _read_index)
{
_isfull = true;
}
}
template <class T>
T circular_buffer<T>::pop()
{
std::lock_guard<std::mutex> lock(_lock);
if (empty())
return T();
T value_element = _buffer[_read_index];
_read_index++;
if (_read_index == _count_elements)
_read_index = 0;
if (_isfull)
_isfull = !_isfull;
return value_element;
}
template <class T>
T& circular_buffer<T>::operator[](const std::size_t index)
{
std::lock_guard<std::mutex> lock(_lock);
if (empty() || index > size())
return T();
return _buffer[(_read_index + index) % _count_elements];
}
template<class T>
const T& circular_buffer<T>::operator[](const std::size_t index) const
{
std::lock_guard<std::mutex> lock(_lock);
if (empty() || index > size())
return T();
return _buffer[(_read_index + index) % _count_elements];
}