Add AsyncIter and test for it
This commit is contained in:
parent
6b9a5e1609
commit
7131247e14
57
src/async_iter.rs
Normal file
57
src/async_iter.rs
Normal 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);
|
||||
}
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
mod async_iter;
|
||||
mod config;
|
||||
mod output;
|
||||
mod tile;
|
||||
|
|
|
@ -49,7 +49,7 @@ impl Stream for TimeStream {
|
|||
type Item = Result<Block, Box<dyn Error + Send + Sync>>;
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
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();
|
||||
Pin::as_mut(&mut self)
|
||||
|
|
Loading…
Reference in a new issue