ring-buffer-macro
A procedural macro for creating ring buffer (circular buffer) data structures at compile time
Documentation | Crates.io | Repository
Overview
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.
Features
- 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
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Quick Start
use ring_buffer;
How It Works
The #[ring_buffer(capacity)] attribute macro transforms your struct:
Input
Output
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
Requirements
- Struct with named fields
- Field named
dataof typeVec<T> - Element type
Tmust implementClone - Capacity must be positive integer literal
Performance
- O(1) enqueue and dequeue operations
- Zero allocations after initialization
- No runtime overhead - everything generated at compile time
- Cache-friendly - contiguous memory access
Use Cases
- 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
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
License
Licensed under the MIT License. See LICENSE for details.