use alux_ext::ext;
use core::future::Future;
use futures::{Stream, stream};
pub trait ChunksAlg {
type Chunk;
type Error;
fn next_chunk(&mut self) -> impl Future<Output = Option<Result<Self::Chunk, Self::Error>>> + Send;
}
#[ext(name = ChunksExt)]
pub impl<This> This
where
This: ChunksAlg + Send + 'static,
This::Chunk: Send,
{
fn moving(self) -> impl Stream<Item = Result<Self::Chunk, Self::Error>> {
stream::unfold(self, |mut chunks| async move {
let taken = chunks.next_chunk().await?;
Some((taken, chunks))
})
}
async fn gathered(mut self) -> Result<Vec<Self::Chunk>, Self::Error> {
let mut taken = Vec::new();
while let Some(chunk) = self.next_chunk().await {
taken.push(chunk?);
}
Ok(taken)
}
}