collect.rs - source
Description: Source of the Rust file `library/core/src/iter/traits/collect.rs`.

#
core/iter/traits/
collect.rs

    1use super::TrustedLen;
    2
    3/// Conversion from an [`Iterator`].
    4///
    5/// By implementing `FromIterator` for a type, you define how it will be
    6/// created from an iterator. This is common for types which describe a
    7/// collection of some kind.
    8///
    9/// If you want to create a collection from the contents of an iterator, the
    10/// [`Iterator::collect()`] method is preferred. However, when you need to
    11/// specify the container type, [`FromIterator::from_iter()`] can be more
    12/// readable than using a turbofish (e.g. `::<Vec<_>>()`). See the
    13/// [`Iterator::collect()`] documentation for more examples of its use.
    14///
    15/// See also: [`IntoIterator`].
    16///
    17/// # Examples
    18///
    19/// Basic usage:
    20///
    21/// ```
    22/// let five_fives = std::iter::repeat(5).take(5);
    23///
    24/// let v = Vec::from_iter(five_fives);
    25///
    26/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
    27/// ```
    28///
    29/// Using [`Iterator::collect()`] to implicitly use `FromIterator`:
    30///
    31/// ```
    32/// let five_fives = std::iter::repeat(5).take(5);
    33///
    34/// let v: Vec<i32> = five_fives.collect();
    35///
    36/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
    37/// ```
    38///
    39/// Using [`FromIterator::from_iter()`] as a more readable alternative to
    40/// [`Iterator::collect()`]:
    41///
    42/// ```
    43/// use std::collections::VecDeque;
    44/// let first = (0..10).collect::<VecDeque<i32>>();
    45/// let second = VecDeque::from_iter(0..10);
    46///
    47/// assert_eq!(first, second);
    48/// ```
    49///
    50/// Implementing `FromIterator` for your type:
    51///
    52/// ```
    53/// // A sample collection, that's just a wrapper over Vec<T>
    54/// #[derive(Debug)]
    55/// struct MyCollection(Vec<i32>);
    56///
    57/// // Let's give it some methods so we can create one and add things
    58/// // to it.
    59/// impl MyCollection {
    60///     fn new() -> MyCollection {
    61///         MyCollection(Vec::new())
    62///     }
    63///
    64///     fn add(&mut self, elem: i32) {
    65///         self.0.push(elem);
    66///     }
    67/// }
    68///
    69/// // and we'll implement FromIterator
    70/// impl FromIterator<i32> for MyCollection {
    71///     fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
    72///         let mut c = MyCollection::new();
    73///
    74///         for i in iter {
    75///             c.add(i);
    76///         }
    77///
    78///         c
    79///     }
    80/// }
    81///
    82/// // Now we can make a new iterator...
    83/// let iter = (0..5).into_iter();
    84///
    85/// // ... and make a MyCollection out of it
    86/// let c = MyCollection::from_iter(iter);
    87///
    88/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
    89///
    90/// // collect works too!
    91///
    92/// let iter = (0..5).into_iter();
    93/// let c: MyCollection = iter.collect();
    94///
    95/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
    96/// ```
    97#[stable(feature = "rust1", since = "1.0.0")]
    98#[rustc_on_unimplemented(
    99    on(
    100        Self = "&[{A}]",
    101        message = "a slice of type `{Self}` cannot be built since we need to store the elements somewhere",
    102        label = "try explicitly collecting into a `Vec<{A}>`",
    103    ),
    104    on(
    105        all(A = "{integer}", any(Self = "&[{integral}]",)),
    106        message = "a slice of type `{Self}` cannot be built since we need to store the elements somewhere",
    107        label = "try explicitly collecting into a `Vec<{A}>`",
    108    ),
    109    on(
    110        Self = "[{A}]",
    111        message = "a slice of type `{Self}` cannot be built since `{Self}` has no definite size",
    112        label = "try explicitly collecting into a `Vec<{A}>`",
    113    ),
    114    on(
    115        all(A = "{integer}", any(Self = "[{integral}]",)),
    116        message = "a slice of type `{Self}` cannot be built since `{Self}` has no definite size",
    117        label = "try explicitly collecting into a `Vec<{A}>`",
    118    ),
    119    on(
    120        Self = "[{A}; _]",
    121        message = "an array of type `{Self}` cannot be built directly from an iterator",
    122        label = "try collecting into a `Vec<{A}>`, then using `.try_into()`",
    123    ),
    124    on(
    125        all(A = "{integer}", any(Self = "[{integral}; _]",)),
    126        message = "an array of type `{Self}` cannot be built directly from an iterator",
    127        label = "try collecting into a `Vec<{A}>`, then using `.try_into()`",
    128    ),
    129    message = "a value of type `{Self}` cannot be built from an iterator \
    130               over elements of type `{A}`",
    131    label = "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
    132)]
    133#[rustc_diagnostic_item = "FromIterator"]
    134pub trait FromIterator<A>: Sized {
    135    /// Creates a value from an iterator.
    136    ///
    137    /// See the [module-level documentation] for more.
    138    ///
    139    /// [module-level documentation]: crate::iter
    140    ///
    141    /// # Examples
    142    ///
    143    /// ```
    144    /// let five_fives = std::iter::repeat(5).take(5);
    145    ///
    146    /// let v = Vec::from_iter(five_fives);
    147    ///
    148    /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
    149    /// ```
    150    #[stable(feature = "rust1", since = "1.0.0")]
    151    #[rustc_diagnostic_item = "from_iter_fn"]
    152    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
    153}
    154
    155/// Conversion into an [`Iterator`].
    156///
    157/// By implementing `IntoIterator` for a type, you define how it will be
    158/// converted to an iterator. This is common for types which describe a
    159/// collection of some kind.
    160///
    161/// One benefit of implementing `IntoIterator` is that your type will [work
    162/// with Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).
    163///
    164/// See also: [`FromIterator`].
    165///
    166/// # Examples
    167///
    168/// Basic usage:
    169///
    170/// ```
    171/// let v = [1, 2, 3];
    172/// let mut iter = v.into_iter();
    173///
    174/// assert_eq!(Some(1), iter.next());
    175/// assert_eq!(Some(2), iter.next());
    176/// assert_eq!(Some(3), iter.next());
    177/// assert_eq!(None, iter.next());
    178/// ```
    179/// Implementing `IntoIterator` for your type:
    180///
    181/// ```
    182/// // A sample collection, that's just a wrapper over Vec<T>
    183/// #[derive(Debug)]
    184/// struct MyCollection(Vec<i32>);
    185///
    186/// // Let's give it some methods so we can create one and add things
    187/// // to it.
    188/// impl MyCollection {
    189///     fn new() -> MyCollection {
    190///         MyCollection(Vec::new())
    191///     }
    192///
    193///     fn add(&mut self, elem: i32) {
    194///         self.0.push(elem);
    195///     }
    196/// }
    197///
    198/// // and we'll implement IntoIterator
    199/// impl IntoIterator for MyCollection {
    200///     type Item = i32;
    201///     type IntoIter = std::vec::IntoIter<Self::Item>;
    202///
    203///     fn into_iter(self) -> Self::IntoIter {
    204///         self.0.into_iter()
    205///     }
    206/// }
    207///
    208/// // Now we can make a new collection...
    209/// let mut c = MyCollection::new();
    210///
    211/// // ... add some stuff to it ...
    212/// c.add(0);
    213/// c.add(1);
    214/// c.add(2);
    215///
    216/// // ... and then turn it into an Iterator:
    217/// for (i, n) in c.into_iter().enumerate() {
    218///     assert_eq!(i as i32, n);
    219/// }
    220/// ```
    221///
    222/// It is common to use `IntoIterator` as a trait bound. This allows
    223/// the input collection type to change, so long as it is still an
    224/// iterator. Additional bounds can be specified by restricting on
    225/// `Item`:
    226///
    227/// ```rust
    228/// fn collect_as_strings<T>(collection: T) -> Vec<String>
    229/// where
    230///     T: IntoIterator,
    231///     T::Item: std::fmt::Debug,
    232/// {
    233///     collection
    234///         .into_iter()
    235///         .map(|item| format!("{item:?}"))
    236///         .collect()
    237/// }
    238/// ```
    239#[rustc_diagnostic_item = "IntoIterator"]
    240#[rustc_on_unimplemented(
    241    on(
    242        Self = "core::ops::range::RangeTo<Idx>",
    243        label = "if you meant to iterate until a value, add a starting value",
    244        note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
    245              bounded `Range`: `0..end`"
    246    ),
    247    on(
    248        Self = "core::ops::range::RangeToInclusive<Idx>",
    249        label = "if you meant to iterate until a value (including it), add a starting value",
    250        note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
    251              to have a bounded `RangeInclusive`: `0..=end`"
    252    ),
    253    on(
    254        Self = "[]",
    255        label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
    256    ),
    257    on(Self = "&[]", label = "`{Self}` is not an iterator; try calling `.iter()`"),
    258    on(
    259        Self = "alloc::vec::Vec<T, A>",
    260        label = "`{Self}` is not an iterator; try calling `.into_iter()` or `.iter()`"
    261    ),
    262    on(Self = "&str", label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"),
    263    on(
    264        Self = "alloc::string::String",
    265        label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
    266    ),
    267    on(
    268        Self = "{integral}",
    269        note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
    270              syntax `start..end` or the inclusive range syntax `start..=end`"
    271    ),
    272    on(
    273        Self = "{float}",
    274        note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
    275              syntax `start..end` or the inclusive range syntax `start..=end`"
    276    ),
    277    label = "`{Self}` is not an iterator",
    278    message = "`{Self}` is not an iterator"
    279)]
    280#[rustc_skip_during_method_dispatch(array, boxed_slice)]
    281#[stable(feature = "rust1", since = "1.0.0")]
    282pub trait IntoIterator {
    283    /// The type of the elements being iterated over.
    284    #[stable(feature = "rust1", since = "1.0.0")]
    285    type Item;
    286
    287    /// Which kind of iterator are we turning this into?
    288    #[stable(feature = "rust1", since = "1.0.0")]
    289    type IntoIter: Iterator<Item = Self::Item>;
    290
    291    /// Creates an iterator from a value.
    292    ///
    293    /// See the [module-level documentation] for more.
    294    ///
    295    /// [module-level documentation]: crate::iter
    296    ///
    297    /// # Examples
    298    ///
    299    /// ```
    300    /// let v = [1, 2, 3];
    301    /// let mut iter = v.into_iter();
    302    ///
    303    /// assert_eq!(Some(1), iter.next());
    304    /// assert_eq!(Some(2), iter.next());
    305    /// assert_eq!(Some(3), iter.next());
    306    /// assert_eq!(None, iter.next());
    307    /// ```
    308    #[lang = "into_iter"]
    309    #[stable(feature = "rust1", since = "1.0.0")]
    310    fn into_iter(self) -> Self::IntoIter;
    311}
    312
    313#[stable(feature = "rust1", since = "1.0.0")]
    314impl<I: Iterator> IntoIterator for I {
    315    type Item = I::Item;
    316    type IntoIter = I;
    317
    318    #[inline]
    319    fn into_iter(self) -> I {
    320        self
    321    }
    322}
    323
    324/// Extend a collection with the contents of an iterator.
    325///
    326/// Iterators produce a series of values, and collections can also be thought
    327/// of as a series of values. The `Extend` trait bridges this gap, allowing you
    328/// to extend a collection by including the contents of that iterator. When
    329/// extending a collection with an already existing key, that entry is updated
    330/// or, in the case of collections that permit multiple entries with equal
    331/// keys, that entry is inserted.
    332///
    333/// # Examples
    334///
    335/// Basic usage:
    336///
    337/// ```
    338/// // You can extend a String with some chars:
    339/// let mut message = String::from("The first three letters are: ");
    340///
    341/// message.extend(&['a', 'b', 'c']);
    342///
    343/// assert_eq!("abc", &message[29..32]);
    344/// ```
    345///
    346/// Implementing `Extend`:
    347///
    348/// ```
    349/// // A sample collection, that's just a wrapper over Vec<T>
    350/// #[derive(Debug)]
    351/// struct MyCollection(Vec<i32>);
    352///
    353/// // Let's give it some methods so we can create one and add things
    354/// // to it.
    355/// impl MyCollection {
    356///     fn new() -> MyCollection {
    357///         MyCollection(Vec::new())
    358///     }
    359///
    360///     fn add(&mut self, elem: i32) {
    361///         self.0.push(elem);
    362///     }
    363/// }
    364///
    365/// // since MyCollection has a list of i32s, we implement Extend for i32
    366/// impl Extend<i32> for MyCollection {
    367///
    368///     // This is a bit simpler with the concrete type signature: we can call
    369///     // extend on anything which can be turned into an Iterator which gives
    370///     // us i32s. Because we need i32s to put into MyCollection.
    371///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
    372///
    373///         // The implementation is very straightforward: loop through the
    374///         // iterator, and add() each element to ourselves.
    375///         for elem in iter {
    376///             self.add(elem);
    377///         }
    378///     }
    379/// }
    380///
    381/// let mut c = MyCollection::new();
    382///
    383/// c.add(5);
    384/// c.add(6);
    385/// c.add(7);
    386///
    387/// // let's extend our collection with three more numbers
    388/// c.extend(vec![1, 2, 3]);
    389///
    390/// // we've added these elements onto the end
    391/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
    392/// ```
    393#[stable(feature = "rust1", since = "1.0.0")]
    394pub trait Extend<A> {
    395    /// Extends a collection with the contents of an iterator.
    396    ///
    397    /// As this is the only required method for this trait, the [trait-level] docs
    398    /// contain more details.
    399    ///
    400    /// [trait-level]: Extend
    401    ///
    402    /// # Examples
    403    ///
    404    /// ```
    405    /// // You can extend a String with some chars:
    406    /// let mut message = String::from("abc");
    407    ///
    408    /// message.extend(['d', 'e', 'f'].iter());
    409    ///
    410    /// assert_eq!("abcdef", &message);
    411    /// ```
    412    #[stable(feature = "rust1", since = "1.0.0")]
    413    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
    414
    415    /// Extends a collection with exactly one element.
    416    #[unstable(feature = "extend_one", issue = "72631")]
    417    fn extend_one(&mut self, item: A) {
    418        self.extend(Some(item));
    419    }
    420
    421    /// Reserves capacity in a collection for the given number of additional elements.
    422    ///
    423    /// The default implementation does nothing.
    424    #[unstable(feature = "extend_one", issue = "72631")]
    425    fn extend_reserve(&mut self, additional: usize) {
    426        let _ = additional;
    427    }
    428
    429    /// Extends a collection with one element, without checking there is enough capacity for it.
    430    ///
    431    /// # Safety
    432    ///
    433    /// **For callers:** This must only be called when we know the collection has enough capacity
    434    /// to contain the new item, for example because we previously called `extend_reserve`.
    435    ///
    436    /// **For implementors:** For a collection to unsafely rely on this method's safety precondition (that is,
    437    /// invoke UB if they are violated), it must implement `extend_reserve` correctly. In other words,
    438    /// callers may assume that if they `extend_reserve`ed enough space they can call this method.
    439    // This method is for internal usage only. It is only on the trait because of specialization's limitations.
    440    #[unstable(feature = "extend_one_unchecked", issue = "none")]
    441    #[doc(hidden)]
    442    unsafe fn extend_one_unchecked(&mut self, item: A)
    443    where
    444        Self: Sized,
    445    {
    446        self.extend_one(item);
    447    }
    448}
    449
    450#[stable(feature = "extend_for_unit", since = "1.28.0")]
    451impl Extend<()> for () {
    452    fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
    453        iter.into_iter().for_each(drop)
    454    }
    455    fn extend_one(&mut self, _item: ()) {}
    456}
    457
    458/// This trait is implemented for tuples up to twelve items long. The `impl`s for
    459/// 1- and 3- through 12-ary tuples were stabilized after 2-tuples, in 1.85.0.
    460#[doc(fake_variadic)] // the other implementations are below.
    461#[stable(feature = "extend_for_tuple", since = "1.56.0")]
    462impl<T, ExtendT> Extend<(T,)> for (ExtendT,)
    463where
    464    ExtendT: Extend<T>,
    465{
    466    /// Allows to `extend` a tuple of collections that also implement `Extend`.
    467    ///
    468    /// See also: [`Iterator::unzip`]
    469    ///
    470    /// # Examples
    471    /// ```
    472    /// // Example given for a 2-tuple, but 1- through 12-tuples are supported
    473    /// let mut tuple = (vec![0], vec![1]);
    474    /// tuple.extend([(2, 3), (4, 5), (6, 7)]);
    475    /// assert_eq!(tuple.0, [0, 2, 4, 6]);
    476    /// assert_eq!(tuple.1, [1, 3, 5, 7]);
    477    ///
    478    /// // also allows for arbitrarily nested tuples as elements
    479    /// let mut nested_tuple = (vec![1], (vec![2], vec![3]));
    480    /// nested_tuple.extend([(4, (5, 6)), (7, (8, 9))]);
    481    ///
    482    /// let (a, (b, c)) = nested_tuple;
    483    /// assert_eq!(a, [1, 4, 7]);
    484    /// assert_eq!(b, [2, 5, 8]);
    485    /// assert_eq!(c, [3, 6, 9]);
    486    /// ```
    487    fn extend<I: IntoIterator<Item = (T,)>>(&mut self, iter: I) {
    488        self.0.extend(iter.into_iter().map(|t| t.0));
    489    }
    490
    491    fn extend_one(&mut self, item: (T,)) {
    492        self.0.extend_one(item.0)
    493    }
    494
    495    fn extend_reserve(&mut self, additional: usize) {
    496        self.0.extend_reserve(additional)
    497    }
    498
    499    unsafe fn extend_one_unchecked(&mut self, item: (T,)) {
    500        // SAFETY: the caller guarantees all preconditions.
    501        unsafe { self.0.extend_one_unchecked(item.0) }
    502    }
    503}
    504
    505/// This implementation turns an iterator of tuples into a tuple of types which implement
    506/// [`Default`] and [`Extend`].
    507///
    508/// This is similar to [`Iterator::unzip`], but is also composable with other [`FromIterator`]
    509/// implementations:
    510///
    511/// ```rust
    512/// # fn main() -> Result<(), core::num::ParseIntError> {
    513/// let string = "1,2,123,4";
    514///
    515/// // Example given for a 2-tuple, but 1- through 12-tuples are supported
    516/// let (numbers, lengths): (Vec<_>, Vec<_>) = string
    517///     .split(',')
    518///     .map(|s| s.parse().map(|n: u32| (n, s.len())))
    519///     .collect::<Result<_, _>>()?;
    520///
    521/// assert_eq!(numbers, [1, 2, 123, 4]);
    522/// assert_eq!(lengths, [1, 1, 3, 1]);
    523/// # Ok(()) }
    524/// ```
    525#[doc(fake_variadic)] // the other implementations are below.
    526#[stable(feature = "from_iterator_for_tuple", since = "1.79.0")]
    527impl<T, ExtendT> FromIterator<(T,)> for (ExtendT,)
    528where
    529    ExtendT: Default + Extend<T>,
    530{
    531    fn from_iter<Iter: IntoIterator<Item = (T,)>>(iter: Iter) -> Self {
    532        let mut res = ExtendT::default();
    533        res.extend(iter.into_iter().map(|t| t.0));
    534        (res,)
    535    }
    536}
    537
    538/// An implementation of [`extend`](Extend::extend) that calls `extend_one` or
    539/// `extend_one_unchecked` for each element of the iterator.
    540fn default_extend<ExtendT, I, T>(collection: &mut ExtendT, iter: I)
    541where
    542    ExtendT: Extend<T>,
    543    I: IntoIterator<Item = T>,
    544{
    545    // Specialize on `TrustedLen` and call `extend_one_unchecked` where
    546    // applicable.
    547    trait SpecExtend<I> {
    548        fn extend(&mut self, iter: I);
    549    }
    550
    551    // Extracting these to separate functions avoid monomorphising the closures
    552    // for every iterator type.
    553    fn extender<ExtendT, T>(collection: &mut ExtendT) -> impl FnMut(T) + use<'_, ExtendT, T>
    554    where
    555        ExtendT: Extend<T>,
    556    {
    557        move |item| collection.extend_one(item)
    558    }
    559
    560    unsafe fn unchecked_extender<ExtendT, T>(
    561        collection: &mut ExtendT,
    562    ) -> impl FnMut(T) + use<'_, ExtendT, T>
    563    where
    564        ExtendT: Extend<T>,
    565    {
    566        // SAFETY: we make sure that there is enough space at the callsite of
    567        // this function.
    568        move |item| unsafe { collection.extend_one_unchecked(item) }
    569    }
    570
    571    impl<ExtendT, I, T> SpecExtend<I> for ExtendT
    572    where
    573        ExtendT: Extend<T>,
    574        I: Iterator<Item = T>,
    575    {
    576        default fn extend(&mut self, iter: I) {
    577            let (lower_bound, _) = iter.size_hint();
    578            if lower_bound > 0 {
    579                self.extend_reserve(lower_bound);
    580            }
    581
    582            iter.for_each(extender(self))
    583        }
    584    }
    585
    586    impl<ExtendT, I, T> SpecExtend<I> for ExtendT
    587    where
    588        ExtendT: Extend<T>,
    589        I: TrustedLen<Item = T>,
    590    {
    591        fn extend(&mut self, iter: I) {
    592            let (lower_bound, upper_bound) = iter.size_hint();
    593            if lower_bound > 0 {
    594                self.extend_reserve(lower_bound);
    595            }
    596
    597            if upper_bound.is_none() {
    598                // We cannot reserve more than `usize::MAX` items, and this is likely to go out of memory anyway.
    599                iter.for_each(extender(self))
    600            } else {
    601                // SAFETY: We reserve enough space for the `size_hint`, and the iterator is
    602                // `TrustedLen` so its `size_hint` is exact.
    603                iter.for_each(unsafe { unchecked_extender(self) })
    604            }
    605        }
    606    }
    607
    608    SpecExtend::extend(collection, iter.into_iter());
    609}
    610
    611// Implements `Extend` and `FromIterator` for tuples with length larger than one.
    612macro_rules! impl_extend_tuple {
    613    ($(($ty:tt, $extend_ty:tt, $index:tt)),+) => {
    614        #[doc(hidden)]
    615        #[stable(feature = "extend_for_tuple", since = "1.56.0")]
    616        impl<$($ty,)+ $($extend_ty,)+> Extend<($($ty,)+)> for ($($extend_ty,)+)
    617        where
    618            $($extend_ty: Extend<$ty>,)+
    619        {
    620            fn extend<T: IntoIterator<Item = ($($ty,)+)>>(&mut self, iter: T) {
    621                default_extend(self, iter)
    622            }
    623
    624            fn extend_one(&mut self, item: ($($ty,)+)) {
    625                $(self.$index.extend_one(item.$index);)+
    626            }
    627
    628            fn extend_reserve(&mut self, additional: usize) {
    629                $(self.$index.extend_reserve(additional);)+
    630            }
    631
    632            unsafe fn extend_one_unchecked(&mut self, item: ($($ty,)+)) {
    633                // SAFETY: Those are our safety preconditions, and we correctly forward `extend_reserve`.
    634                unsafe {
    635                    $(self.$index.extend_one_unchecked(item.$index);)+
    636                }
    637            }
    638        }
    639
    640        #[doc(hidden)]
    641        #[stable(feature = "from_iterator_for_tuple", since = "1.79.0")]
    642        impl<$($ty,)+ $($extend_ty,)+> FromIterator<($($ty,)+)> for ($($extend_ty,)+)
    643        where
    644            $($extend_ty: Default + Extend<$ty>,)+
    645        {
    646            fn from_iter<Iter: IntoIterator<Item = ($($ty,)+)>>(iter: Iter) -> Self {
    647                let mut res = Self::default();
    648                res.extend(iter);
    649                res
    650            }
    651        }
    652    };
    653}
    654
    655impl_extend_tuple!((A, ExA, 0), (B, ExB, 1));
    656impl_extend_tuple!((A, ExA, 0), (B, ExB, 1), (C, ExC, 2));
    657impl_extend_tuple!((A, ExA, 0), (B, ExB, 1), (C, ExC, 2), (D, ExD, 3));
    658impl_extend_tuple!((A, ExA, 0), (B, ExB, 1), (C, ExC, 2), (D, ExD, 3), (E, ExE, 4));
    659impl_extend_tuple!((A, ExA, 0), (B, ExB, 1), (C, ExC, 2), (D, ExD, 3), (E, ExE, 4), (F, ExF, 5));
    660impl_extend_tuple!(
    661    (A, ExA, 0),
    662    (B, ExB, 1),
    663    (C, ExC, 2),
    664    (D, ExD, 3),
    665    (E, ExE, 4),
    666    (F, ExF, 5),
    667    (G, ExG, 6)
    668);
    669impl_extend_tuple!(
    670    (A, ExA, 0),
    671    (B, ExB, 1),
    672    (C, ExC, 2),
    673    (D, ExD, 3),
    674    (E, ExE, 4),
    675    (F, ExF, 5),
    676    (G, ExG, 6),
    677    (H, ExH, 7)
    678);
    679impl_extend_tuple!(
    680    (A, ExA, 0),
    681    (B, ExB, 1),
    682    (C, ExC, 2),
    683    (D, ExD, 3),
    684    (E, ExE, 4),
    685    (F, ExF, 5),
    686    (G, ExG, 6),
    687    (H, ExH, 7),
    688    (I, ExI, 8)
    689);
    690impl_extend_tuple!(
    691    (A, ExA, 0),
    692    (B, ExB, 1),
    693    (C, ExC, 2),
    694    (D, ExD, 3),
    695    (E, ExE, 4),
    696    (F, ExF, 5),
    697    (G, ExG, 6),
    698    (H, ExH, 7),
    699    (I, ExI, 8),
    700    (J, ExJ, 9)
    701);
    702impl_extend_tuple!(
    703    (A, ExA, 0),
    704    (B, ExB, 1),
    705    (C, ExC, 2),
    706    (D, ExD, 3),
    707    (E, ExE, 4),
    708    (F, ExF, 5),
    709    (G, ExG, 6),
    710    (H, ExH, 7),
    711    (I, ExI, 8),
    712    (J, ExJ, 9),
    713    (K, ExK, 10)
    714);
    715impl_extend_tuple!(
    716    (A, ExA, 0),
    717    (B, ExB, 1),
    718    (C, ExC, 2),
    719    (D, ExD, 3),
    720    (E, ExE, 4),
    721    (F, ExF, 5),
    722    (G, ExG, 6),
    723    (H, ExH, 7),
    724    (I, ExI, 8),
    725    (J, ExJ, 9),
    726    (K, ExK, 10),
    727    (L, ExL, 11)
    728);