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