18 #ifndef RAUL_RING_BUFFER_HPP
19 #define RAUL_RING_BUFFER_HPP
43 assert(read_space() == 0);
44 assert(write_space() == size - 1);
55 g_atomic_int_set(&_write_ptr, 0);
56 g_atomic_int_set(&_read_ptr, 0);
59 size_t write_space()
const {
61 const size_t w = g_atomic_int_get(&_write_ptr);
62 const size_t r = g_atomic_int_get(&_read_ptr);
73 size_t read_space()
const {
75 const size_t w = g_atomic_int_get(&_write_ptr);
76 const size_t r = g_atomic_int_get(&_read_ptr);
85 size_t capacity()
const {
return _size; }
87 size_t peek(
size_t size, T* dst);
88 bool full_peek(
size_t size, T* dst);
90 size_t read(
size_t size, T* dst);
91 bool full_read(
size_t size, T* dst);
93 bool skip(
size_t size);
95 void write(
size_t size,
const T* src);
98 mutable int _write_ptr;
99 mutable int _read_ptr;
116 const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
118 const size_t read_size = (priv_read_ptr + size < _size)
120 : _size - priv_read_ptr;
122 memcpy(dst, &_buf[priv_read_ptr], read_size);
132 if (read_space() < size) {
136 const size_t read_size = peek(size, dst);
138 if (read_size < size) {
139 peek(size - read_size, dst + read_size);
156 const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
158 const size_t read_size = (priv_read_ptr + size < _size)
160 : _size - priv_read_ptr;
162 memcpy(dst, &_buf[priv_read_ptr], read_size);
164 g_atomic_int_set(&_read_ptr, (priv_read_ptr + read_size) % _size);
174 if (read_space() < size) {
178 const size_t read_size = read(size, dst);
180 if (read_size < size) {
181 read(size - read_size, dst + read_size);
190 RingBuffer<T>::skip(
size_t size)
192 if (read_space() < size) {
193 std::cerr <<
"WARNING: Attempt to skip past end of MIDI ring buffer" << std::endl;
197 const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
198 g_atomic_int_set(&_read_ptr, (priv_read_ptr + size) % _size);
206 RingBuffer<T>::write(
size_t size,
const T* src)
208 const size_t priv_write_ptr = g_atomic_int_get(&_write_ptr);
210 if (priv_write_ptr + size <= _size) {
211 memcpy(&_buf[priv_write_ptr], src, size);
212 g_atomic_int_set(&_write_ptr, (priv_write_ptr + size) % _size);
214 const size_t this_size = _size - priv_write_ptr;
215 assert(this_size < size);
216 assert(priv_write_ptr + this_size <= _size);
217 memcpy(&_buf[priv_write_ptr], src, this_size);
218 memcpy(&_buf[0], src+this_size, size - this_size);
219 g_atomic_int_set(&_write_ptr, size - this_size);
226 #endif // RAUL_RING_BUFFER_HPP
RingBuffer(size_t size)
Definition: RingBuffer.hpp:38
size_t _size
Size (capacity) in bytes.
Definition: RingBuffer.hpp:101
A lock-free RingBuffer.
Definition: RingBuffer.hpp:33
size_t peek(size_t size, T *dst)
Peek at the ringbuffer (read w/o advancing read pointer).
Definition: RingBuffer.hpp:114
void reset()
Reset(empty) the ringbuffer.
Definition: RingBuffer.hpp:54
T * _buf
size, event, size, event...
Definition: RingBuffer.hpp:102
size_t read(size_t size, T *dst)
Read from the ringbuffer.
Definition: RingBuffer.hpp:154