Add AsyncIter and test for it

This commit is contained in:
Skye Jensen 2020-06-05 19:49:16 -04:00
parent 6b9a5e1609
commit 7131247e14
3 changed files with 59 additions and 1 deletions

57
src/async_iter.rs Normal file
View file

@ -0,0 +1,57 @@
use async_trait::async_trait;
use futures::stream::BoxStream;
use futures::{stream };
#[async_trait]
trait AsyncIter {
type Item: Sized;
async fn next(&mut self) -> Option<Self::Item>;
fn into_stream(self) -> BoxStream<'static, Self::Item>
where
Self: Sized + Send + 'static,
{
async fn helper<I>(mut iter: I) -> Option<(I::Item, I)>
where
I: AsyncIter,
{
let value = iter.next().await?;
Some((value, iter))
}
Box::pin(stream::unfold(self, helper))
}
}
#[cfg(test)]
mod test {
use super::*;
use futures::StreamExt;
use futures::executor;
struct Numbers(usize);
impl Numbers {
fn new() -> Self {
Numbers(0)
}
}
#[async_trait]
impl AsyncIter for Numbers {
type Item = usize;
async fn next(&mut self) -> Option<Self::Item> {
self.0 = self.0.checked_add(1)?;
Some(self.0)
}
}
#[test]
fn test_numbers() {
let a = async {
let vec1: Vec<_> = Numbers::new().into_stream().take(10).collect().await;
let vec2: Vec<_> = (1..=10).into_iter().collect();
assert_eq!(vec1, vec2);
};
executor::block_on(a);
}
}

View file

@ -1,3 +1,4 @@
mod async_iter;
mod config; mod config;
mod output; mod output;
mod tile; mod tile;

View file

@ -49,7 +49,7 @@ impl Stream for TimeStream {
type Item = Result<Block, Box<dyn Error + Send + Sync>>; type Item = Result<Block, Box<dyn Error + Send + Sync>>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let project = Pin::as_mut(&mut self).project(); let project = Pin::as_mut(&mut self).project();
ready!(Future::poll(project.delay, cx)); let () = ready!(Future::poll(project.delay, cx));
let now = Local::now(); let now = Local::now();
Pin::as_mut(&mut self) Pin::as_mut(&mut self)