Skip to content

Commit 73580f7

Browse files
committed
Add fn repeat and Repeat
1 parent 9580696 commit 73580f7

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ pub use sources::{empty, Empty};
5252
pub use sources::{from_fn, FromFn};
5353
pub use sources::{once, Once};
5454
pub use sources::{once_with, OnceWith};
55+
pub use sources::{repeat, Repeat};
5556

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

src/sources.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::{DoubleEndedStreamingIterator, StreamingIterator};
22
use core::marker::PhantomData;
3+
use core::usize;
34

45
/// Turns a normal, non-streaming iterator into a streaming iterator.
56
///
@@ -66,6 +67,12 @@ pub fn once_with<T, F: FnOnce() -> T>(gen: F) -> OnceWith<T, F> {
6667
}
6768
}
6869

70+
/// Creates an iterator that returns an item endlessly.
71+
#[inline]
72+
pub fn repeat<T>(item: T) -> Repeat<T> {
73+
Repeat { item }
74+
}
75+
6976
/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
7077
#[derive(Clone, Debug)]
7178
pub struct Convert<I>
@@ -320,3 +327,31 @@ impl<T, F: FnOnce() -> T> DoubleEndedStreamingIterator for OnceWith<T, F> {
320327
self.advance();
321328
}
322329
}
330+
331+
/// A simple iterator that repeats an item endlessly.
332+
#[derive(Clone, Debug)]
333+
pub struct Repeat<T> {
334+
item: T,
335+
}
336+
337+
impl<T> StreamingIterator for Repeat<T> {
338+
type Item = T;
339+
340+
#[inline]
341+
fn advance(&mut self) {}
342+
343+
#[inline]
344+
fn get(&self) -> Option<&Self::Item> {
345+
Some(&self.item)
346+
}
347+
348+
#[inline]
349+
fn size_hint(&self) -> (usize, Option<usize>) {
350+
(usize::MAX, None)
351+
}
352+
}
353+
354+
impl<T> DoubleEndedStreamingIterator for Repeat<T> {
355+
#[inline]
356+
fn advance_back(&mut self) {}
357+
}

0 commit comments

Comments
 (0)