1 | use 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" ] |
134 | pub 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( |
263 | _Self = "&str" , |
264 | label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" |
265 | ), |
266 | on( |
267 | _Self = "alloc::string::String" , |
268 | label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" |
269 | ), |
270 | on( |
271 | _Self = "{integral}" , |
272 | note = "if you want to iterate between `start` until a value `end`, use the exclusive range \ |
273 | syntax `start..end` or the inclusive range syntax `start..=end`" |
274 | ), |
275 | on( |
276 | _Self = "{float}" , |
277 | note = "if you want to iterate between `start` until a value `end`, use the exclusive range \ |
278 | syntax `start..end` or the inclusive range syntax `start..=end`" |
279 | ), |
280 | label = "`{Self}` is not an iterator" , |
281 | message = "`{Self}` is not an iterator" |
282 | )] |
283 | #[rustc_skip_during_method_dispatch(array, boxed_slice)] |
284 | #[stable (feature = "rust1" , since = "1.0.0" )] |
285 | pub trait IntoIterator { |
286 | /// The type of the elements being iterated over. |
287 | #[stable (feature = "rust1" , since = "1.0.0" )] |
288 | type Item; |
289 | |
290 | /// Which kind of iterator are we turning this into? |
291 | #[stable (feature = "rust1" , since = "1.0.0" )] |
292 | type IntoIter: Iterator<Item = Self::Item>; |
293 | |
294 | /// Creates an iterator from a value. |
295 | /// |
296 | /// See the [module-level documentation] for more. |
297 | /// |
298 | /// [module-level documentation]: crate::iter |
299 | /// |
300 | /// # Examples |
301 | /// |
302 | /// ``` |
303 | /// let v = [1, 2, 3]; |
304 | /// let mut iter = v.into_iter(); |
305 | /// |
306 | /// assert_eq!(Some(1), iter.next()); |
307 | /// assert_eq!(Some(2), iter.next()); |
308 | /// assert_eq!(Some(3), iter.next()); |
309 | /// assert_eq!(None, iter.next()); |
310 | /// ``` |
311 | #[lang = "into_iter" ] |
312 | #[stable (feature = "rust1" , since = "1.0.0" )] |
313 | fn into_iter(self) -> Self::IntoIter; |
314 | } |
315 | |
316 | #[stable (feature = "rust1" , since = "1.0.0" )] |
317 | impl<I: Iterator> IntoIterator for I { |
318 | type Item = I::Item; |
319 | type IntoIter = I; |
320 | |
321 | #[inline ] |
322 | fn into_iter(self) -> I { |
323 | self |
324 | } |
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 | pub trait Extend<A> { |
398 | /// Extends a collection with the contents of an iterator. |
399 | /// |
400 | /// As this is the only required method for this trait, the [trait-level] docs |
401 | /// contain more details. |
402 | /// |
403 | /// [trait-level]: Extend |
404 | /// |
405 | /// # Examples |
406 | /// |
407 | /// ``` |
408 | /// // You can extend a String with some chars: |
409 | /// let mut message = String::from("abc" ); |
410 | /// |
411 | /// message.extend(['d' , 'e' , 'f' ].iter()); |
412 | /// |
413 | /// assert_eq!("abcdef" , &message); |
414 | /// ``` |
415 | #[stable (feature = "rust1" , since = "1.0.0" )] |
416 | fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T); |
417 | |
418 | /// Extends a collection with exactly one element. |
419 | #[unstable (feature = "extend_one" , issue = "72631" )] |
420 | fn extend_one(&mut self, item: A) { |
421 | self.extend(Some(item)); |
422 | } |
423 | |
424 | /// Reserves capacity in a collection for the given number of additional elements. |
425 | /// |
426 | /// The default implementation does nothing. |
427 | #[unstable (feature = "extend_one" , issue = "72631" )] |
428 | fn extend_reserve(&mut self, additional: usize) { |
429 | let _ = additional; |
430 | } |
431 | |
432 | /// Extends a collection with one element, without checking there is enough capacity for it. |
433 | /// |
434 | /// # Safety |
435 | /// |
436 | /// **For callers:** This must only be called when we know the collection has enough capacity |
437 | /// to contain the new item, for example because we previously called `extend_reserve`. |
438 | /// |
439 | /// **For implementors:** For a collection to unsafely rely on this method's safety precondition (that is, |
440 | /// invoke UB if they are violated), it must implement `extend_reserve` correctly. In other words, |
441 | /// callers may assume that if they `extend_reserve`ed enough space they can call this method. |
442 | |
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 | impl Extend<()> for () { |
456 | fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) { |
457 | iter.into_iter().for_each(drop) |
458 | } |
459 | fn extend_one(&mut self, _item: ()) {} |
460 | } |
461 | |
462 | macro_rules! spec_tuple_impl { |
463 | ( |
464 | ( |
465 | $ty_name:ident, $var_name:ident, $extend_ty_name: ident, |
466 | $trait_name:ident, $default_fn_name:ident, $cnt:tt |
467 | ), |
468 | ) => { |
469 | spec_tuple_impl!( |
470 | $trait_name, |
471 | $default_fn_name, |
472 | #[doc(fake_variadic)] |
473 | #[doc = "This trait is implemented for tuples up to twelve items long. The `impl`s for \ |
474 | 1- and 3- through 12-ary tuples were stabilized after 2-tuples, in \ |
475 | 1.85.0." ] |
476 | => ($ty_name, $var_name, $extend_ty_name, $cnt), |
477 | ); |
478 | }; |
479 | ( |
480 | ( |
481 | $ty_name:ident, $var_name:ident, $extend_ty_name: ident, |
482 | $trait_name:ident, $default_fn_name:ident, $cnt:tt |
483 | ), |
484 | $( |
485 | ( |
486 | $ty_names:ident, $var_names:ident, $extend_ty_names:ident, |
487 | $trait_names:ident, $default_fn_names:ident, $cnts:tt |
488 | ), |
489 | )* |
490 | ) => { |
491 | spec_tuple_impl!( |
492 | $( |
493 | ( |
494 | $ty_names, $var_names, $extend_ty_names, |
495 | $trait_names, $default_fn_names, $cnts |
496 | ), |
497 | )* |
498 | ); |
499 | spec_tuple_impl!( |
500 | $trait_name, |
501 | $default_fn_name, |
502 | #[doc(hidden)] |
503 | => ( |
504 | $ty_name, $var_name, $extend_ty_name, $cnt |
505 | ), |
506 | $( |
507 | ( |
508 | $ty_names, $var_names, $extend_ty_names, $cnts |
509 | ), |
510 | )* |
511 | ); |
512 | }; |
513 | ( |
514 | $trait_name:ident, $default_fn_name:ident, #[$meta:meta] |
515 | $(#[$doctext:meta])? => $( |
516 | ( |
517 | $ty_names:ident, $var_names:ident, $extend_ty_names:ident, $cnts:tt |
518 | ), |
519 | )* |
520 | ) => { |
521 | #[$meta] |
522 | $(#[$doctext])? |
523 | #[stable(feature = "extend_for_tuple" , since = "1.56.0" )] |
524 | impl<$($ty_names,)* $($extend_ty_names,)*> Extend<($($ty_names,)*)> for ($($extend_ty_names,)*) |
525 | where |
526 | $($extend_ty_names: Extend<$ty_names>,)* |
527 | { |
528 | /// Allows to `extend` a tuple of collections that also implement `Extend`. |
529 | /// |
530 | /// See also: [`Iterator::unzip`] |
531 | /// |
532 | /// # Examples |
533 | /// ``` |
534 | /// // Example given for a 2-tuple, but 1- through 12-tuples are supported |
535 | /// let mut tuple = (vec![0], vec![1]); |
536 | /// tuple.extend([(2, 3), (4, 5), (6, 7)]); |
537 | /// assert_eq!(tuple.0, [0, 2, 4, 6]); |
538 | /// assert_eq!(tuple.1, [1, 3, 5, 7]); |
539 | /// |
540 | /// // also allows for arbitrarily nested tuples as elements |
541 | /// let mut nested_tuple = (vec![1], (vec![2], vec![3])); |
542 | /// nested_tuple.extend([(4, (5, 6)), (7, (8, 9))]); |
543 | /// |
544 | /// let (a, (b, c)) = nested_tuple; |
545 | /// assert_eq!(a, [1, 4, 7]); |
546 | /// assert_eq!(b, [2, 5, 8]); |
547 | /// assert_eq!(c, [3, 6, 9]); |
548 | /// ``` |
549 | fn extend<T: IntoIterator<Item = ($($ty_names,)*)>>(&mut self, into_iter: T) { |
550 | let ($($var_names,)*) = self; |
551 | let iter = into_iter.into_iter(); |
552 | $trait_name::extend(iter, $($var_names,)*); |
553 | } |
554 | |
555 | fn extend_one(&mut self, item: ($($ty_names,)*)) { |
556 | $(self.$cnts.extend_one(item.$cnts);)* |
557 | } |
558 | |
559 | fn extend_reserve(&mut self, additional: usize) { |
560 | $(self.$cnts.extend_reserve(additional);)* |
561 | } |
562 | |
563 | unsafe fn extend_one_unchecked(&mut self, item: ($($ty_names,)*)) { |
564 | // SAFETY: Those are our safety preconditions, and we correctly forward `extend_reserve`. |
565 | unsafe { |
566 | $(self.$cnts.extend_one_unchecked(item.$cnts);)* |
567 | } |
568 | } |
569 | } |
570 | |
571 | trait $trait_name<$($ty_names),*> { |
572 | fn extend(self, $($var_names: &mut $ty_names,)*); |
573 | } |
574 | |
575 | fn $default_fn_name<$($ty_names,)* $($extend_ty_names,)*>( |
576 | iter: impl Iterator<Item = ($($ty_names,)*)>, |
577 | $($var_names: &mut $extend_ty_names,)* |
578 | ) where |
579 | $($extend_ty_names: Extend<$ty_names>,)* |
580 | { |
581 | fn extend<'a, $($ty_names,)*>( |
582 | $($var_names: &'a mut impl Extend<$ty_names>,)* |
583 | ) -> impl FnMut((), ($($ty_names,)*)) + 'a { |
584 | #[allow(non_snake_case)] |
585 | move |(), ($($extend_ty_names,)*)| { |
586 | $($var_names.extend_one($extend_ty_names);)* |
587 | } |
588 | } |
589 | |
590 | let (lower_bound, _) = iter.size_hint(); |
591 | if lower_bound > 0 { |
592 | $($var_names.extend_reserve(lower_bound);)* |
593 | } |
594 | |
595 | iter.fold((), extend($($var_names,)*)); |
596 | } |
597 | |
598 | impl<$($ty_names,)* $($extend_ty_names,)* Iter> $trait_name<$($extend_ty_names),*> for Iter |
599 | where |
600 | $($extend_ty_names: Extend<$ty_names>,)* |
601 | Iter: Iterator<Item = ($($ty_names,)*)>, |
602 | { |
603 | default fn extend(self, $($var_names: &mut $extend_ty_names),*) { |
604 | $default_fn_name(self, $($var_names),*); |
605 | } |
606 | } |
607 | |
608 | impl<$($ty_names,)* $($extend_ty_names,)* Iter> $trait_name<$($extend_ty_names),*> for Iter |
609 | where |
610 | $($extend_ty_names: Extend<$ty_names>,)* |
611 | Iter: TrustedLen<Item = ($($ty_names,)*)>, |
612 | { |
613 | fn extend(self, $($var_names: &mut $extend_ty_names,)*) { |
614 | fn extend<'a, $($ty_names,)*>( |
615 | $($var_names: &'a mut impl Extend<$ty_names>,)* |
616 | ) -> impl FnMut((), ($($ty_names,)*)) + 'a { |
617 | #[allow(non_snake_case)] |
618 | // SAFETY: We reserve enough space for the `size_hint`, and the iterator is |
619 | // `TrustedLen` so its `size_hint` is exact. |
620 | move |(), ($($extend_ty_names,)*)| unsafe { |
621 | $($var_names.extend_one_unchecked($extend_ty_names);)* |
622 | } |
623 | } |
624 | |
625 | let (lower_bound, upper_bound) = self.size_hint(); |
626 | |
627 | if upper_bound.is_none() { |
628 | // We cannot reserve more than `usize::MAX` items, and this is likely to go out of memory anyway. |
629 | $default_fn_name(self, $($var_names,)*); |
630 | return; |
631 | } |
632 | |
633 | if lower_bound > 0 { |
634 | $($var_names.extend_reserve(lower_bound);)* |
635 | } |
636 | |
637 | self.fold((), extend($($var_names,)*)); |
638 | } |
639 | } |
640 | |
641 | /// This implementation turns an iterator of tuples into a tuple of types which implement |
642 | /// [`Default`] and [`Extend`]. |
643 | /// |
644 | /// This is similar to [`Iterator::unzip`], but is also composable with other [`FromIterator`] |
645 | /// implementations: |
646 | /// |
647 | /// ```rust |
648 | /// # fn main() -> Result<(), core::num::ParseIntError> { |
649 | /// let string = "1,2,123,4"; |
650 | /// |
651 | /// // Example given for a 2-tuple, but 1- through 12-tuples are supported |
652 | /// let (numbers, lengths): (Vec<_>, Vec<_>) = string |
653 | /// .split(',') |
654 | /// .map(|s| s.parse().map(|n: u32| (n, s.len()))) |
655 | /// .collect::<Result<_, _>>()?; |
656 | /// |
657 | /// assert_eq!(numbers, [1, 2, 123, 4]); |
658 | /// assert_eq!(lengths, [1, 1, 3, 1]); |
659 | /// # Ok(()) } |
660 | /// ``` |
661 | #[$meta] |
662 | $(#[$doctext])? |
663 | #[stable(feature = "from_iterator_for_tuple" , since = "1.79.0" )] |
664 | impl<$($ty_names,)* $($extend_ty_names,)*> FromIterator<($($extend_ty_names,)*)> for ($($ty_names,)*) |
665 | where |
666 | $($ty_names: Default + Extend<$extend_ty_names>,)* |
667 | { |
668 | fn from_iter<Iter: IntoIterator<Item = ($($extend_ty_names,)*)>>(iter: Iter) -> Self { |
669 | let mut res = <($($ty_names,)*)>::default(); |
670 | res.extend(iter); |
671 | |
672 | res |
673 | } |
674 | } |
675 | |
676 | }; |
677 | } |
678 | |
679 | spec_tuple_impl!( |
680 | (L, l, EL, TraitL, default_extend_tuple_l, 11), |
681 | (K, k, EK, TraitK, default_extend_tuple_k, 10), |
682 | (J, j, EJ, TraitJ, default_extend_tuple_j, 9), |
683 | (I, i, EI, TraitI, default_extend_tuple_i, 8), |
684 | (H, h, EH, TraitH, default_extend_tuple_h, 7), |
685 | (G, g, EG, TraitG, default_extend_tuple_g, 6), |
686 | (F, f, EF, TraitF, default_extend_tuple_f, 5), |
687 | (E, e, EE, TraitE, default_extend_tuple_e, 4), |
688 | (D, d, ED, TraitD, default_extend_tuple_d, 3), |
689 | (C, c, EC, TraitC, default_extend_tuple_c, 2), |
690 | (B, b, EB, TraitB, default_extend_tuple_b, 1), |
691 | (A, a, EA, TraitA, default_extend_tuple_a, 0), |
692 | ); |
693 | |