Skip to main content

RingBuffer

Struct RingBuffer 

Source
pub struct RingBuffer<T> { /* private fields */ }
Expand description

A lock-free ring buffer with runtime-specified capacity.

This buffer supports both SPSC and MPSC modes:

  • SPSC: Single producer uses push, single consumer uses pop
  • MPSC: Multiple producers use claim_and_write, single consumer uses pop

§Safety

The buffer is safe to use from multiple threads as long as:

  • In SPSC mode: Exactly one producer and one consumer thread
  • In MPSC mode: Any number of producers, exactly one consumer thread

Implementations§

Source§

impl<T> RingBuffer<T>

Source

pub fn new(capacity: usize) -> Self

Creates a new ring buffer with the given capacity.

The capacity will be clamped to [MIN_BUFFER_SIZE, MAX_BUFFER_SIZE] and rounded up to the next power of 2 for efficiency.

§Panics

Panics if capacity is 0.

Source

pub fn capacity(&self) -> usize

Returns the capacity of the buffer.

Source

pub fn is_empty(&self) -> bool

Returns true if the buffer is empty.

Note: This is a snapshot and may change immediately after returning. Uses Relaxed ordering since this is an approximate query.

Source

pub fn is_full(&self) -> bool

Returns true if the buffer is full.

Note: This is a snapshot and may change immediately after returning. Uses Relaxed ordering since this is an approximate query.

Source

pub fn len(&self) -> usize

Returns the current number of items in the buffer.

Note: This is a snapshot and may change immediately after returning. Uses Relaxed ordering since this is an approximate query.

Source

pub fn free_slots(&self) -> usize

Returns the number of free slots in the buffer.

Note: This is a snapshot and may change immediately after returning.

Source

pub fn push(&self, item: T) -> Result<(), T>

Pushes an item to the buffer (SPSC mode).

Returns Ok(()) if successful, or Err(item) if the buffer is full.

§Errors

Returns the item back if the buffer is full.

§Safety

In SPSC mode, this must only be called by the single producer thread.

Source

pub fn pop(&self) -> Option<T>

Pops an item from the buffer.

Returns Some(item) if successful, or None if the buffer is empty.

§Safety

This must only be called by the single consumer thread.

Source

pub fn peek(&self) -> Option<&T>

Peeks at the next item without removing it.

Returns None if the buffer is empty.

§Safety

This must only be called by the single consumer thread.

Source

pub fn claim_slot(&self) -> Option<usize>

Claims a slot for writing (MPSC mode).

Returns the slot index if successful, or None if the buffer is full. The caller must then write to the slot and call publish_slot.

This uses atomic increment on claim_counter to ensure each producer gets a unique slot.

Source

pub unsafe fn write_slot(&self, slot: usize, item: T)

Writes to a claimed slot (MPSC mode).

§Safety

The slot must have been obtained from claim_slot and not yet written to. After calling this, you must call try_publish to make the item visible.

Source

pub fn try_advance_tail(&self, target_tail: usize) -> bool

Attempts to publish written slots up to the given claim (MPSC mode).

This advances the tail if all slots up to claim have been written. Returns true if the tail was advanced.

In MPSC mode, producers write out-of-order but the consumer sees items in order. This function is typically called by each producer after writing, but only succeeds when all prior slots are also written.

For simplicity, this implementation uses a “publish barrier” approach: producers write to their slots, then the tail is advanced by whichever producer happens to have the lowest claimed slot.

Source

pub fn push_batch(&self, items: impl IntoIterator<Item = T>) -> usize

Pushes multiple items to the buffer.

Returns the number of items successfully pushed.

§Safety

In SPSC mode, this must only be called by the single producer thread.

Source

pub fn pop_batch(&self, max_count: usize) -> Vec<T>

Pops multiple items from the buffer.

Returns a vector of up to max_count items.

§Safety

This must only be called by the single consumer thread.

§Performance Warning

This method allocates a Vec on every call. Do not use on hot paths where allocation overhead matters. For zero-allocation consumption, use pop_each or pop_batch_into.

Source

pub fn pop_each<F>(&self, max_count: usize, f: F) -> usize
where F: FnMut(T) -> bool,

Pops items and calls a callback for each (zero-allocation).

Processing stops when:

  • max_count items have been processed
  • The buffer becomes empty
  • The callback returns false

Returns the number of items processed.

§Safety

This must only be called by the single consumer thread.

Source

pub fn pop_batch_into(&self, buffer: &mut [MaybeUninit<T>]) -> usize

Pops items into a caller-provided buffer (zero-allocation).

Returns the number of items popped.

§Safety

This must only be called by the single consumer thread. After this method returns n, the first n elements of buffer are initialized.

Source

pub fn reset(&mut self)

Resets the buffer to empty state.

§Safety

This must only be called when no other threads are accessing the buffer.

Trait Implementations§

Source§

impl<T: Debug> Debug for RingBuffer<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Drop for RingBuffer<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: Send> Send for RingBuffer<T>

Source§

impl<T: Send> Sync for RingBuffer<T>

Auto Trait Implementations§

§

impl<T> !Freeze for RingBuffer<T>

§

impl<T> !RefUnwindSafe for RingBuffer<T>

§

impl<T> Unpin for RingBuffer<T>

§

impl<T> UnwindSafe for RingBuffer<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more