]> git.proxmox.com Git - rustc.git/blob - library/core/src/iter/traits/collect.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / library / core / src / iter / traits / collect.rs
1 /// Conversion from an [`Iterator`].
2 ///
3 /// By implementing `FromIterator` for a type, you define how it will be
4 /// created from an iterator. This is common for types which describe a
5 /// collection of some kind.
6 ///
7 /// If you want to create a collection from the contents of an iterator, the
8 /// [`Iterator::collect()`] method is preferred. However, when you need to
9 /// specify the container type, [`FromIterator::from_iter()`] can be more
10 /// readable than using a turbofish (e.g. `::<Vec<_>>()`). See the
11 /// [`Iterator::collect()`] documentation for more examples of its use.
12 ///
13 /// See also: [`IntoIterator`].
14 ///
15 /// # Examples
16 ///
17 /// Basic usage:
18 ///
19 /// ```
20 /// let five_fives = std::iter::repeat(5).take(5);
21 ///
22 /// let v = Vec::from_iter(five_fives);
23 ///
24 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
25 /// ```
26 ///
27 /// Using [`Iterator::collect()`] to implicitly use `FromIterator`:
28 ///
29 /// ```
30 /// let five_fives = std::iter::repeat(5).take(5);
31 ///
32 /// let v: Vec<i32> = five_fives.collect();
33 ///
34 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
35 /// ```
36 ///
37 /// Using [`FromIterator::from_iter()`] as a more readable alternative to
38 /// [`Iterator::collect()`]:
39 ///
40 /// ```
41 /// use std::collections::VecDeque;
42 /// let first = (0..10).collect::<VecDeque<i32>>();
43 /// let second = VecDeque::from_iter(0..10);
44 ///
45 /// assert_eq!(first, second);
46 /// ```
47 ///
48 /// Implementing `FromIterator` for your type:
49 ///
50 /// ```
51 /// // A sample collection, that's just a wrapper over Vec<T>
52 /// #[derive(Debug)]
53 /// struct MyCollection(Vec<i32>);
54 ///
55 /// // Let's give it some methods so we can create one and add things
56 /// // to it.
57 /// impl MyCollection {
58 /// fn new() -> MyCollection {
59 /// MyCollection(Vec::new())
60 /// }
61 ///
62 /// fn add(&mut self, elem: i32) {
63 /// self.0.push(elem);
64 /// }
65 /// }
66 ///
67 /// // and we'll implement FromIterator
68 /// impl FromIterator<i32> for MyCollection {
69 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
70 /// let mut c = MyCollection::new();
71 ///
72 /// for i in iter {
73 /// c.add(i);
74 /// }
75 ///
76 /// c
77 /// }
78 /// }
79 ///
80 /// // Now we can make a new iterator...
81 /// let iter = (0..5).into_iter();
82 ///
83 /// // ... and make a MyCollection out of it
84 /// let c = MyCollection::from_iter(iter);
85 ///
86 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
87 ///
88 /// // collect works too!
89 ///
90 /// let iter = (0..5).into_iter();
91 /// let c: MyCollection = iter.collect();
92 ///
93 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
94 /// ```
95 #[stable(feature = "rust1", since = "1.0.0")]
96 #[rustc_on_unimplemented(
97 on(
98 _Self = "[{A}]",
99 message = "a value of type `{Self}` cannot be built since `{Self}` has no definite size",
100 label = "try explicitly collecting into a `Vec<{A}>`",
101 ),
102 on(
103 all(
104 A = "{integer}",
105 any(
106 _Self = "[i8]",
107 _Self = "[i16]",
108 _Self = "[i32]",
109 _Self = "[i64]",
110 _Self = "[i128]",
111 _Self = "[isize]",
112 _Self = "[u8]",
113 _Self = "[u16]",
114 _Self = "[u32]",
115 _Self = "[u64]",
116 _Self = "[u128]",
117 _Self = "[usize]"
118 )
119 ),
120 message = "a value of type `{Self}` cannot be built since `{Self}` has no definite size",
121 label = "try explicitly collecting into a `Vec<{A}>`",
122 ),
123 message = "a value of type `{Self}` cannot be built from an iterator \
124 over elements of type `{A}`",
125 label = "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
126 )]
127 #[rustc_diagnostic_item = "FromIterator"]
128 pub trait FromIterator<A>: Sized {
129 /// Creates a value from an iterator.
130 ///
131 /// See the [module-level documentation] for more.
132 ///
133 /// [module-level documentation]: crate::iter
134 ///
135 /// # Examples
136 ///
137 /// Basic usage:
138 ///
139 /// ```
140 /// let five_fives = std::iter::repeat(5).take(5);
141 ///
142 /// let v = Vec::from_iter(five_fives);
143 ///
144 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
145 /// ```
146 #[stable(feature = "rust1", since = "1.0.0")]
147 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
148 }
149
150 /// Conversion into an [`Iterator`].
151 ///
152 /// By implementing `IntoIterator` for a type, you define how it will be
153 /// converted to an iterator. This is common for types which describe a
154 /// collection of some kind.
155 ///
156 /// One benefit of implementing `IntoIterator` is that your type will [work
157 /// with Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).
158 ///
159 /// See also: [`FromIterator`].
160 ///
161 /// # Examples
162 ///
163 /// Basic usage:
164 ///
165 /// ```
166 /// let v = [1, 2, 3];
167 /// let mut iter = v.into_iter();
168 ///
169 /// assert_eq!(Some(1), iter.next());
170 /// assert_eq!(Some(2), iter.next());
171 /// assert_eq!(Some(3), iter.next());
172 /// assert_eq!(None, iter.next());
173 /// ```
174 /// Implementing `IntoIterator` for your type:
175 ///
176 /// ```
177 /// // A sample collection, that's just a wrapper over Vec<T>
178 /// #[derive(Debug)]
179 /// struct MyCollection(Vec<i32>);
180 ///
181 /// // Let's give it some methods so we can create one and add things
182 /// // to it.
183 /// impl MyCollection {
184 /// fn new() -> MyCollection {
185 /// MyCollection(Vec::new())
186 /// }
187 ///
188 /// fn add(&mut self, elem: i32) {
189 /// self.0.push(elem);
190 /// }
191 /// }
192 ///
193 /// // and we'll implement IntoIterator
194 /// impl IntoIterator for MyCollection {
195 /// type Item = i32;
196 /// type IntoIter = std::vec::IntoIter<Self::Item>;
197 ///
198 /// fn into_iter(self) -> Self::IntoIter {
199 /// self.0.into_iter()
200 /// }
201 /// }
202 ///
203 /// // Now we can make a new collection...
204 /// let mut c = MyCollection::new();
205 ///
206 /// // ... add some stuff to it ...
207 /// c.add(0);
208 /// c.add(1);
209 /// c.add(2);
210 ///
211 /// // ... and then turn it into an Iterator:
212 /// for (i, n) in c.into_iter().enumerate() {
213 /// assert_eq!(i as i32, n);
214 /// }
215 /// ```
216 ///
217 /// It is common to use `IntoIterator` as a trait bound. This allows
218 /// the input collection type to change, so long as it is still an
219 /// iterator. Additional bounds can be specified by restricting on
220 /// `Item`:
221 ///
222 /// ```rust
223 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
224 /// where
225 /// T: IntoIterator,
226 /// T::Item: std::fmt::Debug,
227 /// {
228 /// collection
229 /// .into_iter()
230 /// .map(|item| format!("{item:?}"))
231 /// .collect()
232 /// }
233 /// ```
234 #[rustc_diagnostic_item = "IntoIterator"]
235 #[rustc_skip_array_during_method_dispatch]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub trait IntoIterator {
238 /// The type of the elements being iterated over.
239 #[stable(feature = "rust1", since = "1.0.0")]
240 type Item;
241
242 /// Which kind of iterator are we turning this into?
243 #[stable(feature = "rust1", since = "1.0.0")]
244 type IntoIter: Iterator<Item = Self::Item>;
245
246 /// Creates an iterator from a value.
247 ///
248 /// See the [module-level documentation] for more.
249 ///
250 /// [module-level documentation]: crate::iter
251 ///
252 /// # Examples
253 ///
254 /// Basic usage:
255 ///
256 /// ```
257 /// let v = [1, 2, 3];
258 /// let mut iter = v.into_iter();
259 ///
260 /// assert_eq!(Some(1), iter.next());
261 /// assert_eq!(Some(2), iter.next());
262 /// assert_eq!(Some(3), iter.next());
263 /// assert_eq!(None, iter.next());
264 /// ```
265 #[lang = "into_iter"]
266 #[stable(feature = "rust1", since = "1.0.0")]
267 fn into_iter(self) -> Self::IntoIter;
268 }
269
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl<I: Iterator> IntoIterator for I {
272 type Item = I::Item;
273 type IntoIter = I;
274
275 #[inline]
276 fn into_iter(self) -> I {
277 self
278 }
279 }
280
281 /// Extend a collection with the contents of an iterator.
282 ///
283 /// Iterators produce a series of values, and collections can also be thought
284 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
285 /// to extend a collection by including the contents of that iterator. When
286 /// extending a collection with an already existing key, that entry is updated
287 /// or, in the case of collections that permit multiple entries with equal
288 /// keys, that entry is inserted.
289 ///
290 /// # Examples
291 ///
292 /// Basic usage:
293 ///
294 /// ```
295 /// // You can extend a String with some chars:
296 /// let mut message = String::from("The first three letters are: ");
297 ///
298 /// message.extend(&['a', 'b', 'c']);
299 ///
300 /// assert_eq!("abc", &message[29..32]);
301 /// ```
302 ///
303 /// Implementing `Extend`:
304 ///
305 /// ```
306 /// // A sample collection, that's just a wrapper over Vec<T>
307 /// #[derive(Debug)]
308 /// struct MyCollection(Vec<i32>);
309 ///
310 /// // Let's give it some methods so we can create one and add things
311 /// // to it.
312 /// impl MyCollection {
313 /// fn new() -> MyCollection {
314 /// MyCollection(Vec::new())
315 /// }
316 ///
317 /// fn add(&mut self, elem: i32) {
318 /// self.0.push(elem);
319 /// }
320 /// }
321 ///
322 /// // since MyCollection has a list of i32s, we implement Extend for i32
323 /// impl Extend<i32> for MyCollection {
324 ///
325 /// // This is a bit simpler with the concrete type signature: we can call
326 /// // extend on anything which can be turned into an Iterator which gives
327 /// // us i32s. Because we need i32s to put into MyCollection.
328 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
329 ///
330 /// // The implementation is very straightforward: loop through the
331 /// // iterator, and add() each element to ourselves.
332 /// for elem in iter {
333 /// self.add(elem);
334 /// }
335 /// }
336 /// }
337 ///
338 /// let mut c = MyCollection::new();
339 ///
340 /// c.add(5);
341 /// c.add(6);
342 /// c.add(7);
343 ///
344 /// // let's extend our collection with three more numbers
345 /// c.extend(vec![1, 2, 3]);
346 ///
347 /// // we've added these elements onto the end
348 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
349 /// ```
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub trait Extend<A> {
352 /// Extends a collection with the contents of an iterator.
353 ///
354 /// As this is the only required method for this trait, the [trait-level] docs
355 /// contain more details.
356 ///
357 /// [trait-level]: Extend
358 ///
359 /// # Examples
360 ///
361 /// Basic usage:
362 ///
363 /// ```
364 /// // You can extend a String with some chars:
365 /// let mut message = String::from("abc");
366 ///
367 /// message.extend(['d', 'e', 'f'].iter());
368 ///
369 /// assert_eq!("abcdef", &message);
370 /// ```
371 #[stable(feature = "rust1", since = "1.0.0")]
372 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
373
374 /// Extends a collection with exactly one element.
375 #[unstable(feature = "extend_one", issue = "72631")]
376 fn extend_one(&mut self, item: A) {
377 self.extend(Some(item));
378 }
379
380 /// Reserves capacity in a collection for the given number of additional elements.
381 ///
382 /// The default implementation does nothing.
383 #[unstable(feature = "extend_one", issue = "72631")]
384 fn extend_reserve(&mut self, additional: usize) {
385 let _ = additional;
386 }
387 }
388
389 #[stable(feature = "extend_for_unit", since = "1.28.0")]
390 impl Extend<()> for () {
391 fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
392 iter.into_iter().for_each(drop)
393 }
394 fn extend_one(&mut self, _item: ()) {}
395 }
396
397 #[stable(feature = "extend_for_tuple", since = "1.56.0")]
398 impl<A, B, ExtendA, ExtendB> Extend<(A, B)> for (ExtendA, ExtendB)
399 where
400 ExtendA: Extend<A>,
401 ExtendB: Extend<B>,
402 {
403 /// Allows to `extend` a tuple of collections that also implement `Extend`.
404 ///
405 /// See also: [`Iterator::unzip`]
406 ///
407 /// # Examples
408 /// ```
409 /// let mut tuple = (vec![0], vec![1]);
410 /// tuple.extend([(2, 3), (4, 5), (6, 7)]);
411 /// assert_eq!(tuple.0, [0, 2, 4, 6]);
412 /// assert_eq!(tuple.1, [1, 3, 5, 7]);
413 ///
414 /// // also allows for arbitrarily nested tuples as elements
415 /// let mut nested_tuple = (vec![1], (vec![2], vec![3]));
416 /// nested_tuple.extend([(4, (5, 6)), (7, (8, 9))]);
417 ///
418 /// let (a, (b, c)) = nested_tuple;
419 /// assert_eq!(a, [1, 4, 7]);
420 /// assert_eq!(b, [2, 5, 8]);
421 /// assert_eq!(c, [3, 6, 9]);
422 /// ```
423 fn extend<T: IntoIterator<Item = (A, B)>>(&mut self, into_iter: T) {
424 let (a, b) = self;
425 let iter = into_iter.into_iter();
426
427 fn extend<'a, A, B>(
428 a: &'a mut impl Extend<A>,
429 b: &'a mut impl Extend<B>,
430 ) -> impl FnMut((), (A, B)) + 'a {
431 move |(), (t, u)| {
432 a.extend_one(t);
433 b.extend_one(u);
434 }
435 }
436
437 let (lower_bound, _) = iter.size_hint();
438 if lower_bound > 0 {
439 a.extend_reserve(lower_bound);
440 b.extend_reserve(lower_bound);
441 }
442
443 iter.fold((), extend(a, b));
444 }
445
446 fn extend_one(&mut self, item: (A, B)) {
447 self.0.extend_one(item.0);
448 self.1.extend_one(item.1);
449 }
450
451 fn extend_reserve(&mut self, additional: usize) {
452 self.0.extend_reserve(additional);
453 self.1.extend_reserve(additional);
454 }
455 }