Skip to content

Commit bcf58d0

Browse files
committed
Add fn once and Once
1 parent 5173182 commit bcf58d0

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
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::{once, Once};
5253

5354
/// An interface for dealing with streaming iterators.
5455
pub trait StreamingIterator {

src/sources.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ pub fn empty<T>() -> Empty<T> {
4242
}
4343
}
4444

45+
/// Creates an iterator that returns exactly one item
46+
#[inline]
47+
pub fn once<T>(item: T) -> Once<T> {
48+
Once {
49+
first: true,
50+
item: Some(item),
51+
}
52+
}
53+
4554
/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
4655
#[derive(Clone, Debug)]
4756
pub struct Convert<I>
@@ -200,3 +209,41 @@ impl<T> DoubleEndedStreamingIterator for Empty<T> {
200209
#[inline]
201210
fn advance_back(&mut self) {}
202211
}
212+
213+
/// A simple iterator that returns exactly one item.
214+
#[derive(Clone, Debug)]
215+
pub struct Once<T> {
216+
first: bool,
217+
item: Option<T>,
218+
}
219+
220+
impl<T> StreamingIterator for Once<T> {
221+
type Item = T;
222+
223+
#[inline]
224+
fn advance(&mut self) {
225+
if self.first {
226+
self.first = false;
227+
} else {
228+
self.item = None;
229+
}
230+
}
231+
232+
#[inline]
233+
fn get(&self) -> Option<&Self::Item> {
234+
self.item.as_ref()
235+
}
236+
237+
#[inline]
238+
fn size_hint(&self) -> (usize, Option<usize>) {
239+
let len = self.first as usize;
240+
(len, Some(len))
241+
}
242+
}
243+
244+
impl<T> DoubleEndedStreamingIterator for Once<T> {
245+
#[inline]
246+
fn advance_back(&mut self) {
247+
self.advance();
248+
}
249+
}

0 commit comments

Comments
 (0)