pub struct LockFreeRing<T> { /* private fields */ }Expand description
Lock-free SPSC ring buffer.
This ring buffer is designed for Single-Producer Single-Consumer scenarios, where one thread enqueues items and another dequeues them. It uses atomic operations for synchronization without any locks.
§Performance
- Enqueue: O(1) amortized
- Dequeue: O(1) amortized
- Batch operations amortize atomic overhead
§Cache Optimization
- Head and tail indices are cache-line padded to prevent false sharing
- Buffer capacity is always a power of 2 for fast modulo via bitwise AND
Implementations§
Source§impl<T> LockFreeRing<T>
impl<T> LockFreeRing<T>
Sourcepub fn new(capacity: usize) -> Self
pub fn new(capacity: usize) -> Self
Creates a new ring buffer with the specified capacity.
The actual capacity will be rounded up to the next power of 2.
§Panics
Panics if capacity is 0 or allocation fails.
Sourcepub fn with_default_capacity() -> Self
pub fn with_default_capacity() -> Self
Creates a ring buffer with the default capacity.
Sourcepub fn free_slots(&self) -> usize
pub fn free_slots(&self) -> usize
Returns the number of free slots.
Sourcepub fn enqueue(&self, item: T) -> Result<(), T>
pub fn enqueue(&self, item: T) -> Result<(), T>
Enqueues a single item.
Returns Err(item) if the ring is full.
Sourcepub fn enqueue_batch(&self, items: &[T]) -> usizewhere
T: Copy,
pub fn enqueue_batch(&self, items: &[T]) -> usizewhere
T: Copy,
Enqueues multiple items in a batch.
Returns the number of items successfully enqueued. Items that couldn’t be enqueued remain in the slice.
Sourcepub fn dequeue_batch(&self, out: &mut [T]) -> usizewhere
T: Copy,
pub fn dequeue_batch(&self, out: &mut [T]) -> usizewhere
T: Copy,
Dequeues multiple items in a batch.
Returns the number of items dequeued.
Trait Implementations§
Source§impl<T> Debug for LockFreeRing<T>
impl<T> Debug for LockFreeRing<T>
Source§impl<T> Drop for LockFreeRing<T>
impl<T> Drop for LockFreeRing<T>
impl<T: Send> Send for LockFreeRing<T>
impl<T: Send> Sync for LockFreeRing<T>
Auto Trait Implementations§
impl<T> !Freeze for LockFreeRing<T>
impl<T> !RefUnwindSafe for LockFreeRing<T>
impl<T> Unpin for LockFreeRing<T>
impl<T> UnsafeUnpin for LockFreeRing<T>
impl<T> UnwindSafe for LockFreeRing<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more