1
#[cfg(not(feature = "ferrocene_certified"))]
2
use super::TrustedLen;
3

            
4
/// Conversion from an [`Iterator`].
5
///
6
/// By implementing `FromIterator` for a type, you define how it will be
7
/// created from an iterator. This is common for types which describe a
8
/// collection of some kind.
9
///
10
/// If you want to create a collection from the contents of an iterator, the
11
/// [`Iterator::collect()`] method is preferred. However, when you need to
12
/// specify the container type, [`FromIterator::from_iter()`] can be more
13
/// readable than using a turbofish (e.g. `::<Vec<_>>()`). See the
14
/// [`Iterator::collect()`] documentation for more examples of its use.
15
///
16
/// See also: [`IntoIterator`].
17
///
18
/// # Examples
19
///
20
/// Basic usage:
21
///
22
/// ```
23
/// let five_fives = std::iter::repeat(5).take(5);
24
///
25
/// let v = Vec::from_iter(five_fives);
26
///
27
/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
28
/// ```
29
///
30
/// Using [`Iterator::collect()`] to implicitly use `FromIterator`:
31
///
32
/// ```
33
/// let five_fives = std::iter::repeat(5).take(5);
34
///
35
/// let v: Vec<i32> = five_fives.collect();
36
///
37
/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
38
/// ```
39
///
40
/// Using [`FromIterator::from_iter()`] as a more readable alternative to
41
/// [`Iterator::collect()`]:
42
///
43
/// ```
44
/// use std::collections::VecDeque;
45
/// let first = (0..10).collect::<VecDeque<i32>>();
46
/// let second = VecDeque::from_iter(0..10);
47
///
48
/// assert_eq!(first, second);
49
/// ```
50
///
51
/// Implementing `FromIterator` for your type:
52
///
53
/// ```
54
/// // A sample collection, that's just a wrapper over Vec<T>
55
/// #[derive(Debug)]
56
/// struct MyCollection(Vec<i32>);
57
///
58
/// // Let's give it some methods so we can create one and add things
59
/// // to it.
60
/// impl MyCollection {
61
///     fn new() -> MyCollection {
62
///         MyCollection(Vec::new())
63
///     }
64
///
65
///     fn add(&mut self, elem: i32) {
66
///         self.0.push(elem);
67
///     }
68
/// }
69
///
70
/// // and we'll implement FromIterator
71
/// impl FromIterator<i32> for MyCollection {
72
///     fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
73
///         let mut c = MyCollection::new();
74
///
75
///         for i in iter {
76
///             c.add(i);
77
///         }
78
///
79
///         c
80
///     }
81
/// }
82
///
83
/// // Now we can make a new iterator...
84
/// let iter = (0..5).into_iter();
85
///
86
/// // ... and make a MyCollection out of it
87
/// let c = MyCollection::from_iter(iter);
88
///
89
/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
90
///
91
/// // collect works too!
92
///
93
/// let iter = (0..5).into_iter();
94
/// let c: MyCollection = iter.collect();
95
///
96
/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
97
/// ```
98
#[stable(feature = "rust1", since = "1.0.0")]
99
#[rustc_on_unimplemented(
100
    on(
101
        Self = "&[{A}]",
102
        message = "a slice of type `{Self}` cannot be built since we need to store the elements somewhere",
103
        label = "try explicitly collecting into a `Vec<{A}>`",
104
    ),
105
    on(
106
        all(A = "{integer}", any(Self = "&[{integral}]",)),
107
        message = "a slice of type `{Self}` cannot be built since we need to store the elements somewhere",
108
        label = "try explicitly collecting into a `Vec<{A}>`",
109
    ),
110
    on(
111
        Self = "[{A}]",
112
        message = "a slice of type `{Self}` cannot be built since `{Self}` has no definite size",
113
        label = "try explicitly collecting into a `Vec<{A}>`",
114
    ),
115
    on(
116
        all(A = "{integer}", any(Self = "[{integral}]",)),
117
        message = "a slice of type `{Self}` cannot be built since `{Self}` has no definite size",
118
        label = "try explicitly collecting into a `Vec<{A}>`",
119
    ),
120
    on(
121
        Self = "[{A}; _]",
122
        message = "an array of type `{Self}` cannot be built directly from an iterator",
123
        label = "try collecting into a `Vec<{A}>`, then using `.try_into()`",
124
    ),
125
    on(
126
        all(A = "{integer}", any(Self = "[{integral}; _]",)),
127
        message = "an array of type `{Self}` cannot be built directly from an iterator",
128
        label = "try collecting into a `Vec<{A}>`, then using `.try_into()`",
129
    ),
130
    message = "a value of type `{Self}` cannot be built from an iterator \
131
               over elements of type `{A}`",
132
    label = "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
133
)]
134
#[rustc_diagnostic_item = "FromIterator"]
135
#[cfg(not(feature = "ferrocene_certified"))]
136
pub trait FromIterator<A>: Sized {
137
    /// Creates a value from an iterator.
138
    ///
139
    /// See the [module-level documentation] for more.
140
    ///
141
    /// [module-level documentation]: crate::iter
142
    ///
143
    /// # Examples
144
    ///
145
    /// ```
146
    /// let five_fives = std::iter::repeat(5).take(5);
147
    ///
148
    /// let v = Vec::from_iter(five_fives);
149
    ///
150
    /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
151
    /// ```
152
    #[stable(feature = "rust1", since = "1.0.0")]
153
    #[rustc_diagnostic_item = "from_iter_fn"]
154
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
155
}
156

            
157
/// Conversion into an [`Iterator`].
158
///
159
/// By implementing `IntoIterator` for a type, you define how it will be
160
/// converted to an iterator. This is common for types which describe a
161
/// collection of some kind.
162
///
163
/// One benefit of implementing `IntoIterator` is that your type will [work
164
/// with Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).
165
///
166
/// See also: [`FromIterator`].
167
///
168
/// # Examples
169
///
170
/// Basic usage:
171
///
172
/// ```
173
/// let v = [1, 2, 3];
174
/// let mut iter = v.into_iter();
175
///
176
/// assert_eq!(Some(1), iter.next());
177
/// assert_eq!(Some(2), iter.next());
178
/// assert_eq!(Some(3), iter.next());
179
/// assert_eq!(None, iter.next());
180
/// ```
181
/// Implementing `IntoIterator` for your type:
182
///
183
/// ```
184
/// // A sample collection, that's just a wrapper over Vec<T>
185
/// #[derive(Debug)]
186
/// struct MyCollection(Vec<i32>);
187
///
188
/// // Let's give it some methods so we can create one and add things
189
/// // to it.
190
/// impl MyCollection {
191
///     fn new() -> MyCollection {
192
///         MyCollection(Vec::new())
193
///     }
194
///
195
///     fn add(&mut self, elem: i32) {
196
///         self.0.push(elem);
197
///     }
198
/// }
199
///
200
/// // and we'll implement IntoIterator
201
/// impl IntoIterator for MyCollection {
202
///     type Item = i32;
203
///     type IntoIter = std::vec::IntoIter<Self::Item>;
204
///
205
///     fn into_iter(self) -> Self::IntoIter {
206
///         self.0.into_iter()
207
///     }
208
/// }
209
///
210
/// // Now we can make a new collection...
211
/// let mut c = MyCollection::new();
212
///
213
/// // ... add some stuff to it ...
214
/// c.add(0);
215
/// c.add(1);
216
/// c.add(2);
217
///
218
/// // ... and then turn it into an Iterator:
219
/// for (i, n) in c.into_iter().enumerate() {
220
///     assert_eq!(i as i32, n);
221
/// }
222
/// ```
223
///
224
/// It is common to use `IntoIterator` as a trait bound. This allows
225
/// the input collection type to change, so long as it is still an
226
/// iterator. Additional bounds can be specified by restricting on
227
/// `Item`:
228
///
229
/// ```rust
230
/// fn collect_as_strings<T>(collection: T) -> Vec<String>
231
/// where
232
///     T: IntoIterator,
233
///     T::Item: std::fmt::Debug,
234
/// {
235
///     collection
236
///         .into_iter()
237
///         .map(|item| format!("{item:?}"))
238
///         .collect()
239
/// }
240
/// ```
241
#[rustc_diagnostic_item = "IntoIterator"]
242
#[rustc_on_unimplemented(
243
    on(
244
        Self = "core::ops::range::RangeTo<Idx>",
245
        label = "if you meant to iterate until a value, add a starting value",
246
        note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
247
              bounded `Range`: `0..end`"
248
    ),
249
    on(
250
        Self = "core::ops::range::RangeToInclusive<Idx>",
251
        label = "if you meant to iterate until a value (including it), add a starting value",
252
        note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
253
              to have a bounded `RangeInclusive`: `0..=end`"
254
    ),
255
    on(
256
        Self = "[]",
257
        label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
258
    ),
259
    on(Self = "&[]", label = "`{Self}` is not an iterator; try calling `.iter()`"),
260
    on(
261
        Self = "alloc::vec::Vec<T, A>",
262
        label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
263
    ),
264
    on(Self = "&str", label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"),
265
    on(
266
        Self = "alloc::string::String",
267
        label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
268
    ),
269
    on(
270
        Self = "{integral}",
271
        note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
272
              syntax `start..end` or the inclusive range syntax `start..=end`"
273
    ),
274
    on(
275
        Self = "{float}",
276
        note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
277
              syntax `start..end` or the inclusive range syntax `start..=end`"
278
    ),
279
    label = "`{Self}` is not an iterator",
280
    message = "`{Self}` is not an iterator"
281
)]
282
#[rustc_skip_during_method_dispatch(array, boxed_slice)]
283
#[stable(feature = "rust1", since = "1.0.0")]
284
pub trait IntoIterator {
285
    /// The type of the elements being iterated over.
286
    #[stable(feature = "rust1", since = "1.0.0")]
287
    type Item;
288

            
289
    /// Which kind of iterator are we turning this into?
290
    #[stable(feature = "rust1", since = "1.0.0")]
291
    type IntoIter: Iterator<Item = Self::Item>;
292

            
293
    /// Creates an iterator from a value.
294
    ///
295
    /// See the [module-level documentation] for more.
296
    ///
297
    /// [module-level documentation]: crate::iter
298
    ///
299
    /// # Examples
300
    ///
301
    /// ```
302
    /// let v = [1, 2, 3];
303
    /// let mut iter = v.into_iter();
304
    ///
305
    /// assert_eq!(Some(1), iter.next());
306
    /// assert_eq!(Some(2), iter.next());
307
    /// assert_eq!(Some(3), iter.next());
308
    /// assert_eq!(None, iter.next());
309
    /// ```
310
    #[lang = "into_iter"]
311
    #[stable(feature = "rust1", since = "1.0.0")]
312
    fn into_iter(self) -> Self::IntoIter;
313
}
314

            
315
#[stable(feature = "rust1", since = "1.0.0")]
316
#[cfg(not(feature = "ferrocene_certified"))]
317
impl<I: Iterator> IntoIterator for I {
318
    type Item = I::Item;
319
    type IntoIter = I;
320

            
321
    #[inline]
322
4011187
    fn into_iter(self) -> I {
323
4011187
        self
324
4011187
    }
325
}
326

            
327
/// Extend a collection with the contents of an iterator.
328
///
329
/// Iterators produce a series of values, and collections can also be thought
330
/// of as a series of values. The `Extend` trait bridges this gap, allowing you
331
/// to extend a collection by including the contents of that iterator. When
332
/// extending a collection with an already existing key, that entry is updated
333
/// or, in the case of collections that permit multiple entries with equal
334
/// keys, that entry is inserted.
335
///
336
/// # Examples
337
///
338
/// Basic usage:
339
///
340
/// ```
341
/// // You can extend a String with some chars:
342
/// let mut message = String::from("The first three letters are: ");
343
///
344
/// message.extend(&['a', 'b', 'c']);
345
///
346
/// assert_eq!("abc", &message[29..32]);
347
/// ```
348
///
349
/// Implementing `Extend`:
350
///
351
/// ```
352
/// // A sample collection, that's just a wrapper over Vec<T>
353
/// #[derive(Debug)]
354
/// struct MyCollection(Vec<i32>);
355
///
356
/// // Let's give it some methods so we can create one and add things
357
/// // to it.
358
/// impl MyCollection {
359
///     fn new() -> MyCollection {
360
///         MyCollection(Vec::new())
361
///     }
362
///
363
///     fn add(&mut self, elem: i32) {
364
///         self.0.push(elem);
365
///     }
366
/// }
367
///
368
/// // since MyCollection has a list of i32s, we implement Extend for i32
369
/// impl Extend<i32> for MyCollection {
370
///
371
///     // This is a bit simpler with the concrete type signature: we can call
372
///     // extend on anything which can be turned into an Iterator which gives
373
///     // us i32s. Because we need i32s to put into MyCollection.
374
///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
375
///
376
///         // The implementation is very straightforward: loop through the
377
///         // iterator, and add() each element to ourselves.
378
///         for elem in iter {
379
///             self.add(elem);
380
///         }
381
///     }
382
/// }
383
///
384
/// let mut c = MyCollection::new();
385
///
386
/// c.add(5);
387
/// c.add(6);
388
/// c.add(7);
389
///
390
/// // let's extend our collection with three more numbers
391
/// c.extend(vec![1, 2, 3]);
392
///
393
/// // we've added these elements onto the end
394
/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
395
/// ```
396
#[stable(feature = "rust1", since = "1.0.0")]
397
#[cfg(not(feature = "ferrocene_certified"))]
398
pub trait Extend<A> {
399
    /// Extends a collection with the contents of an iterator.
400
    ///
401
    /// As this is the only required method for this trait, the [trait-level] docs
402
    /// contain more details.
403
    ///
404
    /// [trait-level]: Extend
405
    ///
406
    /// # Examples
407
    ///
408
    /// ```
409
    /// // You can extend a String with some chars:
410
    /// let mut message = String::from("abc");
411
    ///
412
    /// message.extend(['d', 'e', 'f'].iter());
413
    ///
414
    /// assert_eq!("abcdef", &message);
415
    /// ```
416
    #[stable(feature = "rust1", since = "1.0.0")]
417
    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
418

            
419
    /// Extends a collection with exactly one element.
420
    #[unstable(feature = "extend_one", issue = "72631")]
421
    fn extend_one(&mut self, item: A) {
422
        self.extend(Some(item));
423
    }
424

            
425
    /// Reserves capacity in a collection for the given number of additional elements.
426
    ///
427
    /// The default implementation does nothing.
428
    #[unstable(feature = "extend_one", issue = "72631")]
429
    fn extend_reserve(&mut self, additional: usize) {
430
        let _ = additional;
431
    }
432

            
433
    /// Extends a collection with one element, without checking there is enough capacity for it.
434
    ///
435
    /// # Safety
436
    ///
437
    /// **For callers:** This must only be called when we know the collection has enough capacity
438
    /// to contain the new item, for example because we previously called `extend_reserve`.
439
    ///
440
    /// **For implementors:** For a collection to unsafely rely on this method's safety precondition (that is,
441
    /// invoke UB if they are violated), it must implement `extend_reserve` correctly. In other words,
442
    /// callers may assume that if they `extend_reserve`ed enough space they can call this method.
443
    // This method is for internal usage only. It is only on the trait because of specialization's limitations.
444
    #[unstable(feature = "extend_one_unchecked", issue = "none")]
445
    #[doc(hidden)]
446
    unsafe fn extend_one_unchecked(&mut self, item: A)
447
    where
448
        Self: Sized,
449
    {
450
        self.extend_one(item);
451
    }
452
}
453

            
454
#[stable(feature = "extend_for_unit", since = "1.28.0")]
455
#[cfg(not(feature = "ferrocene_certified"))]
456
impl Extend<()> for () {
457
    fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
458
        iter.into_iter().for_each(drop)
459
    }
460
    fn extend_one(&mut self, _item: ()) {}
461
}
462

            
463
macro_rules! spec_tuple_impl {
464
    (
465
        (
466
            $ty_name:ident, $var_name:ident, $extend_ty_name: ident,
467
            $trait_name:ident, $default_fn_name:ident, $cnt:tt
468
        ),
469
    ) => {
470
        spec_tuple_impl!(
471
            $trait_name,
472
            $default_fn_name,
473
            #[doc(fake_variadic)]
474
            #[doc = "This trait is implemented for tuples up to twelve items long. The `impl`s for \
475
                     1- and 3- through 12-ary tuples were stabilized after 2-tuples, in \
476
                     1.85.0."]
477
            => ($ty_name, $var_name, $extend_ty_name, $cnt),
478
        );
479
    };
480
    (
481
        (
482
            $ty_name:ident, $var_name:ident, $extend_ty_name: ident,
483
            $trait_name:ident, $default_fn_name:ident, $cnt:tt
484
        ),
485
        $(
486
            (
487
                $ty_names:ident, $var_names:ident,  $extend_ty_names:ident,
488
                $trait_names:ident, $default_fn_names:ident, $cnts:tt
489
            ),
490
        )*
491
    ) => {
492
        spec_tuple_impl!(
493
            $(
494
                (
495
                    $ty_names, $var_names, $extend_ty_names,
496
                    $trait_names, $default_fn_names, $cnts
497
                ),
498
            )*
499
        );
500
        spec_tuple_impl!(
501
            $trait_name,
502
            $default_fn_name,
503
            #[doc(hidden)]
504
            => (
505
                $ty_name, $var_name, $extend_ty_name, $cnt
506
            ),
507
            $(
508
                (
509
                    $ty_names, $var_names, $extend_ty_names, $cnts
510
                ),
511
            )*
512
        );
513
    };
514
    (
515
        $trait_name:ident, $default_fn_name:ident, #[$meta:meta]
516
        $(#[$doctext:meta])? => $(
517
            (
518
                $ty_names:ident, $var_names:ident, $extend_ty_names:ident, $cnts:tt
519
            ),
520
        )*
521
    ) => {
522
        #[$meta]
523
        $(#[$doctext])?
524
        #[stable(feature = "extend_for_tuple", since = "1.56.0")]
525
        #[cfg(not(feature = "ferrocene_certified"))]
526
        impl<$($ty_names,)* $($extend_ty_names,)*> Extend<($($ty_names,)*)> for ($($extend_ty_names,)*)
527
        where
528
            $($extend_ty_names: Extend<$ty_names>,)*
529
        {
530
            /// Allows to `extend` a tuple of collections that also implement `Extend`.
531
            ///
532
            /// See also: [`Iterator::unzip`]
533
            ///
534
            /// # Examples
535
            /// ```
536
            /// // Example given for a 2-tuple, but 1- through 12-tuples are supported
537
            /// let mut tuple = (vec![0], vec![1]);
538
            /// tuple.extend([(2, 3), (4, 5), (6, 7)]);
539
            /// assert_eq!(tuple.0, [0, 2, 4, 6]);
540
            /// assert_eq!(tuple.1, [1, 3, 5, 7]);
541
            ///
542
            /// // also allows for arbitrarily nested tuples as elements
543
            /// let mut nested_tuple = (vec![1], (vec![2], vec![3]));
544
            /// nested_tuple.extend([(4, (5, 6)), (7, (8, 9))]);
545
            ///
546
            /// let (a, (b, c)) = nested_tuple;
547
            /// assert_eq!(a, [1, 4, 7]);
548
            /// assert_eq!(b, [2, 5, 8]);
549
            /// assert_eq!(c, [3, 6, 9]);
550
            /// ```
551
            fn extend<T: IntoIterator<Item = ($($ty_names,)*)>>(&mut self, into_iter: T) {
552
                let ($($var_names,)*) = self;
553
                let iter = into_iter.into_iter();
554
                $trait_name::extend(iter, $($var_names,)*);
555
            }
556

            
557
            fn extend_one(&mut self, item: ($($ty_names,)*)) {
558
                $(self.$cnts.extend_one(item.$cnts);)*
559
            }
560

            
561
            fn extend_reserve(&mut self, additional: usize) {
562
                $(self.$cnts.extend_reserve(additional);)*
563
            }
564

            
565
            unsafe fn extend_one_unchecked(&mut self, item: ($($ty_names,)*)) {
566
                // SAFETY: Those are our safety preconditions, and we correctly forward `extend_reserve`.
567
                unsafe {
568
                     $(self.$cnts.extend_one_unchecked(item.$cnts);)*
569
                }
570
            }
571
        }
572

            
573
        #[cfg(not(feature = "ferrocene_certified"))]
574
        trait $trait_name<$($ty_names),*> {
575
            fn extend(self, $($var_names: &mut $ty_names,)*);
576
        }
577

            
578
        #[cfg(not(feature = "ferrocene_certified"))]
579
        fn $default_fn_name<$($ty_names,)* $($extend_ty_names,)*>(
580
            iter: impl Iterator<Item = ($($ty_names,)*)>,
581
            $($var_names: &mut $extend_ty_names,)*
582
        ) where
583
            $($extend_ty_names: Extend<$ty_names>,)*
584
        {
585
            fn extend<'a, $($ty_names,)*>(
586
                $($var_names: &'a mut impl Extend<$ty_names>,)*
587
            ) -> impl FnMut((), ($($ty_names,)*)) + 'a {
588
                #[allow(non_snake_case)]
589
                move |(), ($($extend_ty_names,)*)| {
590
                    $($var_names.extend_one($extend_ty_names);)*
591
                }
592
            }
593

            
594
            let (lower_bound, _) = iter.size_hint();
595
            if lower_bound > 0 {
596
                $($var_names.extend_reserve(lower_bound);)*
597
            }
598

            
599
            iter.fold((), extend($($var_names,)*));
600
        }
601

            
602
        #[cfg(not(feature = "ferrocene_certified"))]
603
        impl<$($ty_names,)* $($extend_ty_names,)* Iter> $trait_name<$($extend_ty_names),*> for Iter
604
        where
605
            $($extend_ty_names: Extend<$ty_names>,)*
606
            Iter: Iterator<Item = ($($ty_names,)*)>,
607
        {
608
            default fn extend(self, $($var_names: &mut $extend_ty_names),*) {
609
                $default_fn_name(self, $($var_names),*);
610
            }
611
        }
612

            
613
        #[cfg(not(feature = "ferrocene_certified"))]
614
        impl<$($ty_names,)* $($extend_ty_names,)* Iter> $trait_name<$($extend_ty_names),*> for Iter
615
        where
616
            $($extend_ty_names: Extend<$ty_names>,)*
617
            Iter: TrustedLen<Item = ($($ty_names,)*)>,
618
        {
619
            fn extend(self, $($var_names: &mut $extend_ty_names,)*) {
620
                fn extend<'a, $($ty_names,)*>(
621
                    $($var_names: &'a mut impl Extend<$ty_names>,)*
622
                ) -> impl FnMut((), ($($ty_names,)*)) + 'a {
623
                    #[allow(non_snake_case)]
624
                    // SAFETY: We reserve enough space for the `size_hint`, and the iterator is
625
                    // `TrustedLen` so its `size_hint` is exact.
626
                    move |(), ($($extend_ty_names,)*)| unsafe {
627
                        $($var_names.extend_one_unchecked($extend_ty_names);)*
628
                    }
629
                }
630

            
631
                let (lower_bound, upper_bound) = self.size_hint();
632

            
633
                if upper_bound.is_none() {
634
                    // We cannot reserve more than `usize::MAX` items, and this is likely to go out of memory anyway.
635
                    $default_fn_name(self, $($var_names,)*);
636
                    return;
637
                }
638

            
639
                if lower_bound > 0 {
640
                    $($var_names.extend_reserve(lower_bound);)*
641
                }
642

            
643
                self.fold((), extend($($var_names,)*));
644
            }
645
        }
646

            
647
        /// This implementation turns an iterator of tuples into a tuple of types which implement
648
        /// [`Default`] and [`Extend`].
649
        ///
650
        /// This is similar to [`Iterator::unzip`], but is also composable with other [`FromIterator`]
651
        /// implementations:
652
        ///
653
        /// ```rust
654
        /// # fn main() -> Result<(), core::num::ParseIntError> {
655
        /// let string = "1,2,123,4";
656
        ///
657
        /// // Example given for a 2-tuple, but 1- through 12-tuples are supported
658
        /// let (numbers, lengths): (Vec<_>, Vec<_>) = string
659
        ///     .split(',')
660
        ///     .map(|s| s.parse().map(|n: u32| (n, s.len())))
661
        ///     .collect::<Result<_, _>>()?;
662
        ///
663
        /// assert_eq!(numbers, [1, 2, 123, 4]);
664
        /// assert_eq!(lengths, [1, 1, 3, 1]);
665
        /// # Ok(()) }
666
        /// ```
667
        #[$meta]
668
        $(#[$doctext])?
669
        #[stable(feature = "from_iterator_for_tuple", since = "1.79.0")]
670
        #[cfg(not(feature = "ferrocene_certified"))]
671
        impl<$($ty_names,)* $($extend_ty_names,)*> FromIterator<($($extend_ty_names,)*)> for ($($ty_names,)*)
672
        where
673
            $($ty_names: Default + Extend<$extend_ty_names>,)*
674
        {
675
            fn from_iter<Iter: IntoIterator<Item = ($($extend_ty_names,)*)>>(iter: Iter) -> Self {
676
                let mut res = <($($ty_names,)*)>::default();
677
                res.extend(iter);
678

            
679
                res
680
            }
681
        }
682

            
683
    };
684
}
685

            
686
spec_tuple_impl!(
687
    (L, l, EL, TraitL, default_extend_tuple_l, 11),
688
    (K, k, EK, TraitK, default_extend_tuple_k, 10),
689
    (J, j, EJ, TraitJ, default_extend_tuple_j, 9),
690
    (I, i, EI, TraitI, default_extend_tuple_i, 8),
691
    (H, h, EH, TraitH, default_extend_tuple_h, 7),
692
    (G, g, EG, TraitG, default_extend_tuple_g, 6),
693
    (F, f, EF, TraitF, default_extend_tuple_f, 5),
694
    (E, e, EE, TraitE, default_extend_tuple_e, 4),
695
    (D, d, ED, TraitD, default_extend_tuple_d, 3),
696
    (C, c, EC, TraitC, default_extend_tuple_c, 2),
697
    (B, b, EB, TraitB, default_extend_tuple_b, 1),
698
    (A, a, EA, TraitA, default_extend_tuple_a, 0),
699
);