]> git.lizzy.rs Git - rust.git/blob - library/core/src/iter/adapters/zip.rs
Rollup merge of #75837 - GuillaumeGomez:fix-font-color-help-button, r=Cldfire
[rust.git] / library / core / src / iter / adapters / zip.rs
1 use crate::cmp;
2 use crate::fmt::{self, Debug};
3
4 use super::super::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, TrustedLen};
5
6 /// An iterator that iterates two other iterators simultaneously.
7 ///
8 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
9 /// documentation for more.
10 ///
11 /// [`zip`]: trait.Iterator.html#method.zip
12 /// [`Iterator`]: trait.Iterator.html
13 #[derive(Clone)]
14 #[must_use = "iterators are lazy and do nothing unless consumed"]
15 #[stable(feature = "rust1", since = "1.0.0")]
16 pub struct Zip<A, B> {
17     a: A,
18     b: B,
19     // index and len are only used by the specialized version of zip
20     index: usize,
21     len: usize,
22 }
23 impl<A: Iterator, B: Iterator> Zip<A, B> {
24     pub(in super::super) fn new(a: A, b: B) -> Zip<A, B> {
25         ZipImpl::new(a, b)
26     }
27     fn super_nth(&mut self, mut n: usize) -> Option<(A::Item, B::Item)> {
28         while let Some(x) = Iterator::next(self) {
29             if n == 0 {
30                 return Some(x);
31             }
32             n -= 1;
33         }
34         None
35     }
36 }
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 impl<A, B> Iterator for Zip<A, B>
40 where
41     A: Iterator,
42     B: Iterator,
43 {
44     type Item = (A::Item, B::Item);
45
46     #[inline]
47     fn next(&mut self) -> Option<Self::Item> {
48         ZipImpl::next(self)
49     }
50
51     #[inline]
52     fn size_hint(&self) -> (usize, Option<usize>) {
53         ZipImpl::size_hint(self)
54     }
55
56     #[inline]
57     fn nth(&mut self, n: usize) -> Option<Self::Item> {
58         ZipImpl::nth(self, n)
59     }
60
61     #[inline]
62     unsafe fn get_unchecked(&mut self, idx: usize) -> Self::Item
63     where
64         Self: TrustedRandomAccess,
65     {
66         // SAFETY: `ZipImpl::get_unchecked` has same safety requirements as
67         // `Iterator::get_unchecked`.
68         unsafe { ZipImpl::get_unchecked(self, idx) }
69     }
70 }
71
72 #[stable(feature = "rust1", since = "1.0.0")]
73 impl<A, B> DoubleEndedIterator for Zip<A, B>
74 where
75     A: DoubleEndedIterator + ExactSizeIterator,
76     B: DoubleEndedIterator + ExactSizeIterator,
77 {
78     #[inline]
79     fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
80         ZipImpl::next_back(self)
81     }
82 }
83
84 // Zip specialization trait
85 #[doc(hidden)]
86 trait ZipImpl<A, B> {
87     type Item;
88     fn new(a: A, b: B) -> Self;
89     fn next(&mut self) -> Option<Self::Item>;
90     fn size_hint(&self) -> (usize, Option<usize>);
91     fn nth(&mut self, n: usize) -> Option<Self::Item>;
92     fn next_back(&mut self) -> Option<Self::Item>
93     where
94         A: DoubleEndedIterator + ExactSizeIterator,
95         B: DoubleEndedIterator + ExactSizeIterator;
96     // This has the same safety requirements as `Iterator::get_unchecked`
97     unsafe fn get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item
98     where
99         Self: Iterator + TrustedRandomAccess;
100 }
101
102 // General Zip impl
103 #[doc(hidden)]
104 impl<A, B> ZipImpl<A, B> for Zip<A, B>
105 where
106     A: Iterator,
107     B: Iterator,
108 {
109     type Item = (A::Item, B::Item);
110     default fn new(a: A, b: B) -> Self {
111         Zip {
112             a,
113             b,
114             index: 0, // unused
115             len: 0,   // unused
116         }
117     }
118
119     #[inline]
120     default fn next(&mut self) -> Option<(A::Item, B::Item)> {
121         let x = self.a.next()?;
122         let y = self.b.next()?;
123         Some((x, y))
124     }
125
126     #[inline]
127     default fn nth(&mut self, n: usize) -> Option<Self::Item> {
128         self.super_nth(n)
129     }
130
131     #[inline]
132     default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
133     where
134         A: DoubleEndedIterator + ExactSizeIterator,
135         B: DoubleEndedIterator + ExactSizeIterator,
136     {
137         let a_sz = self.a.len();
138         let b_sz = self.b.len();
139         if a_sz != b_sz {
140             // Adjust a, b to equal length
141             if a_sz > b_sz {
142                 for _ in 0..a_sz - b_sz {
143                     self.a.next_back();
144                 }
145             } else {
146                 for _ in 0..b_sz - a_sz {
147                     self.b.next_back();
148                 }
149             }
150         }
151         match (self.a.next_back(), self.b.next_back()) {
152             (Some(x), Some(y)) => Some((x, y)),
153             (None, None) => None,
154             _ => unreachable!(),
155         }
156     }
157
158     #[inline]
159     default fn size_hint(&self) -> (usize, Option<usize>) {
160         let (a_lower, a_upper) = self.a.size_hint();
161         let (b_lower, b_upper) = self.b.size_hint();
162
163         let lower = cmp::min(a_lower, b_lower);
164
165         let upper = match (a_upper, b_upper) {
166             (Some(x), Some(y)) => Some(cmp::min(x, y)),
167             (Some(x), None) => Some(x),
168             (None, Some(y)) => Some(y),
169             (None, None) => None,
170         };
171
172         (lower, upper)
173     }
174
175     default unsafe fn get_unchecked(&mut self, _idx: usize) -> <Self as Iterator>::Item
176     where
177         Self: TrustedRandomAccess,
178     {
179         unreachable!("Always specialized");
180     }
181 }
182
183 #[doc(hidden)]
184 impl<A, B> ZipImpl<A, B> for Zip<A, B>
185 where
186     A: TrustedRandomAccess + Iterator,
187     B: TrustedRandomAccess + Iterator,
188 {
189     fn new(a: A, b: B) -> Self {
190         let len = cmp::min(a.size(), b.size());
191         Zip { a, b, index: 0, len }
192     }
193
194     #[inline]
195     fn next(&mut self) -> Option<(A::Item, B::Item)> {
196         if self.index < self.len {
197             let i = self.index;
198             self.index += 1;
199             // SAFETY: `i` is smaller than `self.len`, thus smaller than `self.a.len()` and `self.b.len()`
200             unsafe { Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) }
201         } else if A::may_have_side_effect() && self.index < self.a.size() {
202             // match the base implementation's potential side effects
203             // SAFETY: we just checked that `self.index` < `self.a.len()`
204             unsafe {
205                 self.a.get_unchecked(self.index);
206             }
207             self.index += 1;
208             None
209         } else {
210             None
211         }
212     }
213
214     #[inline]
215     fn size_hint(&self) -> (usize, Option<usize>) {
216         let len = self.len - self.index;
217         (len, Some(len))
218     }
219
220     #[inline]
221     fn nth(&mut self, n: usize) -> Option<Self::Item> {
222         let delta = cmp::min(n, self.len - self.index);
223         let end = self.index + delta;
224         while self.index < end {
225             let i = self.index;
226             self.index += 1;
227             if A::may_have_side_effect() {
228                 // SAFETY: the usage of `cmp::min` to calculate `delta`
229                 // ensures that `end` is smaller than or equal to `self.len`,
230                 // so `i` is also smaller than `self.len`.
231                 unsafe {
232                     self.a.get_unchecked(i);
233                 }
234             }
235             if B::may_have_side_effect() {
236                 // SAFETY: same as above.
237                 unsafe {
238                     self.b.get_unchecked(i);
239                 }
240             }
241         }
242
243         self.super_nth(n - delta)
244     }
245
246     #[inline]
247     fn next_back(&mut self) -> Option<(A::Item, B::Item)>
248     where
249         A: DoubleEndedIterator + ExactSizeIterator,
250         B: DoubleEndedIterator + ExactSizeIterator,
251     {
252         let a_side_effect = A::may_have_side_effect();
253         let b_side_effect = B::may_have_side_effect();
254         if a_side_effect || b_side_effect {
255             let sz_a = self.a.size();
256             let sz_b = self.b.size();
257             // Adjust a, b to equal length, make sure that only the first call
258             // of `next_back` does this, otherwise we will break the restriction
259             // on calls to `self.next_back()` after calling `get_unchecked()`.
260             if sz_a != sz_b {
261                 let sz_a = self.a.size();
262                 if a_side_effect && sz_a > self.len {
263                     for _ in 0..sz_a - cmp::max(self.len, self.index) {
264                         self.a.next_back();
265                     }
266                 }
267                 let sz_b = self.b.size();
268                 if b_side_effect && sz_b > self.len {
269                     for _ in 0..sz_b - self.len {
270                         self.b.next_back();
271                     }
272                 }
273             }
274         }
275         if self.index < self.len {
276             self.len -= 1;
277             let i = self.len;
278             // SAFETY: `i` is smaller than the previous value of `self.len`,
279             // which is also smaller than or equal to `self.a.len()` and `self.b.len()`
280             unsafe { Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) }
281         } else {
282             None
283         }
284     }
285
286     #[inline]
287     unsafe fn get_unchecked(&mut self, idx: usize) -> <Self as Iterator>::Item {
288         // SAFETY: the caller must uphold the contract for
289         // `Iterator::get_unchecked`.
290         unsafe { (self.a.get_unchecked(idx), self.b.get_unchecked(idx)) }
291     }
292 }
293
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl<A, B> ExactSizeIterator for Zip<A, B>
296 where
297     A: ExactSizeIterator,
298     B: ExactSizeIterator,
299 {
300 }
301
302 #[doc(hidden)]
303 #[unstable(feature = "trusted_random_access", issue = "none")]
304 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
305 where
306     A: TrustedRandomAccess,
307     B: TrustedRandomAccess,
308 {
309     fn may_have_side_effect() -> bool {
310         A::may_have_side_effect() || B::may_have_side_effect()
311     }
312 }
313
314 #[stable(feature = "fused", since = "1.26.0")]
315 impl<A, B> FusedIterator for Zip<A, B>
316 where
317     A: FusedIterator,
318     B: FusedIterator,
319 {
320 }
321
322 #[unstable(feature = "trusted_len", issue = "37572")]
323 unsafe impl<A, B> TrustedLen for Zip<A, B>
324 where
325     A: TrustedLen,
326     B: TrustedLen,
327 {
328 }
329
330 #[stable(feature = "rust1", since = "1.0.0")]
331 impl<A: Debug, B: Debug> Debug for Zip<A, B> {
332     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333         ZipFmt::fmt(self, f)
334     }
335 }
336
337 trait ZipFmt<A, B> {
338     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
339 }
340
341 impl<A: Debug, B: Debug> ZipFmt<A, B> for Zip<A, B> {
342     default fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343         f.debug_struct("Zip").field("a", &self.a).field("b", &self.b).finish()
344     }
345 }
346
347 impl<A: Debug + TrustedRandomAccess, B: Debug + TrustedRandomAccess> ZipFmt<A, B> for Zip<A, B> {
348     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349         // It's *not safe* to call fmt on the contained iterators, since once
350         // we start iterating they're in strange, potentially unsafe, states.
351         f.debug_struct("Zip").finish()
352     }
353 }
354
355 /// An iterator whose items are random-accessible efficiently
356 ///
357 /// # Safety
358 ///
359 /// The iterator's `size_hint` must be exact and cheap to call.
360 ///
361 /// `size` may not be overridden.
362 ///
363 /// `<Self as Iterator>::get_unchecked` must be safe to call provided the
364 /// following conditions are met.
365 ///
366 /// 1. `0 <= idx` and `idx < self.size()`.
367 /// 2. If `self: !Clone`, then `get_unchecked` is never called with the same
368 ///    index on `self` more than once.
369 /// 3. After `self.get_unchecked(idx)` has been called then `next_back` will
370 ///    only be called at most `self.size() - idx - 1` times.
371 /// 4. After `get_unchecked` is called, then only the following methods will be
372 ///    called on `self`:
373 ///     * `std::clone::Clone::clone`
374 ///     * `std::iter::Iterator::size_hint()`
375 ///     * `std::iter::Iterator::next_back()`
376 ///     * `std::iter::Iterator::get_unchecked()`
377 ///     * `std::iter::TrustedRandomAccess::size()`
378 ///
379 /// Further, given that these conditions are met, it must guarantee that:
380 ///
381 /// * It does not change the value returned from `size_hint`
382 /// * It must be safe to call the methods listed above on `self` after calling
383 ///   `get_unchecked`, assuming that the required traits are implemented.
384 /// * It must also be safe to drop `self` after calling `get_unchecked`.
385 #[doc(hidden)]
386 #[unstable(feature = "trusted_random_access", issue = "none")]
387 #[rustc_specialization_trait]
388 pub unsafe trait TrustedRandomAccess: Sized {
389     // Convenience method.
390     fn size(&self) -> usize
391     where
392         Self: Iterator,
393     {
394         self.size_hint().0
395     }
396     /// Returns `true` if getting an iterator element may have
397     /// side effects. Remember to take inner iterators into account.
398     fn may_have_side_effect() -> bool;
399 }
400
401 /// Like `Iterator::get_unchecked`, but doesn't require the compiler to
402 /// know that `U: TrustedRandomAccess`.
403 ///
404 /// ## Safety
405 ///
406 /// Same requirements calling `get_unchecked` directly.
407 #[doc(hidden)]
408 pub(in crate::iter::adapters) unsafe fn try_get_unchecked<I>(it: &mut I, idx: usize) -> I::Item
409 where
410     I: Iterator,
411 {
412     // SAFETY: the caller must uphold the contract for
413     // `Iterator::get_unchecked`.
414     unsafe { it.try_get_unchecked(idx) }
415 }
416
417 unsafe trait SpecTrustedRandomAccess: Iterator {
418     /// If `Self: TrustedRandomAccess`, it must be safe to call a
419     /// `Iterator::get_unchecked(self, index)`.
420     unsafe fn try_get_unchecked(&mut self, index: usize) -> Self::Item;
421 }
422
423 unsafe impl<I: Iterator> SpecTrustedRandomAccess for I {
424     default unsafe fn try_get_unchecked(&mut self, _: usize) -> Self::Item {
425         panic!("Should only be called on TrustedRandomAccess iterators");
426     }
427 }
428
429 unsafe impl<I: Iterator + TrustedRandomAccess> SpecTrustedRandomAccess for I {
430     unsafe fn try_get_unchecked(&mut self, index: usize) -> Self::Item {
431         // SAFETY: the caller must uphold the contract for
432         // `Iterator::get_unchecked`.
433         unsafe { self.get_unchecked(index) }
434     }
435 }