1 #ifndef _MA_RINGBUFFER_H_
2 #define _MA_RINGBUFFER_H_
16 static_assert(std::is_trivially_copyable<T>::value);
17 static_assert(std::is_trivially_destructible<T>::value);
19 m_buffer =
new T[m_size];
21 std::memset(m_buffer, 0, m_size *
sizeof(T));
34 const size_t head = m_head.load();
35 const size_t tail = m_tail.load();
36 return head >= tail ? head - tail : m_size - tail + head;
41 size_t push(
const T* data,
size_t size) noexcept {
42 if (!data ||
size == 0) {
45 size_t head = m_head.load();
46 const size_t tail = m_tail.load();
47 const size_t free = (head >= tail ? m_size - head + tail : tail - head) - 1;
52 for (
size_t i = 0; i <
size; ++i) {
53 m_buffer[head] = data[i];
54 head = (head + 1) % m_size;
60 size_t pop(T* data,
size_t size) noexcept {
61 if (!data ||
size == 0) {
64 const size_t head = m_head.load();
65 size_t tail = m_tail.load();
66 const size_t used = head >= tail ? head - tail : m_size - tail + head;
68 for (
size_t i = 0; i <
size; ++i) {
69 data[i] = m_buffer[tail];
70 tail = (tail + 1) % m_size;
76 size_t popIf(T* data,
size_t size, T value) noexcept {
77 if (!data ||
size == 0) {
80 const size_t head = m_head.load();
81 size_t tail = m_tail.load();
82 const size_t used = head >= tail ? head - tail : m_size - tail + head;
84 for (; i < tail + used; ++i) {
85 if (m_buffer[i % m_size] == value) {
89 if (i++ == tail + used) {
93 for (
size_t j = 0; j <
size; ++j) {
94 data[j] = m_buffer[tail];
95 tail = (tail + 1) % m_size;
97 m_tail.store(i % m_size);
107 alignas(32) std::atomic<size_t> m_head;
108 alignas(32) std::atomic<size_t> m_tail;
Definition: ma_ringbuffer.hpp:13
bool empty() const
Definition: ma_ringbuffer.hpp:39
size_t push(const T *data, size_t size) noexcept
Definition: ma_ringbuffer.hpp:41
size_t size() const
Definition: ma_ringbuffer.hpp:33
void clear() noexcept
Definition: ma_ringbuffer.hpp:101
size_t capacity() const
Definition: ma_ringbuffer.hpp:31
size_t pop(T *data, size_t size) noexcept
Definition: ma_ringbuffer.hpp:60
~SPSCRingBuffer() noexcept
Definition: ma_ringbuffer.hpp:24
size_t popIf(T *data, size_t size, T value) noexcept
Definition: ma_ringbuffer.hpp:76
SPSCRingBuffer(size_t size) noexcept
Definition: ma_ringbuffer.hpp:15