Skip to content

Commit 9baf814

Browse files
committed
Add peek methods to Consumer
1 parent 9c11aeb commit 9baf814

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/traits/consumer.rs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,10 +121,21 @@ pub trait Consumer: Observer {
121121
}
122122
}
123123

124-
/// Removes items from the ring buffer and writes them into an uninit slice.
124+
/// Returns the reference to the eldest item without removing it from the buffer.
125125
///
126-
/// Returns count of items been removed.
127-
fn pop_slice_uninit(&mut self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
126+
/// Returns `None` if the ring buffer is empty.
127+
fn try_peek(&self) -> Option<&Self::Item> {
128+
if !self.is_empty() {
129+
Some(unsafe { self.occupied_slices().0.get_unchecked(0).assume_init_ref() })
130+
} else {
131+
None
132+
}
133+
}
134+
135+
/// Copies items from the ring buffer to an uninit slice without removing them from the ring buffer.
136+
///
137+
/// Returns a number of items being copied.
138+
fn peek_slice_uninit(&self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
128139
let (left, right) = self.occupied_slices();
129140
let count = if elems.len() < left.len() {
130141
move_uninit_slice(elems, unsafe { left.get_unchecked(..elems.len()) });
@@ -141,6 +152,24 @@ pub trait Consumer: Observer {
141152
right.len()
142153
}
143154
};
155+
count
156+
}
157+
158+
/// Copies items from the ring buffer to a slice without removing them from the ring buffer.
159+
///
160+
/// Returns a number of items being copied.
161+
fn peek_slice(&self, elems: &mut [Self::Item]) -> usize
162+
where
163+
Self::Item: Copy,
164+
{
165+
self.peek_slice_uninit(unsafe { slice_as_uninit_mut(elems) })
166+
}
167+
168+
/// Removes items from the ring buffer and writes them into an uninit slice.
169+
///
170+
/// Returns count of items been removed.
171+
fn pop_slice_uninit(&mut self, elems: &mut [MaybeUninit<Self::Item>]) -> usize {
172+
let count = self.peek_slice_uninit(elems);
144173
unsafe { self.advance_read_index(count) };
145174
count
146175
}

0 commit comments

Comments
 (0)