channels_io/source/mod.rs
1//! [`Source`] and [`AsyncSource`] traits.
2
3use core::pin::Pin;
4use core::task::{Context, Poll};
5
6use crate::util::assert_future;
7
8mod next;
9
10pub use self::next::Next;
11
12/// This trait allows receiving items from somewhere.
13///
14/// Types implementing this trait are called "sources".
15pub trait Source {
16 /// The type of items the source receives.
17 type Item;
18
19 /// Get the next item.
20 fn next(&mut self) -> Self::Item;
21
22 /// Get an estimation of the number of items yet to be received.
23 ///
24 /// Returns a tuple where the 2 elements are the lower and upper bounds of the number
25 /// of items expected to be received. The upper bound is an `Option<usize>` to account
26 /// for cases where the upper bound is not known. In such cases, implementations should
27 /// return `None` as the upper bound.
28 ///
29 /// The default implementation returns `(0, None)`.
30 fn size_hint(&self) -> (usize, Option<usize>) {
31 (0, None)
32 }
33}
34
35/// Extension trait for [`Source`].
36pub trait SourceExt: Source {}
37
38impl<T: Source + ?Sized> SourceExt for T {}
39
40/// The asynchronous version of [`Source`].
41pub trait AsyncSource {
42 /// The type of items the source receives.
43 type Item;
44
45 /// Attempt to receive the next item from the source.
46 fn poll_next(
47 self: Pin<&mut Self>,
48 cx: &mut Context,
49 ) -> Poll<Self::Item>;
50
51 /// Get an estimation of the number of items yet to be received.
52 ///
53 /// Returns a tuple where the 2 elements are the lower and upper bounds of the number
54 /// of items expected to be received. The upper bound is an `Option<usize>` to account
55 /// for cases where the upper bound is not known. In such cases, implementations should
56 /// return `None` as the upper bound.
57 ///
58 /// The default implementation returns `(0, None)`.
59 fn size_hint(&self) -> (usize, Option<usize>) {
60 (0, None)
61 }
62}
63
64/// Extension trait for [`AsyncSource`].
65pub trait AsyncSourceExt: AsyncSource {
66 /// The asynchronous version of [`next()`].
67 ///
68 /// [`next()`]: Source::next
69 fn next(&mut self) -> Next<'_, Self>
70 where
71 Self: Unpin,
72 {
73 assert_future::<Self::Item, _>(Next::new(self))
74 }
75}
76
77impl<T: AsyncSource + ?Sized> AsyncSourceExt for T {}