monoio/io/stream/
mod.rs

1//! Stream trait in GAT style.
2
3mod iter;
4mod stream_ext;
5
6use std::future::Future;
7
8pub use iter::{iter, Iter};
9pub use stream_ext::StreamExt;
10
11/// A stream of values produced asynchronously in pure async/await.
12#[must_use = "streams do nothing unless polled"]
13pub trait Stream {
14    /// Values yielded by the stream.
15    type Item;
16
17    /// Attempt to pull out the next value of this stream, registering the
18    /// current task for wakeup if the value is not yet available, and returning
19    /// `None` if the stream is exhausted.
20    fn next(&mut self) -> impl Future<Output = Option<Self::Item>>;
21
22    /// Returns the bounds on the remaining length of the stream.
23    ///
24    /// Specifically, `size_hint()` returns a tuple where the first element
25    /// is the lower bound, and the second element is the upper bound.
26    ///
27    /// The second half of the tuple that is returned is an
28    /// [`Option`]`<`[`usize`]`>`. A [`None`] here means that either there
29    /// is no known upper bound, or the upper bound is larger than
30    /// [`usize`].
31    ///
32    /// # Implementation notes
33    ///
34    /// It is not enforced that a stream implementation yields the declared
35    /// number of elements. A buggy stream may yield less than the lower bound
36    /// or more than the upper bound of elements.
37    ///
38    /// `size_hint()` is primarily intended to be used for optimizations such as
39    /// reserving space for the elements of the stream, but must not be
40    /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
41    /// implementation of `size_hint()` should not lead to memory safety
42    /// violations.
43    ///
44    /// That said, the implementation should provide a correct estimation,
45    /// because otherwise it would be a violation of the trait's protocol.
46    ///
47    /// The default implementation returns `(0, `[`None`]`)` which is correct
48    /// for any stream.
49    #[inline]
50    fn size_hint(&self) -> (usize, Option<usize>) {
51        (0, None)
52    }
53}
54
55impl<S: ?Sized + Stream> Stream for &mut S {
56    type Item = S::Item;
57
58    fn next(&mut self) -> impl Future<Output = Option<Self::Item>> {
59        (**self).next()
60    }
61}
62
63// Just a helper function to ensure the streams we're returning all have the
64// right implementations.
65pub(crate) fn assert_stream<T, S>(stream: S) -> S
66where
67    S: Stream<Item = T>,
68{
69    stream
70}