Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
ring_buffer.hpp
Go to the documentation of this file.
1#ifndef SBL_SYSTEM_RING_BUFFER_HPP_
2#define SBL_SYSTEM_RING_BUFFER_HPP_
3
4/**
5 * @file ring_buffer.hpp
6 * @brief Lock-free single-producer, single-consumer ring buffer
7 * @ingroup system
8 */
9
10#include <atomic>
11#include <cstdint>
12
13namespace sbl {
14namespace system {
15
16namespace detail {
17
18#if defined(__arm__) && !defined(__linux__)
19inline void ring_acquire_fence() { std::atomic_signal_fence(std::memory_order_acquire); }
20inline void ring_release_fence() { std::atomic_signal_fence(std::memory_order_release); }
21#else
22inline void ring_acquire_fence() { std::atomic_thread_fence(std::memory_order_acquire); }
23inline void ring_release_fence() { std::atomic_thread_fence(std::memory_order_release); }
24#endif
25
26} // namespace detail
27
28/**
29 * @brief Lock-free single-producer, single-consumer ring buffer
30 *
31 * Carries data from one execution context to another without blocking
32 * either: ISR -> main on hardware, thread -> thread on the workbench. Every
33 * operation is bounded and allocation-free.
34 *
35 * ## Ordering
36 *
37 * The indices are relaxed `std::atomic<uint32_t>` - no torn or invented
38 * accesses, and no data race in the C++ sense. Ordering between the slot
39 * contents and the index that publishes them comes from a fence pair:
40 *
41 * producer: write slot -> release fence -> store head
42 * consumer: load head -> acquire fence -> read slot -> release fence -> store tail
43 *
44 * The fence strength follows the target:
45 *
46 * - **Single-core bare metal** (Cortex-M): producer and consumer share one
47 * core - an ISR preempting a thread is like a signal handler - so the
48 * fences are `atomic_signal_fence`, compiler-only, zero instructions.
49 * - **Host** (workbench, unit tests): producer and consumer may run on
50 * different cores, so the fences are `atomic_thread_fence` (DMB on
51 * AArch64).
52 *
53 * One slot is reserved to tell full from empty: capacity is Size - 1.
54 *
55 * Usage:
56 * @code
57 * RingBuffer<uint8_t, 256> rx;
58 *
59 * // Producer (ISR)
60 * if (!rx.push(byte)) { ++overflows; }
61 *
62 * // Consumer (main)
63 * uint8_t b;
64 * while (rx.pop(b)) { handle(b); }
65 * @endcode
66 *
67 *
68 * @context push() from the producer context only, pop() from the consumer
69 * context only. empty(), full() and size() are snapshots from either side.
70 *
71 * @tparam T Element type (copied in and out)
72 * @tparam Size Slot count, a power of 2 from 2 to 65536; capacity is Size - 1
73 */
74template<typename T, uint32_t Size>
76 static_assert((Size & (Size - 1)) == 0, "Size must be power of 2");
77 static_assert(Size > 1, "Size must be greater than 1");
78 static_assert(Size <= 65536, "Size must fit in practical memory constraints");
79 static_assert(std::atomic<uint32_t>::is_always_lock_free, "RingBuffer needs lock-free 32-bit atomics");
80
81public:
82 RingBuffer() = default;
83
84 /**
85 * @brief Push an element (producer side)
86 * @return false if the buffer is full; the element is not stored
87 * @context Producer context only, ISR included; bounded, non-blocking.
88 */
89 bool push(const T& item) {
90 const uint32_t head = head_.load(std::memory_order_relaxed);
91 const uint32_t next = (head + 1) & MASK;
92 if (next == tail_.load(std::memory_order_relaxed)) {
93 return false;
94 }
95 detail::ring_acquire_fence(); // consumer finished with this slot
96 buffer_[head] = item;
97 detail::ring_release_fence(); // slot written before head publishes it
98 head_.store(next, std::memory_order_relaxed);
99 return true;
100 }
101
102 /**
103 * @brief Pop the oldest element (consumer side)
104 * @return false if the buffer is empty; `item` is unchanged
105 * @context Consumer context only, ISR included; bounded, non-blocking.
106 */
107 bool pop(T& item) {
108 const uint32_t tail = tail_.load(std::memory_order_relaxed);
109 if (tail == head_.load(std::memory_order_relaxed)) {
110 return false;
111 }
112 detail::ring_acquire_fence(); // head observed before the slot is read
113 item = buffer_[tail];
114 detail::ring_release_fence(); // slot read before tail frees it
115 tail_.store((tail + 1) & MASK, std::memory_order_relaxed);
116 return true;
117 }
118
119 bool empty() const { return head_.load(std::memory_order_relaxed) == tail_.load(std::memory_order_relaxed); }
120
121 bool full() const {
122 return ((head_.load(std::memory_order_relaxed) + 1) & MASK) == tail_.load(std::memory_order_relaxed);
123 }
124
125 /** Element count - a snapshot, may change immediately after the call. */
126 uint32_t size() const {
127 return (head_.load(std::memory_order_relaxed) - tail_.load(std::memory_order_relaxed)) & MASK;
128 }
129
130 static constexpr uint32_t capacity() { return Size - 1; }
131
132 /** Empty the buffer. Only while neither producer nor consumer runs. */
133 void clear() {
134 head_.store(0, std::memory_order_relaxed);
135 tail_.store(0, std::memory_order_relaxed);
136 }
137
138private:
139 static constexpr uint32_t MASK = Size - 1;
140
141 T buffer_[Size] = {};
142 std::atomic<uint32_t> head_{0}; // producer writes, consumer reads
143 std::atomic<uint32_t> tail_{0}; // consumer writes, producer reads
144};
145
146} // namespace system
147} // namespace sbl
148
149#endif // SBL_SYSTEM_RING_BUFFER_HPP_
Lock-free single-producer, single-consumer ring buffer.
bool pop(T &item)
Pop the oldest element (consumer side)
bool push(const T &item)
Push an element (producer side)
uint32_t size() const
Root namespace for all Sound Byte Libs code.