1 use crate::iter::{InPlaceIterable, Iterator};
2 use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, NeverShortCircuit, Residual, Try};
29 #[stable(feature = "rust1", since = "1.0.0")]
31 chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap,
32 flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev,
33 scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip,
36 #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
37 pub use self::array_chunks::ArrayChunks;
39 #[unstable(feature = "std_internals", issue = "none")]
40 pub use self::by_ref_sized::ByRefSized;
42 #[stable(feature = "iter_cloned", since = "1.1.0")]
43 pub use self::cloned::Cloned;
45 #[stable(feature = "iterator_step_by", since = "1.28.0")]
46 pub use self::step_by::StepBy;
48 #[stable(feature = "iterator_flatten", since = "1.29.0")]
49 pub use self::flatten::Flatten;
51 #[stable(feature = "iter_copied", since = "1.36.0")]
52 pub use self::copied::Copied;
54 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
55 pub use self::intersperse::{Intersperse, IntersperseWith};
57 #[stable(feature = "iter_map_while", since = "1.57.0")]
58 pub use self::map_while::MapWhile;
60 #[unstable(feature = "trusted_random_access", issue = "none")]
61 pub use self::zip::TrustedRandomAccess;
63 #[unstable(feature = "trusted_random_access", issue = "none")]
64 pub use self::zip::TrustedRandomAccessNoCoerce;
66 #[stable(feature = "iter_zip", since = "1.59.0")]
67 pub use self::zip::zip;
69 /// This trait provides transitive access to source-stage in an iterator-adapter pipeline
70 /// under the conditions that
71 /// * the iterator source `S` itself implements `SourceIter<Source = S>`
72 /// * there is a delegating implementation of this trait for each adapter in the pipeline between
73 /// the source and the pipeline consumer.
75 /// When the source is an owning iterator struct (commonly called `IntoIter`) then
76 /// this can be useful for specializing [`FromIterator`] implementations or recovering the
77 /// remaining elements after an iterator has been partially exhausted.
79 /// Note that implementations do not necessarily have to provide access to the inner-most
80 /// source of a pipeline. A stateful intermediate adapter might eagerly evaluate a part
81 /// of the pipeline and expose its internal storage as source.
83 /// The trait is unsafe because implementers must uphold additional safety properties.
84 /// See [`as_inner`] for details.
86 /// The primary use of this trait is in-place iteration. Refer to the [`vec::in_place_collect`]
87 /// module documentation for more information.
89 /// [`vec::in_place_collect`]: ../../../../alloc/vec/in_place_collect/index.html
93 /// Retrieving a partially consumed source:
96 /// # #![feature(inplace_iteration)]
97 /// # use std::iter::SourceIter;
99 /// let mut iter = vec![9, 9, 9].into_iter().map(|i| i * i);
100 /// let _ = iter.next();
101 /// let mut remainder = std::mem::replace(unsafe { iter.as_inner() }, Vec::new().into_iter());
102 /// println!("n = {} elements remaining", remainder.len());
105 /// [`FromIterator`]: crate::iter::FromIterator
106 /// [`as_inner`]: SourceIter::as_inner
107 #[unstable(issue = "none", feature = "inplace_iteration")]
109 #[rustc_specialization_trait]
110 pub unsafe trait SourceIter {
111 /// A source stage in an iterator pipeline.
114 /// Retrieve the source of an iterator pipeline.
118 /// Implementations of must return the same mutable reference for their lifetime, unless
119 /// replaced by a caller.
120 /// Callers may only replace the reference when they stopped iteration and drop the
121 /// iterator pipeline after extracting the source.
123 /// This means iterator adapters can rely on the source not changing during
124 /// iteration but they cannot rely on it in their Drop implementations.
126 /// Implementing this method means adapters relinquish private-only access to their
127 /// source and can only rely on guarantees made based on method receiver types.
128 /// The lack of restricted access also requires that adapters must uphold the source's
129 /// public API even when they have access to its internals.
131 /// Callers in turn must expect the source to be in any state that is consistent with
132 /// its public API since adapters sitting between it and the source have the same
133 /// access. In particular an adapter may have consumed more elements than strictly necessary.
135 /// The overall goal of these requirements is to let the consumer of a pipeline use
136 /// * whatever remains in the source after iteration has stopped
137 /// * the memory that has become unused by advancing a consuming iterator
139 /// [`next()`]: Iterator::next()
140 unsafe fn as_inner(&mut self) -> &mut Self::Source;
143 /// An iterator adapter that produces output as long as the underlying
144 /// iterator produces values where `Try::branch` says to `ControlFlow::Continue`.
146 /// If a `ControlFlow::Break` is encountered, the iterator stops and the
147 /// residual is stored.
148 pub(crate) struct GenericShunt<'a, I, R> {
150 residual: &'a mut Option<R>,
153 /// Process the given iterator as if it yielded a the item's `Try::Output`
154 /// type instead. Any `Try::Residual`s encountered will stop the inner iterator
155 /// and be propagated back to the overall result.
156 pub(crate) fn try_process<I, T, R, F, U>(iter: I, mut f: F) -> ChangeOutputType<I::Item, U>
158 I: Iterator<Item: Try<Output = T, Residual = R>>,
159 for<'a> F: FnMut(GenericShunt<'a, I, R>) -> U,
162 let mut residual = None;
163 let shunt = GenericShunt { iter, residual: &mut residual };
164 let value = f(shunt);
166 Some(r) => FromResidual::from_residual(r),
167 None => Try::from_output(value),
171 impl<I, R> Iterator for GenericShunt<'_, I, R>
173 I: Iterator<Item: Try<Residual = R>>,
175 type Item = <I::Item as Try>::Output;
177 fn next(&mut self) -> Option<Self::Item> {
178 self.try_for_each(ControlFlow::Break).break_value()
181 fn size_hint(&self) -> (usize, Option<usize>) {
182 if self.residual.is_some() {
185 let (_, upper) = self.iter.size_hint();
190 fn try_fold<B, F, T>(&mut self, init: B, mut f: F) -> T
192 F: FnMut(B, Self::Item) -> T,
196 .try_fold(init, |acc, x| match Try::branch(x) {
197 ControlFlow::Continue(x) => ControlFlow::from_try(f(acc, x)),
198 ControlFlow::Break(r) => {
199 *self.residual = Some(r);
200 ControlFlow::Break(try { acc })
206 fn fold<B, F>(mut self, init: B, fold: F) -> B
209 F: FnMut(B, Self::Item) -> B,
211 self.try_fold(init, NeverShortCircuit::wrap_mut_2(fold)).0
215 #[unstable(issue = "none", feature = "inplace_iteration")]
216 unsafe impl<I, R> SourceIter for GenericShunt<'_, I, R>
220 type Source = I::Source;
223 unsafe fn as_inner(&mut self) -> &mut Self::Source {
224 // SAFETY: unsafe function forwarding to unsafe function with the same requirements
225 unsafe { SourceIter::as_inner(&mut self.iter) }
229 // SAFETY: GenericShunt::next calls `I::try_for_each`, which has to advance `iter`
230 // in order to return `Some(_)`. Since `iter` has type `I: InPlaceIterable` it's
231 // guaranteed that at least one item will be moved out from the underlying source.
232 #[unstable(issue = "none", feature = "inplace_iteration")]
233 unsafe impl<I, T, R> InPlaceIterable for GenericShunt<'_, I, R> where
234 I: Iterator<Item: Try<Output = T, Residual = R>> + InPlaceIterable