Skip to content

Commit 9580696

Browse files
committed
Add fn from_fn and FromFn
1 parent 857288e commit 9580696

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ mod sources;
4949
pub use sources::{convert, Convert};
5050
pub use sources::{convert_ref, ConvertRef};
5151
pub use sources::{empty, Empty};
52+
pub use sources::{from_fn, FromFn};
5253
pub use sources::{once, Once};
5354
pub use sources::{once_with, OnceWith};
5455

src/sources.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,13 @@ pub fn empty<T>() -> Empty<T> {
4242
}
4343
}
4444

45-
/// Creates an iterator that returns exactly one item
45+
/// Creates an iterator that returns items from a function call.
46+
#[inline]
47+
pub fn from_fn<T, F: FnMut() -> Option<T>>(gen: F) -> FromFn<T, F> {
48+
FromFn { gen, item: None }
49+
}
50+
51+
/// Creates an iterator that returns exactly one item.
4652
#[inline]
4753
pub fn once<T>(item: T) -> Once<T> {
4854
Once {
@@ -219,6 +225,27 @@ impl<T> DoubleEndedStreamingIterator for Empty<T> {
219225
fn advance_back(&mut self) {}
220226
}
221227

228+
/// A simple iterator that returns items from a function call.
229+
#[derive(Clone, Debug)]
230+
pub struct FromFn<T, F> {
231+
gen: F,
232+
item: Option<T>,
233+
}
234+
235+
impl<T, F: FnMut() -> Option<T>> StreamingIterator for FromFn<T, F> {
236+
type Item = T;
237+
238+
#[inline]
239+
fn advance(&mut self) {
240+
self.item = (self.gen)();
241+
}
242+
243+
#[inline]
244+
fn get(&self) -> Option<&Self::Item> {
245+
self.item.as_ref()
246+
}
247+
}
248+
222249
/// A simple iterator that returns exactly one item.
223250
#[derive(Clone, Debug)]
224251
pub struct Once<T> {

0 commit comments

Comments
 (0)