Skip to content

Commit 3ee7aee

Browse files
committed
Add fn repeat_with and RepeatWith
1 parent 73580f7 commit 3ee7aee

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ pub use sources::{from_fn, FromFn};
5353
pub use sources::{once, Once};
5454
pub use sources::{once_with, OnceWith};
5555
pub use sources::{repeat, Repeat};
56+
pub use sources::{repeat_with, RepeatWith};
5657

5758
/// An interface for dealing with streaming iterators.
5859
pub trait StreamingIterator {

src/sources.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,12 @@ pub fn repeat<T>(item: T) -> Repeat<T> {
7373
Repeat { item }
7474
}
7575

76+
/// Creates an iterator that endlessly returns items from a function call.
77+
#[inline]
78+
pub fn repeat_with<T, F: FnMut() -> T>(gen: F) -> RepeatWith<T, F> {
79+
RepeatWith { gen, item: None }
80+
}
81+
7682
/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
7783
#[derive(Clone, Debug)]
7884
pub struct Convert<I>
@@ -355,3 +361,29 @@ impl<T> DoubleEndedStreamingIterator for Repeat<T> {
355361
#[inline]
356362
fn advance_back(&mut self) {}
357363
}
364+
365+
/// A simple iterator that endlessly returns items from a function call.
366+
#[derive(Clone, Debug)]
367+
pub struct RepeatWith<T, F> {
368+
gen: F,
369+
item: Option<T>,
370+
}
371+
372+
impl<T, F: FnMut() -> T> StreamingIterator for RepeatWith<T, F> {
373+
type Item = T;
374+
375+
#[inline]
376+
fn advance(&mut self) {
377+
self.item = Some((self.gen)());
378+
}
379+
380+
#[inline]
381+
fn get(&self) -> Option<&Self::Item> {
382+
self.item.as_ref()
383+
}
384+
385+
#[inline]
386+
fn size_hint(&self) -> (usize, Option<usize>) {
387+
(usize::MAX, None)
388+
}
389+
}

0 commit comments

Comments
 (0)