Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream::cycle implementation #34

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions examples/stream-cycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//! Repeats given stream values and sum them
#![feature(async_await)]

use async_std::io;
use async_std::prelude::*;
use async_std::stream;
use async_std::task;

fn main() -> io::Result<()> {
task::block_on(async {
let mut s = stream::cycle(vec![6, 7, 8]);
let mut total = 0;

while let Some(v) = s.next().await {
total += v;
if total == 42 {
println!("Found {} the meaning of life!", total);
break;
}
}

Ok(())
})
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example is cool, but I think it's probably fine to just have the doc test for now. In #131 and #129 there are quite a few more methods, and I think it'd be wise to try and keep our line count down where possible.

57 changes: 57 additions & 0 deletions src/stream/cycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use std::pin::Pin;
use std::sync::Mutex;

use crate::task::{Context, Poll};

/// Creates a stream that yields the given elements continually.
///
/// # Examples
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::cycle(vec![1, 2, 3]);
///
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In std the API is:

let a = [1, 2, 3];

let mut it = a.iter().cycle();

assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&1));
assert_eq!(it.next(), Some(&2));
assert_eq!(it.next(), Some(&3));
assert_eq!(it.next(), Some(&1));

I'd expect this API to be (with #125 landed):

let a = [1, 2, 3];

let mut it = a.into_stream().cycle();

assert_eq!(it.next().await, Some(&1));
assert_eq!(it.next().await, Some(&2));
assert_eq!(it.next().await, Some(&3));
assert_eq!(it.next().await, Some(&1));
assert_eq!(it.next().await, Some(&2));
assert_eq!(it.next().await, Some(&3));
assert_eq!(it.next().await, Some(&1));

Similar, but subtly different in that it's more generic, which should make it more widely applicable!

/// assert_eq!(s.next().await, Some(1));
/// assert_eq!(s.next().await, Some(2));
/// assert_eq!(s.next().await, Some(3));
/// assert_eq!(s.next().await, Some(1));
/// assert_eq!(s.next().await, Some(2));
/// #
/// # }) }
/// ```
pub fn cycle<T>(items: Vec<T>) -> Cycle<T>
where
T: Clone,
{
Cycle {
items,
cursor: Mutex::new(0_usize),
}
}

/// A stream that yields the given elements continually.
///
/// This stream is constructed by the [`cycle`] function.
///
/// [`cycle`]: fn.cycle.html
#[derive(Debug)]
pub struct Cycle<T> {
items: Vec<T>,
cursor: Mutex<usize>,
}

impl<T: Clone> futures::Stream for Cycle<T> {
type Item = T;

fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let cursor = &mut *self.cursor.lock().unwrap();
let p = Poll::Ready(self.items.get(*cursor).map(|x| x.to_owned()));
*cursor = (*cursor + 1_usize) % self.items.len();
p
}
}
2 changes: 2 additions & 0 deletions src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
//! # }) }
//! ```
pub use cycle::{cycle, Cycle};
pub use empty::{empty, Empty};
pub use once::{once, Once};
pub use repeat::{repeat, Repeat};
pub use stream::{Stream, Take};

mod cycle;
mod empty;
mod once;
mod repeat;
Expand Down