Skip to content

Commit

Permalink
Add peek methods to Consumer, bump version
Browse files Browse the repository at this point in the history
  • Loading branch information
agerasev committed Aug 16, 2024
1 parent 9c11aeb commit 3d97c60
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ readme = "README.md"
license = "MIT/Apache-2.0"

[workspace.dependencies]
ringbuf = { path = ".", version = "0.4.2" }
ringbuf = { path = ".", version = "0.4.3" }

[workspace]
members = ["async", "blocking"]

[package]
name = "ringbuf"
version = "0.4.2"
version = "0.4.3"
edition.workspace = true
authors.workspace = true
description = "Lock-free SPSC FIFO ring buffer with direct access to inner data"
Expand Down
35 changes: 32 additions & 3 deletions src/traits/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,21 @@ pub trait Consumer: Observer {
}
}

/// Removes items from the ring buffer and writes them into an uninit slice.
/// Returns the reference to the eldest item without removing it from the buffer.
///
/// Returns count of items been removed.
fn pop_slice_uninit(&mut self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
/// Returns `None` if the ring buffer is empty.
fn try_peek(&self) -> Option<&Self::Item> {
if !self.is_empty() {
Some(unsafe { self.occupied_slices().0.get_unchecked(0).assume_init_ref() })
} else {
None
}
}

/// Copies items from the ring buffer to an uninit slice without removing them from the ring buffer.
///
/// Returns a number of items being copied.
fn peek_slice_uninit(&self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
let (left, right) = self.occupied_slices();
let count = if elems.len() < left.len() {
move_uninit_slice(elems, unsafe { left.get_unchecked(..elems.len()) });
Expand All @@ -141,6 +152,24 @@ pub trait Consumer: Observer {
right.len()
}
};
count
}

/// Copies items from the ring buffer to a slice without removing them from the ring buffer.
///
/// Returns a number of items being copied.
fn peek_slice(&self, elems: &mut [Self::Item]) -> usize
where
Self::Item: Copy,
{
self.peek_slice_uninit(unsafe { slice_as_uninit_mut(elems) })
}

/// Removes items from the ring buffer and writes them into an uninit slice.
///
/// Returns count of items been removed.
fn pop_slice_uninit(&mut self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
let count = self.peek_slice_uninit(elems);
unsafe { self.advance_read_index(count) };
count
}
Expand Down

0 comments on commit 3d97c60

Please sign in to comment.