clone_stream/lib.rs
1//! # Lazily 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.
5//!
6//! The [`CloneStream`] struct implements the
7//! [`Stream`] trait and allows for cloning of the stream, while the [`Fork`]
8//! struct manages the underlying "base" (or input) stream and the other sibling
9//! stream clones.
10//!
11//! The [`ForkStream`] trait is implemented for any stream that yields items
12//! that implement the `Clone` trait. This allows for easy conversion of a
13//! stream into a [`CloneStream`]. Just import this trait if you want to use the
14//! functionality in this library.
15mod clone;
16mod fork;
17
18mod states;
19
20pub use clone::CloneStream;
21use fork::Fork;
22use futures::Stream;
23
24impl<BaseStream> From<BaseStream> for CloneStream<BaseStream>
25where
26 BaseStream: Stream<Item: Clone>,
27{
28 /// Forks the stream into a new stream that can be cloned.
29 fn from(base_stream: BaseStream) -> CloneStream<BaseStream> {
30 CloneStream::from(Fork::new(base_stream))
31 }
32}
33
34/// A trait that turns an input [`Stream`] with [`Stream::Item`]s that implement
35/// [`Clone`] into a stream that is [`Clone`]. The output stream yields items of
36/// the same type as the input stream.
37pub trait ForkStream: Stream<Item: Clone> + Sized {
38 /// Forks the stream into a new stream that can be cloned.
39 ///
40 /// # Example
41 ///
42 /// ```rust
43 /// use clone_stream::ForkStream;
44 /// use futures::{FutureExt, StreamExt, stream};
45 /// let non_clone_stream = stream::iter(0..10);
46 /// let clone_stream = non_clone_stream.fork();
47 /// let mut cloned_stream = clone_stream.clone();
48 /// ```
49 fn fork(self) -> CloneStream<Self> {
50 CloneStream::from(Fork::new(self))
51 }
52}
53
54impl<BaseStream> ForkStream for BaseStream where BaseStream: Stream<Item: Clone> {}