1 use crate::iter::{DoubleEndedIterator, FusedIterator, Iterator, TrustedLen};
5 /// An iterator that links two iterators together, in a chain.
7 /// This `struct` is created by [`Iterator::chain`]. See its documentation
13 /// use std::iter::Chain;
14 /// use std::slice::Iter;
16 /// let a1 = [1, 2, 3];
17 /// let a2 = [4, 5, 6];
18 /// let iter: Chain<Iter<_>, Iter<_>> = a1.iter().chain(a2.iter());
20 #[derive(Clone, Debug)]
21 #[must_use = "iterators are lazy and do nothing unless consumed"]
22 #[stable(feature = "rust1", since = "1.0.0")]
23 pub struct Chain<A, B> {
24 // These are "fused" with `Option` so we don't need separate state to track which part is
25 // already exhausted, and we may also get niche layout for `None`. We don't use the real `Fuse`
26 // adapter because its specialization for `FusedIterator` unconditionally descends into the
27 // iterator, and that could be expensive to keep revisiting stuff like nested chains. It also
28 // hurts compiler performance to add more iterator layers to `Chain`.
30 // Only the "first" iterator is actually set `None` when exhausted, depending on whether you
31 // iterate forward or backward. If you mix directions, then both sides may be `None`.
35 impl<A, B> Chain<A, B> {
36 pub(in super::super) fn new(a: A, b: B) -> Chain<A, B> {
37 Chain { a: Some(a), b: Some(b) }
41 /// Fuse the iterator if the expression is `None`.
43 ($self:ident . $iter:ident . $($call:tt)+) => {
45 Some(ref mut iter) => match iter.$($call)+ {
57 /// Try an iterator method without fusing,
58 /// like an inline `.as_mut().and_then(...)`
60 ($self:ident . $iter:ident . $($call:tt)+) => {
62 Some(ref mut iter) => iter.$($call)+,
68 #[stable(feature = "rust1", since = "1.0.0")]
69 impl<A, B> Iterator for Chain<A, B>
72 B: Iterator<Item = A::Item>,
77 fn next(&mut self) -> Option<A::Item> {
78 match fuse!(self.a.next()) {
79 None => maybe!(self.b.next()),
85 #[rustc_inherit_overflow_checks]
86 fn count(self) -> usize {
87 let a_count = match self.a {
91 let b_count = match self.b {
98 fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
101 F: FnMut(Acc, Self::Item) -> R,
104 if let Some(ref mut a) = self.a {
105 acc = a.try_fold(acc, &mut f)?;
108 if let Some(ref mut b) = self.b {
109 acc = b.try_fold(acc, f)?;
110 // we don't fuse the second iterator
115 fn fold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
117 F: FnMut(Acc, Self::Item) -> Acc,
119 if let Some(a) = self.a {
120 acc = a.fold(acc, &mut f);
122 if let Some(b) = self.b {
123 acc = b.fold(acc, f);
129 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
130 if let Some(ref mut a) = self.a {
131 while let Some(x) = a.next() {
139 maybe!(self.b.nth(n))
143 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
145 P: FnMut(&Self::Item) -> bool,
147 match fuse!(self.a.find(&mut predicate)) {
148 None => maybe!(self.b.find(predicate)),
154 fn last(self) -> Option<A::Item> {
155 // Must exhaust a before b.
156 let a_last = match self.a {
160 let b_last = match self.b {
168 fn size_hint(&self) -> (usize, Option<usize>) {
170 Chain { a: Some(a), b: Some(b) } => {
171 let (a_lower, a_upper) = a.size_hint();
172 let (b_lower, b_upper) = b.size_hint();
174 let lower = a_lower.saturating_add(b_lower);
176 let upper = match (a_upper, b_upper) {
177 (Some(x), Some(y)) => x.checked_add(y),
183 Chain { a: Some(a), b: None } => a.size_hint(),
184 Chain { a: None, b: Some(b) } => b.size_hint(),
185 Chain { a: None, b: None } => (0, Some(0)),
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<A, B> DoubleEndedIterator for Chain<A, B>
193 A: DoubleEndedIterator,
194 B: DoubleEndedIterator<Item = A::Item>,
197 fn next_back(&mut self) -> Option<A::Item> {
198 match fuse!(self.b.next_back()) {
199 None => maybe!(self.a.next_back()),
205 fn nth_back(&mut self, mut n: usize) -> Option<A::Item> {
206 if let Some(ref mut b) = self.b {
207 while let Some(x) = b.next_back() {
215 maybe!(self.a.nth_back(n))
219 fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item>
221 P: FnMut(&Self::Item) -> bool,
223 match fuse!(self.b.rfind(&mut predicate)) {
224 None => maybe!(self.a.rfind(predicate)),
229 fn try_rfold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
232 F: FnMut(Acc, Self::Item) -> R,
235 if let Some(ref mut b) = self.b {
236 acc = b.try_rfold(acc, &mut f)?;
239 if let Some(ref mut a) = self.a {
240 acc = a.try_rfold(acc, f)?;
241 // we don't fuse the second iterator
246 fn rfold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
248 F: FnMut(Acc, Self::Item) -> Acc,
250 if let Some(b) = self.b {
251 acc = b.rfold(acc, &mut f);
253 if let Some(a) = self.a {
254 acc = a.rfold(acc, f);
260 // Note: *both* must be fused to handle double-ended iterators.
261 #[stable(feature = "fused", since = "1.26.0")]
262 impl<A, B> FusedIterator for Chain<A, B>
265 B: FusedIterator<Item = A::Item>,
269 #[unstable(feature = "trusted_len", issue = "37572")]
270 unsafe impl<A, B> TrustedLen for Chain<A, B>
273 B: TrustedLen<Item = A::Item>,