clone_stream/
lib.rs

1//! # Clone streams with `clone-stream`
2//!
3//! This module provides a way to fork a stream into multiple streams that can
4//! be cloned and used independently. The `CloneStream` struct implements the
5//! `Stream` trait and allows for cloning of the stream, while the `Fork` struct
6//! manages the underlying stream and its clones.
7//!
8//! The [`ForkStream`] trait is implemented for any stream that yields items
9//! that implement the `Clone` trait. This allows for easy conversion of a
10//! stream into a [`CloneStream`].
11mod clone;
12mod fork;
13
14mod states;
15
16pub use clone::CloneStream;
17use fork::Fork;
18use futures::Stream;
19
20impl<BaseStream> From<BaseStream> for CloneStream<BaseStream>
21where
22    BaseStream: Stream<Item: Clone>,
23{
24    /// Forks the stream into a new stream that can be cloned.
25    fn from(base_stream: BaseStream) -> CloneStream<BaseStream> {
26        CloneStream::from(Fork::new(base_stream))
27    }
28}
29
30/// A trait that turns an input [`Stream`] with [`Stream::Item`]s that implement
31/// [`Clone`] into a stream that is [`Clone`]. The output stream yields items of
32/// the same type as the input stream.
33pub trait ForkStream: Stream<Item: Clone> + Sized {
34    /// Forks the stream into a new stream that can be cloned.
35    ///
36    /// # Example
37    ///
38    /// ```rust
39    /// use clone_stream::ForkStream;
40    /// use futures::{FutureExt, StreamExt, stream};
41    /// let non_clone_stream = stream::iter(0..10);
42    /// let clone_stream = non_clone_stream.fork();
43    /// let mut cloned_stream = clone_stream.clone();
44    /// ```
45    fn fork(self) -> CloneStream<Self> {
46        CloneStream::from(Fork::new(self))
47    }
48}
49
50impl<BaseStream> ForkStream for BaseStream where BaseStream: Stream<Item: Clone> {}