Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,14 @@ mod tests {
b.push(1);
b.push(2);
b.push(3);
b.push(4);

let mut iter = b.iter();
assert_eq!(&1, iter.next().unwrap());
assert_eq!(&4, iter.next_back().unwrap());
assert_eq!(&2, iter.next().unwrap());
assert_eq!(&3, iter.next().unwrap());
assert_eq!(None, iter.next());
}

test_iter(AllocRingBuffer::with_capacity(8));
Expand Down
26 changes: 25 additions & 1 deletion src/ringbuffer_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,13 @@ pub trait RingBufferExt<T>:
mod iter {
use crate::{RingBufferExt, RingBufferRead};
use core::marker::PhantomData;
use core::iter::FusedIterator;

/// RingBufferIterator holds a reference to a `RingBufferExt` and iterates over it. `index` is the
/// current iterator position.
pub struct RingBufferIterator<'rb, T, RB: RingBufferExt<T>> {
obj: &'rb RB,
len: usize,
index: usize,
phantom: PhantomData<T>,
}
Expand All @@ -211,6 +213,7 @@ mod iter {
pub fn new(obj: &'rb RB) -> Self {
Self {
obj,
len: obj.len(),
index: 0,
phantom: PhantomData::default(),
}
Expand All @@ -222,14 +225,35 @@ mod iter {

#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.obj.len() {
if self.index < self.len {
let res = self.obj.get(self.index as isize);
self.index += 1;
res
} else {
None
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}

impl<'rb, T: 'rb, RB: RingBufferExt<T>> FusedIterator for RingBufferIterator<'rb, T, RB> { }

impl<'rb, T: 'rb, RB: RingBufferExt<T>> ExactSizeIterator for RingBufferIterator<'rb, T, RB> { }

impl<'rb, T: 'rb, RB: RingBufferExt<T>> DoubleEndedIterator for RingBufferIterator<'rb, T, RB> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
if self.len > 0 && self.index < self.len {
let res = self.obj.get((self.len - 1) as isize);
Comment thread
NULLx76 marked this conversation as resolved.
self.len -= 1;
res
} else {
None
}
}
}

/// `RingBufferMutIterator` holds a reference to a `RingBufferExt` and iterates over it. `index` is the
Expand Down