A procedural macro for creating ring buffer (circular buffer) data structures at compile time
A ring buffer is a fixed-size FIFO (First-In-First-Out) data structure that efficiently reuses memory by wrapping around when it reaches the end. This macro generates all necessary fields and methods at compile time with zero runtime overhead.
- Zero runtime overhead - All code generation happens at compile time
- Type safe - Works with any type implementing
Clone - Generic support - Preserves type parameters and constraints
- Visibility preservation - Maintains your struct's visibility modifiers
- Comprehensive API - All standard ring buffer operations
Add this to your Cargo.toml:
[dependencies]
ring-buffer-macro = "0.1.0"use ring_buffer_macro::ring_buffer;
#[ring_buffer(5)]
struct IntBuffer {
data: Vec<i32>,
}
fn main() {
let mut buf = IntBuffer::new();
buf.enqueue(1).unwrap();
buf.enqueue(2).unwrap();
buf.enqueue(3).unwrap();
assert_eq!(buf.dequeue(), Some(1));
assert_eq!(buf.dequeue(), Some(2));
assert_eq!(buf.len(), 1);
}The #[ring_buffer(capacity)] attribute macro transforms your struct:
#[ring_buffer(5)]
struct Buffer {
data: Vec<i32>,
}Adds fields:
capacity: usize- Maximum elementshead: usize- Read positiontail: usize- Write positionsize: usize- Current count
Generates methods:
new()- Creates empty bufferenqueue(item)- Adds item, returnsErr(item)if fulldequeue()- Removes oldest item (requiresT: Clone)is_full()- Checks if at capacityis_empty()- Checks if emptylen()- Current element countcapacity()- Maximum capacityclear()- Removes all elements
- Struct with named fields
- Field named
dataof typeVec<T> - Element type
Tmust implementClone - Capacity must be positive integer literal
- O(1) enqueue and dequeue operations
- Zero allocations after initialization
- No runtime overhead - everything generated at compile time
- Cache-friendly - contiguous memory access
- Logging systems with fixed-size buffers
- Audio/video sample buffers
- Network packet queues
- Embedded systems with constrained resources
- Rate limiting request queues
- Producer-consumer patterns
Contributions are welcome! Please open an issue or submit a pull request.
Licensed under the MIT License. See LICENSE for details.