1. Analyze the User's Request:
* Goal: Design an efficient circular queue (also known as a circular buffer or ring buffer).
* Context: Data logging in an embedded application.
* Key Constraints/Requirements implied by "embedded application":
* Efficiency (speed, memory usage).
* Determinism (avoid dynamic memory allocation like malloc at runtime).
* Robustness (handle concurrency if interrupts are involved).
* Resource constraints (limited RAM/Flash).
* Language: Typically C or C++. I'll focus on C because it's the lingua franca of low-level embedded systems, but I'll mention C++ features where applicable.
Core Data Structure Concept:
A fixed-size array.
A head (write) pointer/index.
A tail (read) pointer/index.
A size or count variable (optional, but helpful for distinguishing full vs. empty states).
Key Design Decisions & Trade-offs:
Full vs. Empty Detection: There are three main approaches:
Boolean Flag: Requires an extra variable. Simple logic.
Count Variable: Stores the number of elements. Very easy to check count == 0 or count == capacity. Good for generic use.
"Always One Empty Slot": The buffer is considered full when head + 1 == tail. This wastes one slot of memory but removes the need for a separate counter or flag (atomic operations are easier).
Decision for Embedded: For data logging, we usually want to utilize as much memory as possible. A count variable is often fine unless we are severely RAM constrained (like < 16 bytes total). However, for concurrency (ISR safe), the "one empty slot" or "mirrored index" approach is often preferred to avoid non-atomic read-modify-write on a counter.
Selection: I will implement the "Count/Size" approach as the primary one because it's most intuitive for data logging (you often want to know how much data is pending). I will discuss the atomic/concurrency aspect separately because that's crucial for embedded.
Data Types:
The buffer needs to hold bytes (uint8_t) or structs (log_entry_t).
I should use volatile if shared with ISRs.
I should use static allocation (compile-time array or struct member array).
API Design:
init(): Reset indices.
push() / write(): Add data.
pop() / read(): Remove data.
is_empty(), is_full().
peek() (optional but useful).
Drafting the Solution (Mental or Scratchpad):
Structure:
c
typedef struct {
uint8_t *buffer;
size_t head;
size_t tail;
size_t max_len; // of the data
size_t count; // current items
} cqueue_t;
Wait, is this flexible enough? For an embedded library, passing a pointer to the buffer storage allows the user to place the buffer in specific memory sections (e.g., non-cached RAM, external RAM).
Optimization: Using powers of two for buffer size allows using bitwise AND (&) instead of modulo (%) for wrapping indices. Modulo is expensive on small MCUs.
Refining for "Efficiency" & "Embedded":
Inlining: Mark small functions static inline to reduce function call overhead.
Modulo optimization: Mention the Power-of-2 trick.
Concurrency: This is the biggest pitfall. If the main loop writes and an ISR reads (or vice versa), race conditions occur.
Critical Sections: Disable interrupts.
Overwrite Policy: For data logging, "overwrite old data" vs "reject new data" is a specific choice.
Scenario A (Sensor Data): If the buffer fills up, we probably missed a beat. We might want to drop new data or overwrite old.
Scenario B (TX Buffer): Usually overwrite is bad?
Standard Logging: Usually FIFO. If full, we often stop logging or overwrite oldest.
Decision: I will implement "Reject if full" as default but show how to do "Overwrite".
Structuring the Response:
Introduction: Acknowledge the constraints (RAM, determinism).
The "Classic" Approach (Count-based): Explain why (distinguishes full/empty easily).
Implementation (C Code):
Struct definition.
Initialization.
Write (Enqueue).
Read (Dequeue).
Optimizations (The "Efficient" part):
Power-of-2 sizing (Bitmasks instead of Modulo).
Static allocation.
Concurrency (The "Embedded" part):
Atomicity issues.
Use of volatile.
Critical sections (Disable Interrupts).
Advanced Technique: Lock-free (Single Producer, Single Consumer).
Writing the Code (Iterative refinement):
Standard Logic:
c
void push(val) {
if (is_full) return;
buffer[head] = val;
head = (head + 1) % size;
count++;
}
Optimized Logic (Power of 2):
c
// Assume size is 2^n, mask is (size - 1)
head = (head + 1) & mask;
Handling Data Types:
Instead of hardcoding uint8_t, use void* and element_size, OR use a macro/template approach. For embedded, uint8_t byte streams are the most common "generic" logging format. I'll stick to a byte-oriented buffer for simplicity but mention how to adapt it.
Review against "Data Logging":
Data logging often involves bursts.
Optimization: write_multiple (memcpy)? Yes, that's a very good optimization for logging. I should include a function to write a chunk of bytes, handling the wrap-around efficiently.
Final Polish:
Check code style.
Ensure comments explain why.
Add the Critical Section macros (mock them out).
Self-Correction during drafting:
Initial thought: Just give the basic ring buffer code.
Correction: The prompt asks for "Efficient" and "Embedded". I must address the modulo operator cost and interrupt safety. Without interrupt safety, it's useless in embedded.
Final Output Structure:
Core Concept: Struct layout.
The Implementation: The code (Init, Push, Pop).
Optimization 1 (Math): Power-of-2 logic.
Optimization 2 (Concurrency): volatile and critical sections.
Optimization 3 (Bulk ops): Linearizing access.
(Self-Correction on Concurrency):
If I use a count variable, I need to protect the update of count AND the index.
If I use the "always one slot empty" method, I only read head in the consumer and tail in the producer. This is easier to make lock-free (for SPSC). I will stick to the count method for readability but emphasize the critical section, as true lock-free is harder to get right for a general audience. However, I will mention the volatile keyword is mandatory.
Let's write the code.
File:circular_buffer.h/c
Features:
Fixed size.
Byte stream.
Wrap handling.
ISR safety.
Let's refine the "Power of 2" bit. It's a huge saving on Cortex-M0/M3 if no hardware divider exists or it's slow.
Let's refine the "Bulk Write". For logging, you usually have a formatted string or a struct. You don't want to push byte-by-byte.
Final Plan:
Design Goals: Define what makes it "embedded efficient" (Static memory, No malloc, ISR safe).
The Structure:struct with indices and buffer.
The "Math" Trick: Replace % with & (bitmask).
The Code: A clean C implementation.
Concurrency: Explanation of Critical Sections.
Advanced Usage: Linearizing (handling wrap-around for DMA/Memcpy).
This looks solid. Proceeding to generate output.
In embedded systems, a Circular Queue (or Ring Buffer) is the standard solution for data logging. It allows constant-time insertions and handles data overflow gracefully (either by overwriting old data or rejecting new data) without needing malloc or heap fragmentation.
Here is a design for an efficient, ISR-safe, and zero-copy friendly Circular Queue in C.
1. Design Considerations for Embedded Systems
To make this "efficient" for embedded contexts (ARM Cortex-M, AVR, ESP32, etc.), we apply three specific constraints:
Power-of-Two Sizing: The buffer size is defined as 2n. This allows us to use a bitwise AND (&) instead of the modulo operator (%) for index wrapping, which is significantly faster on small microcontrollers.
No Heap Allocation: The buffer is allocated statically or globally at compile time to prevent memory fragmentation.
Atomic Access: Since data logging often involves a high-priority Interrupt Service Routine (ISR) writing data while the main loop reads it, the design must handle concurrency without full mutexes (which are too heavy/slow for ISRs).
2. The Data Structure
We will use the "Keep Track of Count" variation. This maintains a separate count variable.
Pros: Easily distinguishes between "Buffer Full" and "Buffer Empty".
Cons: Slightly more RAM usage (one extra integer).
c
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
// 1. Define the buffer size as a Power of Two (e.g., 64, 128, 1024, 4096)
#define LOG_BUFFER_SIZE 256
#define LOG_BUFFER_MASK (LOG_BUFFER_SIZE - 1)
typedef struct {
uint8_t buffer[LOG_BUFFER_SIZE]; // Statically allocated array
volatile uint16_t head; // Write index (modified by Producer)
volatile uint16_t tail; // Read index (modified by Consumer)
volatile uint16_t count; // Current number of items
} CircularQueue_t;
// Global instance
CircularQueue_t g_logQueue = {0};
Note: volatile is critical here. It tells the compiler not to optimize reads/writes to these variables, as they can change asynchronously (e.g., via an interrupt).
3. Core Implementation
Initialization
Strictly speaking, global variables are zero-initialized in C, but an init function is good practice for reuse.
This function writes data to the buffer. In a logging scenario, this might be called by an interrupt (e.g., UART RX handler).
c
bool Queue_Enqueue(CircularQueue_t *q, uint8_t data) {
// 1. Check if full (Optional: Overwrite policy)
if (q->count >= LOG_BUFFER_SIZE) {
return false; // Buffer full, data lost
}
// 2. Write data
q->buffer[q->head] = data;
// 3. Advance head using Bitwise AND (Efficient Modulo)
q->head = (q->head + 1) & LOG_BUFFER_MASK;
// 4. Increment count
// CRITICAL SECTION: If this is called inside an ISR,
// no atomic protection is needed here. If called from main,
// disable interrupts briefly.
q->count++;
return true;
}
Dequeue (Data Out)
This function reads data. This is typically called by the main application loop to process/send logs.
For high-speed logging (e.g., logging 100 samples at once), calling Enqueue 100 times is inefficient due to the function call overhead and loop checking.
Instead, we can implement a Write Commit pattern. This allows writing a block of data or interfacing with DMA (Direct Memory Access).
c
// Returns a pointer to the contiguous free space and how much is available
// This allows the caller to 'memcpy' directly into the buffer.
uint8_t* Queue_GetWritePtr(CircularQueue_t *q, uint16_t max_len, uint16_t *available) {
// Calculate contiguous space until the end of the array or until tail
// Note: This simplified logic assumes we stop at the physical end of the array.
// A more complex "mirrored" buffer handles wrap-around seamlessly.
*available = LOG_BUFFER_SIZE - q->head;
if (*available > max_len) *available = max_len;
// Don't allow writing past the tail (Full check)
uint16_t free_space = LOG_BUFFER_SIZE - q->count;
if (*available > free_space) *available = free_space;
return &q->buffer[q->head];
}
// Call this after you have copied data into the pointer provided above
void Queue_CommitWrite(CircularQueue_t *q, uint16_t len) {
q->head = (q->head + len) & LOG_BUFFER_MASK;
q->count += len;
}
5. Handling Concurrency (ISR Safety)
In an embedded application, Enqueue often happens in an Interrupt Service Routine (e.g., UART_IRQHandler), while Dequeue happens in the main while(1) loop.
If the microcontroller supports atomic 16-bit reads/writes (most 32-bit MCUs do), and you use the "Count" method, you often don't need to disable interrupts for simple checks, but you do need them when modifying shared state if operations are not atomic.
Safe Usage Pattern:
c
// In Main Loop (Consumer)
void Process_Logs() {
uint8_t byte;
// Disable IRQs briefly to read 'count' safely if the arch is 8-bit
__disable_irq();
uint16_t current_count = g_logQueue.count;
__enable_irq();
if (current_count > 0) {
// Dequeue is safe assuming Head is only written by ISR (Producer)
// and Tail is only written by Main (Consumer).
// However, 'count' modification needs care.
if (Queue_Dequeue(&g_logQueue, &byte)) {
// Process byte...
printf("%c", byte);
}
}
}
Summary of Optimizations
Feature
Standard Approach
Embedded Optimization
Index Wrap
index = (index + 1) % size
index = (index + 1) & mask (Bitwise AND is ~10x faster)
Memory
malloc / new
Static array (No fragmentation, compile-time sizing)
Policy
Blocking / Error
Overwrite Oldest (ideal for oscilloscope/log traces) or Drop Newest