Skip to main content

core/iter/adapters/
chain.rs

1use crate::iter::{FusedIterator, TrustedLen};
2use crate::num::NonZero;
3use crate::ops::Try;
4
5/// An iterator that links two iterators together, in a chain.
6///
7/// This `struct` is created by [`chain`] or [`Iterator::chain`]. See their
8/// documentation for more.
9///
10/// # Examples
11///
12/// ```
13/// use std::iter::Chain;
14/// use std::slice::Iter;
15///
16/// let a1 = [1, 2, 3];
17/// let a2 = [4, 5, 6];
18/// let iter: Chain<Iter<'_, _>, Iter<'_, _>> = a1.iter().chain(a2.iter());
19/// ```
20#[derive(Clone, Debug)]
21#[must_use = "iterators are lazy and do nothing unless consumed"]
22#[stable(feature = "rust1", since = "1.0.0")]
23#[ferrocene::prevalidated]
24pub struct Chain<A, B> {
25    // These are "fused" with `Option` so we don't need separate state to track which part is
26    // already exhausted, and we may also get niche layout for `None`. We don't use the real `Fuse`
27    // adapter because its specialization for `FusedIterator` unconditionally descends into the
28    // iterator, and that could be expensive to keep revisiting stuff like nested chains. It also
29    // hurts compiler performance to add more iterator layers to `Chain`.
30    //
31    // Only the "first" iterator is actually set `None` when exhausted, depending on whether you
32    // iterate forward or backward. If you mix directions, then both sides may be `None`.
33    a: Option<A>,
34    b: Option<B>,
35}
36impl<A, B> Chain<A, B> {
37    #[ferrocene::prevalidated]
38    pub(in super::super) const fn new(a: A, b: B) -> Chain<A, B> {
39        Chain { a: Some(a), b: Some(b) }
40    }
41}
42
43/// Converts the arguments to iterators and links them together, in a chain.
44///
45/// See the documentation of [`Iterator::chain`] for more.
46///
47/// # Examples
48///
49/// ```
50/// use std::iter::chain;
51///
52/// let a = [1, 2, 3];
53/// let b = [4, 5, 6];
54///
55/// let mut iter = chain(a, b);
56///
57/// assert_eq!(iter.next(), Some(1));
58/// assert_eq!(iter.next(), Some(2));
59/// assert_eq!(iter.next(), Some(3));
60/// assert_eq!(iter.next(), Some(4));
61/// assert_eq!(iter.next(), Some(5));
62/// assert_eq!(iter.next(), Some(6));
63/// assert_eq!(iter.next(), None);
64/// ```
65#[stable(feature = "iter_chain", since = "1.91.0")]
66pub fn chain<A, B>(a: A, b: B) -> Chain<A::IntoIter, B::IntoIter>
67where
68    A: IntoIterator,
69    B: IntoIterator<Item = A::Item>,
70{
71    Chain::new(a.into_iter(), b.into_iter())
72}
73
74#[stable(feature = "rust1", since = "1.0.0")]
75impl<A, B> Iterator for Chain<A, B>
76where
77    A: Iterator,
78    B: Iterator<Item = A::Item>,
79{
80    type Item = A::Item;
81
82    #[inline]
83    #[ferrocene::prevalidated]
84    fn next(&mut self) -> Option<A::Item> {
85        and_then_or_clear(&mut self.a, Iterator::next).or_else(|| self.b.as_mut()?.next())
86    }
87
88    #[inline]
89    #[rustc_inherit_overflow_checks]
90    #[ferrocene::prevalidated]
91    fn count(self) -> usize {
92        let a_count = match self.a {
93            Some(a) => a.count(),
94            None => 0,
95        };
96        let b_count = match self.b {
97            Some(b) => b.count(),
98            None => 0,
99        };
100        a_count + b_count
101    }
102
103    #[ferrocene::prevalidated]
104    #[inline]
105    fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
106    where
107        Self: Sized,
108        F: FnMut(Acc, Self::Item) -> R,
109        R: Try<Output = Acc>,
110    {
111        if let Some(ref mut a) = self.a {
112            acc = a.try_fold(acc, &mut f)?;
113            self.a = None;
114        }
115        if let Some(ref mut b) = self.b {
116            acc = b.try_fold(acc, f)?;
117            // we don't fuse the second iterator
118        }
119        try { acc }
120    }
121
122    #[ferrocene::prevalidated]
123    #[inline]
124    fn fold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
125    where
126        F: FnMut(Acc, Self::Item) -> Acc,
127    {
128        if let Some(a) = self.a {
129            acc = a.fold(acc, &mut f);
130        }
131        if let Some(b) = self.b {
132            acc = b.fold(acc, f);
133        }
134        acc
135    }
136
137    #[inline]
138    #[ferrocene::prevalidated]
139    fn advance_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
140        if let Some(ref mut a) = self.a {
141            n = match a.advance_by(n) {
142                Ok(()) => return Ok(()),
143                Err(k) => k.get(),
144            };
145            self.a = None;
146        }
147
148        if let Some(ref mut b) = self.b {
149            return b.advance_by(n);
150            // we don't fuse the second iterator
151        }
152
153        NonZero::new(n).map_or(Ok(()), Err)
154    }
155
156    #[inline]
157    #[ferrocene::prevalidated]
158    fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
159        if let Some(ref mut a) = self.a {
160            n = match a.advance_by(n) {
161                Ok(()) => match a.next() {
162                    None => 0,
163                    x => return x,
164                },
165                Err(k) => k.get(),
166            };
167
168            self.a = None;
169        }
170
171        self.b.as_mut()?.nth(n)
172    }
173
174    #[inline]
175    #[ferrocene::prevalidated]
176    fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
177    where
178        P: FnMut(&Self::Item) -> bool,
179    {
180        and_then_or_clear(&mut self.a, |a| a.find(&mut predicate))
181            .or_else(|| self.b.as_mut()?.find(predicate))
182    }
183
184    #[inline]
185    #[ferrocene::prevalidated]
186    fn last(self) -> Option<A::Item> {
187        // Must exhaust a before b.
188        let a_last = self.a.and_then(Iterator::last);
189        let b_last = self.b.and_then(Iterator::last);
190        b_last.or(a_last)
191    }
192
193    #[inline]
194    #[ferrocene::prevalidated]
195    fn size_hint(&self) -> (usize, Option<usize>) {
196        match self {
197            Chain { a: Some(a), b: Some(b) } => {
198                let (a_lower, a_upper) = a.size_hint();
199                let (b_lower, b_upper) = b.size_hint();
200
201                let lower = a_lower.saturating_add(b_lower);
202
203                let upper = match (a_upper, b_upper) {
204                    (Some(x), Some(y)) => x.checked_add(y),
205                    _ => None,
206                };
207
208                (lower, upper)
209            }
210            Chain { a: Some(a), b: None } => a.size_hint(),
211            Chain { a: None, b: Some(b) } => b.size_hint(),
212            Chain { a: None, b: None } => (0, Some(0)),
213        }
214    }
215}
216
217#[stable(feature = "rust1", since = "1.0.0")]
218impl<A, B> DoubleEndedIterator for Chain<A, B>
219where
220    A: DoubleEndedIterator,
221    B: DoubleEndedIterator<Item = A::Item>,
222{
223    #[inline]
224    fn next_back(&mut self) -> Option<A::Item> {
225        and_then_or_clear(&mut self.b, |b| b.next_back()).or_else(|| self.a.as_mut()?.next_back())
226    }
227
228    #[inline]
229    fn advance_back_by(&mut self, mut n: usize) -> Result<(), NonZero<usize>> {
230        if let Some(ref mut b) = self.b {
231            n = match b.advance_back_by(n) {
232                Ok(()) => return Ok(()),
233                Err(k) => k.get(),
234            };
235            self.b = None;
236        }
237
238        if let Some(ref mut a) = self.a {
239            return a.advance_back_by(n);
240            // we don't fuse the second iterator
241        }
242
243        NonZero::new(n).map_or(Ok(()), Err)
244    }
245
246    #[inline]
247    fn nth_back(&mut self, mut n: usize) -> Option<Self::Item> {
248        if let Some(ref mut b) = self.b {
249            n = match b.advance_back_by(n) {
250                Ok(()) => match b.next_back() {
251                    None => 0,
252                    x => return x,
253                },
254                Err(k) => k.get(),
255            };
256
257            self.b = None;
258        }
259
260        self.a.as_mut()?.nth_back(n)
261    }
262
263    #[inline]
264    fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item>
265    where
266        P: FnMut(&Self::Item) -> bool,
267    {
268        and_then_or_clear(&mut self.b, |b| b.rfind(&mut predicate))
269            .or_else(|| self.a.as_mut()?.rfind(predicate))
270    }
271
272    #[inline]
273    fn try_rfold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
274    where
275        Self: Sized,
276        F: FnMut(Acc, Self::Item) -> R,
277        R: Try<Output = Acc>,
278    {
279        if let Some(ref mut b) = self.b {
280            acc = b.try_rfold(acc, &mut f)?;
281            self.b = None;
282        }
283        if let Some(ref mut a) = self.a {
284            acc = a.try_rfold(acc, f)?;
285            // we don't fuse the second iterator
286        }
287        try { acc }
288    }
289
290    #[inline]
291    fn rfold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
292    where
293        F: FnMut(Acc, Self::Item) -> Acc,
294    {
295        if let Some(b) = self.b {
296            acc = b.rfold(acc, &mut f);
297        }
298        if let Some(a) = self.a {
299            acc = a.rfold(acc, f);
300        }
301        acc
302    }
303}
304
305// Note: *both* must be fused to handle double-ended iterators.
306#[stable(feature = "fused", since = "1.26.0")]
307impl<A, B> FusedIterator for Chain<A, B>
308where
309    A: FusedIterator,
310    B: FusedIterator<Item = A::Item>,
311{
312}
313
314#[unstable(feature = "trusted_len", issue = "37572")]
315unsafe impl<A, B> TrustedLen for Chain<A, B>
316where
317    A: TrustedLen,
318    B: TrustedLen<Item = A::Item>,
319{
320}
321
322#[stable(feature = "default_iters", since = "1.70.0")]
323impl<A: Default, B: Default> Default for Chain<A, B> {
324    /// Creates a `Chain` from the default values for `A` and `B`.
325    ///
326    /// ```
327    /// # use core::iter::Chain;
328    /// # use core::slice;
329    /// # use std::collections::{btree_set, BTreeSet};
330    /// # use std::mem;
331    /// struct Foo<'a>(Chain<slice::Iter<'a, u8>, btree_set::Iter<'a, u8>>);
332    ///
333    /// let set = BTreeSet::<u8>::new();
334    /// let slice: &[u8] = &[];
335    /// let mut foo = Foo(slice.iter().chain(set.iter()));
336    ///
337    /// // take requires `Default`
338    /// let _: Chain<_, _> = mem::take(&mut foo.0);
339    /// ```
340    fn default() -> Self {
341        Chain::new(Default::default(), Default::default())
342    }
343}
344
345#[inline]
346#[ferrocene::prevalidated]
347fn and_then_or_clear<T, U>(opt: &mut Option<T>, f: impl FnOnce(&mut T) -> Option<U>) -> Option<U> {
348    let x = f(opt.as_mut()?);
349    if x.is_none() {
350        *opt = None;
351    }
352    x
353}