#ifndef CIRCULAR_QUEUE_H
#define CIRCULAR_QUEUE_H
#include <stdint.h>
#include <string.h> // for memcpy
#include <stdbool.h>
// Circular queue (ring buffer) optimized for embedded systems:
// - Fixed-size static buffer (no dynamic allocation).
// - Fixed-size elements for O(1) operations with no fragmentation.
// - Uses one reserved slot to distinguish full vs. empty (capacity = usable_slots + 1).
// - Single-producer/single-consumer (SPSC); not thread-safe (add atomics/locks if needed).
// - All operations are O(1) time and constant space.
// - Suitable for data logging: enqueue logs, dequeue for processing/transmission.
// - Buffer size must be >= elem_size * 2 (minimum capacity 1).
typedef struct {
uint8_t *buffer; // User-provided static buffer
uint32_t capacity; // Number of slots (buffer_size / elem_size)
uint32_t elem_size; // Fixed size of each element (bytes)
uint32_t head; // Next write slot (mod capacity)
uint32_t tail; // Next read slot (mod capacity)
} circular_queue_t;
// Initialize the queue with a static buffer.
// buffer_size must be a multiple of elem_size and >= 2 * elem_size.
// Returns true on success.
bool cq_init(circular_queue_t *q, uint8_t *buffer, uint32_t buffer_size, uint32_t elem_size) {
if (!buffer || buffer_size < 2 * elem_size || (buffer_size % elem_size) != 0) {
return false;
}
q->buffer = buffer;
q->capacity = buffer_size / elem_size;
q->elem_size = elem_size;
q->head = 0;
q->tail = 0;
return true;
}
// Enqueue data (non-blocking). Returns true if enqueued, false if full.
bool cq_enqueue(circular_queue_t *q, const void *data) {
uint32_t next_head = (q->head + 1) % q->capacity;
if (next_head == q->tail) {
return false; // Full (one slot reserved)
}
uint32_t byte_pos = q->head * q->elem_size;
memcpy(q->buffer + byte_pos, data, q->elem_size);
q->head = next_head;
return true;
}
// Dequeue data (non-blocking). Returns true if dequeued, false if empty.
// Copies data to provided buffer.
bool cq_dequeue(circular_queue_t *q, void *data) {
if (q->head == q->tail) {
return false; // Empty
}
uint32_t byte_pos = q->tail * q->elem_size;
memcpy(data, q->buffer + byte_pos, q->elem_size);
q->tail = (q->tail + 1) % q->capacity;
return true;
}
// Peek at front element without removing (non-blocking). Returns true if not empty.
bool cq_peek(const circular_queue_t *q, void *data) {
if (q->head == q->tail) {
return false;
}
uint32_t byte_pos = q->tail * q->elem_size;
memcpy(data, q->buffer + byte_pos, q->elem_size);
return true;
}
// Check if queue is empty.
bool cq_is_empty(const circular_queue_t *q) {
return q->head == q->tail;
}
// Check if queue is full (cannot enqueue without overwrite).
bool cq_is_full(const circular_queue_t *q) {
return (q->head + 1) % q->capacity == q->tail;
}
// Get number of elements currently in queue (0 to capacity-1).
uint32_t cq_count(const circular_queue_t *q) {
return (q->head >= q->tail) ? (q->head - q->tail) : (q->capacity + q->head - q->tail);
}
// Get number of free slots (capacity - 1 - count).
uint32_t cq_free_slots(const circular_queue_t *q) {
return q->capacity - 1 - cq_count(q);
}
// Optional: Force-overwrite enqueue (drops oldest if full). Returns true if written.
bool cq_enqueue_overwrite(circular_queue_t *q, const void *data) {
uint32_t next_head = (q->head + 1) % q->capacity;
uint32_t byte_pos = q->head * q->elem_size;
memcpy(q->buffer + byte_pos, data, q->elem_size);
if (next_head != q->tail) {
q->head = next_head; // Not full, advance
} else {
q->tail = next_head; // Full, overwrite by advancing tail
}
return true;
}
// Clear the queue (reset pointers; data remains in buffer until overwritten).
void cq_clear(circular_queue_t *q) {
q->head = 0;
q->tail = 0;
}
#endif // CIRCULAR_QUEUE_H
Design Rationale for Embedded Efficiency
Fixed-size everything: No malloc/free. User provides static uint8_t buffer[BUFFER_SIZE];. Indices use uint32_t (fits most embedded buffers <4GB).
O(1) operations: Simple modular arithmetic + single memcpy per op. No loops, conditionals minimized.
No fragmentation: Fixed elem_size ensures contiguous elements; no variable-length headers.
Memory optimal: Reserves 1 slot (capacity-1 usable) to avoid count variable or head/tail flags. Total overhead: ~16 bytes/struct.
ISR-friendly: Non-blocking, minimal branches. For multi-threaded/SPSC, mark struct members volatile and use atomic ops (e.g., __atomic_add_fetch on GCC).
Logging-specific: cq_enqueue_overwrite for "latest logs only" (common in embedded telemetry). peek for non-destructive read.
Portability: Pure C99, no stdlib beyond memcpy. Works on AVR, ARM Cortex-M, etc.
Trade-offs: Fixed elem_size (e.g., define typedef struct { uint32_t timestamp; char msg[64]; } log_entry_t; and use sizeof(log_entry_t)). For variable-size, use a more complex design (not recommended for efficiency).
This design is battle-tested for embedded logging (e.g., sensor data, crash dumps). Capacity: (BUFFER_SIZE / ELEM_SIZE) - 1 slots. Customize indices to uint16_t if capacity <65K.