13 assert((
capacity > 1) &&
"Ring buffer capacity must be greater than one!");
14 assert(((
capacity & (
capacity - 1)) == 0) &&
"Ring buffer capacity must be a power of two!");
16 memset(_pad0, 0,
sizeof(cache_line_pad));
17 memset(_pad1, 0,
sizeof(cache_line_pad));
18 memset(_pad2, 0,
sizeof(cache_line_pad));
19 memset(_pad3, 0,
sizeof(cache_line_pad));
24 const size_t head = _head.load(std::memory_order_acquire);
25 const size_t tail = _tail.load(std::memory_order_acquire);
32 assert((
size <= _capacity) &&
"Data size should not be greater than ring buffer capacity!");
39 assert((data !=
nullptr) &&
"Pointer to the data should not be null!");
43 const size_t head = _head.load(std::memory_order_relaxed);
44 const size_t tail = _tail.load(std::memory_order_acquire);
47 if ((
size + head - tail) > _capacity)
51 size_t head_index = head & _mask;
52 size_t tail_index = tail & _mask;
53 size_t remain = (tail_index > head_index) ? (tail_index - head_index) : (_capacity - head_index);
54 size_t first = (
size > remain) ? remain :
size;
55 size_t last = (
size > remain) ?
size - remain : 0;
56 memcpy(&_buffer[head_index], (uint8_t*)data, first);
57 memcpy(_buffer, (uint8_t*)data + first, last);
60 _head.store(head +
size, std::memory_order_release);
70 assert((data !=
nullptr) &&
"Pointer to the data should not be null!");
74 const size_t tail = _tail.load(std::memory_order_relaxed);
75 const size_t head = _head.load(std::memory_order_acquire);
78 size_t available = head - tail;
87 size_t head_index = head & _mask;
88 size_t tail_index = tail & _mask;
89 size_t remain = (head_index > tail_index) ? (head_index - tail_index) : (_capacity - tail_index);
90 size_t first = (
size > remain) ? remain :
size;
91 size_t last = (
size > remain) ?
size - remain : 0;
92 memcpy((uint8_t*)data, &_buffer[tail_index], first);
93 memcpy((uint8_t*)data + first, _buffer, last);
96 _tail.store(tail +
size, std::memory_order_release);
bool Enqueue(const void *data, size_t size)
Enqueue a data into the ring buffer (single producer thread method)
size_t size() const noexcept
Get ring buffer size in bytes.
bool Dequeue(void *data, size_t &size)
Dequeue a data from the ring buffer (single consumer thread method)
size_t capacity() const noexcept
Get ring buffer capacity in bytes.
SPSCRingBuffer(size_t capacity)
Default class constructor.
C++ Common project definitions.