Skip to content

Commit 39909a3

Browse files
author
Victor
authored
Merge pull request #42 from bgamari/double-ended-iter
Implement additional iterator traits
2 parents 268a60e + eb8ace3 commit 39909a3

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,11 +196,14 @@ mod tests {
196196
b.push(1);
197197
b.push(2);
198198
b.push(3);
199+
b.push(4);
199200

200201
let mut iter = b.iter();
201202
assert_eq!(&1, iter.next().unwrap());
203+
assert_eq!(&4, iter.next_back().unwrap());
202204
assert_eq!(&2, iter.next().unwrap());
203205
assert_eq!(&3, iter.next().unwrap());
206+
assert_eq!(None, iter.next());
204207
}
205208

206209
test_iter(AllocRingBuffer::with_capacity(8));

src/ringbuffer_trait.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,11 +197,13 @@ pub trait RingBufferExt<T>:
197197
mod iter {
198198
use crate::{RingBufferExt, RingBufferRead};
199199
use core::marker::PhantomData;
200+
use core::iter::FusedIterator;
200201

201202
/// RingBufferIterator holds a reference to a `RingBufferExt` and iterates over it. `index` is the
202203
/// current iterator position.
203204
pub struct RingBufferIterator<'rb, T, RB: RingBufferExt<T>> {
204205
obj: &'rb RB,
206+
len: usize,
205207
index: usize,
206208
phantom: PhantomData<T>,
207209
}
@@ -211,6 +213,7 @@ mod iter {
211213
pub fn new(obj: &'rb RB) -> Self {
212214
Self {
213215
obj,
216+
len: obj.len(),
214217
index: 0,
215218
phantom: PhantomData::default(),
216219
}
@@ -222,14 +225,35 @@ mod iter {
222225

223226
#[inline]
224227
fn next(&mut self) -> Option<Self::Item> {
225-
if self.index < self.obj.len() {
228+
if self.index < self.len {
226229
let res = self.obj.get(self.index as isize);
227230
self.index += 1;
228231
res
229232
} else {
230233
None
231234
}
232235
}
236+
237+
fn size_hint(&self) -> (usize, Option<usize>) {
238+
(self.len, Some(self.len))
239+
}
240+
}
241+
242+
impl<'rb, T: 'rb, RB: RingBufferExt<T>> FusedIterator for RingBufferIterator<'rb, T, RB> { }
243+
244+
impl<'rb, T: 'rb, RB: RingBufferExt<T>> ExactSizeIterator for RingBufferIterator<'rb, T, RB> { }
245+
246+
impl<'rb, T: 'rb, RB: RingBufferExt<T>> DoubleEndedIterator for RingBufferIterator<'rb, T, RB> {
247+
#[inline]
248+
fn next_back(&mut self) -> Option<Self::Item> {
249+
if self.len > 0 && self.index < self.len {
250+
let res = self.obj.get((self.len - 1) as isize);
251+
self.len -= 1;
252+
res
253+
} else {
254+
None
255+
}
256+
}
233257
}
234258

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

0 commit comments

Comments
 (0)