Circular Buffer Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circular Buffer runs in O(1) time and O(n) space, in Rust as in every other language.
- ✓std::collections::VecDeque is the ring buffer in std: one contiguous allocation with a start index and a length, and as_slices or make_contiguous hand you the two halves the wrap produces.
- ✓Reviewers want assert!(cap.is_power_of_two()) at construction, Option<T>::take rather than mem::replace where take says it better, and push_overwrite returning Option<T> so the evicted value is handed back with its ownership instead of being dropped where nobody can see it.
- ✓The Rust trap: A raw fixed array is the trap. [T; N] cannot even be built without T: Copy or a Default, so people reach for MaybeUninit<T> and silently take on the drop obligation: dropping that array drops nothing, so every live element leaks unless your Drop walks head..head+len calling assume_init_drop, and any slot dropped twice is undefined behaviour.
- ✓There is no GC and no boxing: Box<[T]> stores T inline, so a ring of plain structs is one contiguous run of bytes and the hardware prefetcher works.
What Circular Buffer actually is
Circular Buffer in Rust: what you actually reach for
Rust implementation
pub struct RingBuffer<T> {
buf: Box<[Option<T>]>,
mask: usize,
head: usize, // index of the oldest element
len: usize, // count field: full and empty are never the same state
}
impl<T> RingBuffer<T> {
pub fn with_capacity(cap: usize) -> Self {
assert!(cap.is_power_of_two(), "capacity must be a power of two");
let mut v = Vec::with_capacity(cap);
v.resize_with(cap, || None); // resize_with does not require T: Clone
Self { buf: v.into_boxed_slice(), mask: cap - 1, head: 0, len: 0 }
}
/// Overwrite-oldest. The evicted value is returned, so ownership of it is
/// handed to the caller rather than dropped somewhere they cannot see.
pub fn push_overwrite(&mut self, value: T) -> Option<T> {
let tail = (self.head + self.len) & self.mask;
let evicted = if self.len == self.buf.len() {
self.head = (self.head + 1) & self.mask; // tail == head when full
self.buf[tail].take() // moves out, leaves None
} else {
self.len += 1;
None
};
self.buf[tail] = Some(value);
evicted
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
return None;
}
let v = self.buf[self.head].take();
self.head = (self.head + 1) & self.mask;
self.len -= 1;
v
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Circular Buffer?
std::collections::VecDeque is the ring buffer in std: one contiguous allocation with a start index and a length, and as_slices or make_contiguous hand you the two halves the wrap produces. It grows rather than rejecting and has no overwrite-when-full mode, so a fixed-capacity overwriting ring is yours to write over Box<[Option<T>]> or an array of core::mem::MaybeUninit<T>. For the concurrent variants the ecosystem answers are crossbeam::queue::ArrayQueue, which is bounded and lock-free and offers both push returning Err on full and force_push returning the evicted Option<T>, and heapless::spsc::Queue for no_std with the capacity as a const generic.
What is the most common Rust mistake when implementing Circular Buffer?
A raw fixed array is the trap. [T; N] cannot even be built without T: Copy or a Default, so people reach for MaybeUninit<T> and silently take on the drop obligation: dropping that array drops nothing, so every live element leaks unless your Drop walks head..head+len calling assume_init_drop, and any slot dropped twice is undefined behaviour. Option<T> costs nothing extra for a niche-optimized T and makes take do the right thing for free. The other bite is the borrow checker on the lock-free variant: a single &mut self cannot be split across two threads, so the real shape is one allocation behind UnsafeCell, two AtomicUsize cursors, and unsafe impl Send plus Sync that you must actually justify.
How does Circular Buffer actually perform in Rust?
There is no GC and no boxing: Box<[T]> stores T inline, so a ring of plain structs is one contiguous run of bytes and the hardware prefetcher works. Power-of-two capacity is what lets the optimizer lower the wrap to a single AND, whereas % on a runtime value is a division. Bounds checks stay on every index; they are usually cheap, and get_unchecked removes them only where you can prove the index. VecDeque wraps, so extending from a slice is two memcpys rather than one and iteration crosses a discontinuity; call make_contiguous once when you need a single &[T]. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.