1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
use crate::ops::DerefMut;
use crate::pin::Pin;
use crate::task::{Context, Poll};
/// 用于处理异步迭代器的接口。
///
/// 这是主流 trait。
/// 有关一般的流概念的更多信息,请参见 [模块级文档][module-level documentation]。
/// 特别是,您可能想知道如何 [实现 `Stream`][impl]。
///
/// [module-level documentation]: index.html
/// [impl]: index.html#implementing-stream
#[unstable(feature = "async_stream", issue = "79024")]
#[must_use = "streams do nothing unless polled"]
pub trait Stream {
/// 流产生的项的类型。
type Item;
/// 尝试拉出该流的下一个值,如果该值尚不可用,则注册当前任务以进行唤醒,如果流已用尽,则返回 `None`。
///
/// # 返回值
///
/// 有几个可能的返回值,每个返回值指示不同的流状态:
///
/// - `Poll::Pending` 意味着这个流的下一个值还没有准备好。实现将确保在准备好下一个值时将通知当前任务。
///
/// - `Poll::Ready(Some(val))` 表示流已成功生成值 `val`,并且可能会在后续 `poll_next` 调用中生成更多值。
///
/// - `Poll::Ready(None)` 表示流已终止,不应再次调用 `poll_next`。
///
/// # Panics
///
/// 流完成后 (从 `poll_next` 返回 `Ready(None)`),再次调用其 `poll_next` 方法可能会 panic,永远阻塞或引起其他类型的问题。`Stream` trait 对这种调用的效果没有任何要求。
///
/// 但是,由于 `poll_next` 方法未标记为 `unsafe`,因此适用 Rust 的通常规则:调用决不能引起未定义的行为 (内存损坏,对 `unsafe` 函数的错误使用等),而与流的状态无关。
///
///
///
///
///
///
///
///
///
///
///
///
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
/// 返回流剩余长度上的边界。
///
/// 具体来说,`size_hint()` 返回一个元组,其中第一个元素是下界,第二个元素是上界。
///
/// 返回的元组的后半部分是 <code>[Option]<[usize]></code>。
/// 这里的 [`None`] 表示没有已知的上限,或者该上限大于 [`usize`]。
///
/// # 实现说明
///
/// 流实现不会产生声明数量的元素,这不是强制性的。buggy 流产生的值可能小于元素的下限,也可能大于元素的上限。
///
/// `size_hint()` 主要用于优化,例如为流的元素保留空间,但不能被信任,例如省略不安全代码中的边界检查。
/// `size_hint()` 的不正确实现不应导致违反内存安全性。
///
/// 也就是说,该实现应提供正确的估计,因为否则将违反 trait 的协议。
///
/// 默认实现返回了 <code>(0, [None])</code>,这对于任何流都是正确的。
///
///
///
///
///
///
///
///
///
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
}
#[unstable(feature = "async_stream", issue = "79024")]
impl<S: ?Sized + Stream + Unpin> Stream for &mut S {
type Item = S::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
S::poll_next(Pin::new(&mut **self), cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
}
#[unstable(feature = "async_stream", issue = "79024")]
impl<P> Stream for Pin<P>
where
P: DerefMut,
P::Target: Stream,
{
type Item = <P::Target as Stream>::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
<P::Target as Stream>::poll_next(self.as_deref_mut(), cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
}