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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use crate::iter::{InPlaceIterable, Iterator};
use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};

mod array_chunks;
mod by_ref_sized;
mod chain;
mod cloned;
mod copied;
mod cycle;
mod enumerate;
mod filter;
mod filter_map;
mod flatten;
mod fuse;
mod inspect;
mod intersperse;
mod map;
mod map_while;
mod peekable;
mod rev;
mod scan;
mod skip;
mod skip_while;
mod step_by;
mod take;
mod take_while;
mod zip;

#[stable(feature = "rust1", since = "1.0.0")]
pub use self::{
    chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap,
    flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev,
    scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip,
};

#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
pub use self::array_chunks::ArrayChunks;

#[unstable(feature = "std_internals", issue = "none")]
pub use self::by_ref_sized::ByRefSized;

#[stable(feature = "iter_cloned", since = "1.1.0")]
pub use self::cloned::Cloned;

#[stable(feature = "iterator_step_by", since = "1.28.0")]
pub use self::step_by::StepBy;

#[stable(feature = "iterator_flatten", since = "1.29.0")]
pub use self::flatten::Flatten;

#[stable(feature = "iter_copied", since = "1.36.0")]
pub use self::copied::Copied;

#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
pub use self::intersperse::{Intersperse, IntersperseWith};

#[stable(feature = "iter_map_while", since = "1.57.0")]
pub use self::map_while::MapWhile;

#[unstable(feature = "trusted_random_access", issue = "none")]
pub use self::zip::TrustedRandomAccess;

#[unstable(feature = "trusted_random_access", issue = "none")]
pub use self::zip::TrustedRandomAccessNoCoerce;

#[stable(feature = "iter_zip", since = "1.59.0")]
pub use self::zip::zip;

/// 此 trait 在以下条件下提供对迭代器适配器管道中源级的传递访问
/// * 迭代器源 `S` 本身实现 `SourceIter<Source = S>`
/// * 在源和管道消费者之间的管道中,每个适配器都有 trait 的委派实现。
///
/// 当源是拥有的迭代器结构体 (通常称为 `IntoIter`) 时,这对于专门化 [`FromIterator`] 实现或在迭代器部分用尽之后恢复其余元素很有用。
///
///
/// 注意,实现不一定必须提供对管道最内层源的访问。有状态的中间适配器可能会急切地评估管道的一部分,并将其内部存储公开为源。
///
/// 这个 trait 是不安全的,因为实现者必须维护额外的安全属性。
/// 有关详细信息,请参见 [`as_inner`]。
///
/// 这个 trait 的主要用途是就地迭代。有关详细信息,请参见 [`vec::in_place_collect`] 模块文档。
///
/// [`vec::in_place_collect`]: ../../../../alloc/vec/in_place_collect/index.html
///
/// # Examples
///
/// 检索部分消耗的源:
///
/// ```
/// # #![feature(inplace_iteration)]
/// # use std::iter::SourceIter;
///
/// let mut iter = vec![9, 9, 9].into_iter().map(|i| i * i);
/// let _ = iter.next();
/// let mut remainder = std::mem::replace(unsafe { iter.as_inner() }, Vec::new().into_iter());
/// println!("n = {} elements remaining", remainder.len());
/// ```
///
/// [`FromIterator`]: crate::iter::FromIterator
/// [`as_inner`]: SourceIter::as_inner
///
///
///
///
///
///
#[unstable(issue = "none", feature = "inplace_iteration")]
#[doc(hidden)]
#[rustc_specialization_trait]
pub unsafe trait SourceIter {
    /// 迭代器管道中的源阶段。
    type Source;

    /// 检索迭代器管道的源。
    ///
    /// # Safety
    ///
    /// 的实现必须为其生命周期返回相同的可变引用,除非被调用者替换。
    /// 调用者只有在停止迭代并在提取源之后丢弃迭代器管道时才可以替换引用。
    ///
    /// 这意味着迭代器适配器可以依赖在迭代过程中未更改的源,但不能在其 Drop 实现中依赖它。
    ///
    /// 实现此方法意味着适配器放弃对其源的仅私有访问,并且只能依赖基于方法接收者类型的保证。
    /// 缺少受限制的访问还要求适配器即使在访问其内部时也必须维护源的公共 API。
    ///
    /// 依次,调用者必须期望源处于与其公共 API 一致的任何状态,因为位于源和源之间的适配器具有相同的访问权限。
    /// 特别是适配器可能消耗了比严格需要更多的元素。
    ///
    /// 这些要求的总体目标是让管道的消费者使用
    /// * 迭代停止后保留在源中的所有内容
    /// * 推进消费迭代器而变得未使用的内存
    ///
    /// [`next()`]: Iterator::next()
    ///
    ///
    ///
    ///
    ///
    ///
    unsafe fn as_inner(&mut self) -> &mut Self::Source;
}

/// 一个迭代器适配器,只要底层迭代器产生值,就会产生输出,其中 `Try::branch` 表示 `ControlFlow::Continue`。
///
///
/// 如果遇到 `ControlFlow::Break`,则迭代器将停止,并存储剩余部分。
///
pub(crate) struct GenericShunt<'a, I, R> {
    iter: I,
    residual: &'a mut Option<R>,
}

/// 处理给定的迭代器,就像它产生了该项的 `Try::Output` 类型一样。
/// 遇到的任何 `Try::Residual` 都会停止内部迭代器,并传播回整个结果。
///
pub(crate) fn try_process<I, T, R, F, U>(iter: I, mut f: F) -> ChangeOutputType<I::Item, U>
where
    I: Iterator<Item: Try<Output = T, Residual = R>>,
    for<'a> F: FnMut(GenericShunt<'a, I, R>) -> U,
    R: Residual<U>,
{
    let mut residual = None;
    let shunt = GenericShunt { iter, residual: &mut residual };
    let value = f(shunt);
    match residual {
        Some(r) => FromResidual::from_residual(r),
        None => Try::from_output(value),
    }
}

impl<I, R> Iterator for GenericShunt<'_, I, R>
where
    I: Iterator<Item: Try<Residual = R>>,
{
    type Item = <I::Item as Try>::Output;

    fn next(&mut self) -> Option<Self::Item> {
        self.try_for_each(ControlFlow::Break).break_value()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.residual.is_some() {
            (0, Some(0))
        } else {
            let (_, upper) = self.iter.size_hint();
            (0, upper)
        }
    }

    fn try_fold<B, F, T>(&mut self, init: B, mut f: F) -> T
    where
        F: FnMut(B, Self::Item) -> T,
        T: Try<Output = B>,
    {
        self.iter
            .try_fold(init, |acc, x| match Try::branch(x) {
                ControlFlow::Continue(x) => ControlFlow::from_try(f(acc, x)),
                ControlFlow::Break(r) => {
                    *self.residual = Some(r);
                    ControlFlow::Break(try { acc })
                }
            })
            .into_try()
    }

    impl_fold_via_try_fold! { fold -> try_fold }
}

#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I, R> SourceIter for GenericShunt<'_, I, R>
where
    I: SourceIter,
{
    type Source = I::Source;

    #[inline]
    unsafe fn as_inner(&mut self) -> &mut Self::Source {
        // SAFETY: 将不安全的函数转发到具有相同要求的不安全的函数
        unsafe { SourceIter::as_inner(&mut self.iter) }
    }
}

// SAFETY: GenericShunt::next 调用 `I::try_for_each`,它必须提前 `iter`,才能返回 `Some(_)`。
// 由于 `iter` 的类型为 `I: InPlaceIterable`,因此可以保证至少有一个项将从底层源中移出。
//
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I, T, R> InPlaceIterable for GenericShunt<'_, I, R> where
    I: Iterator<Item: Try<Output = T, Residual = R>> + InPlaceIterable
{
}