use crate::{AlgebraMessage, BoundedAlgebraSender};
use futures::stream::{AbortHandle, Abortable};
use futures::{Stream, StreamExt};
use std::future::Future;
use std::num::NonZeroUsize;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
pub type AlgebraStream<Operation, Reply> = Abortable<ReceiverStream<AlgebraMessage<Operation, Reply>>>;
pub fn bounded_algebra_channel<Operation, Reply>(
capacity: NonZeroUsize,
) -> (BoundedAlgebraSender<Operation, Reply>, AlgebraStream<Operation, Reply>) {
let (sender, receiver) = mpsc::channel(capacity.get());
let (stop, stopped) = AbortHandle::new_pair();
(BoundedAlgebraSender::from_sender(sender, stop), Abortable::new(ReceiverStream::new(receiver), stopped))
}
pub async fn interpret_stream<Message, Apply, Applied>(
mut stream: impl Stream<Item = Message> + Unpin,
mut apply: Apply,
) where
Apply: FnMut(Message) -> Applied,
Applied: Future<Output = ()>,
{
while let Some(message) = stream.next().await {
apply(message).await;
}
}