]> git.proxmox.com Git - rustc.git/blob - library/core/src/iter/traits/collect.rs
New upstream version 1.53.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 /// [`FromIterator::from_iter()`] is rarely called explicitly, and is instead
8 /// used through [`Iterator::collect()`] method. See [`Iterator::collect()`]'s
9 /// documentation for more examples.
10 ///
11 /// See also: [`IntoIterator`].
12 ///
13 /// # Examples
14 ///
15 /// Basic usage:
16 ///
17 /// ```
18 /// use std::iter::FromIterator;
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 /// Implementing `FromIterator` for your type:
38 ///
39 /// ```
40 /// use std::iter::FromIterator;
41 ///
42 /// // A sample collection, that's just a wrapper over Vec<T>
43 /// #[derive(Debug)]
44 /// struct MyCollection(Vec<i32>);
45 ///
46 /// // Let's give it some methods so we can create one and add things
47 /// // to it.
48 /// impl MyCollection {
49 /// fn new() -> MyCollection {
50 /// MyCollection(Vec::new())
51 /// }
52 ///
53 /// fn add(&mut self, elem: i32) {
54 /// self.0.push(elem);
55 /// }
56 /// }
57 ///
58 /// // and we'll implement FromIterator
59 /// impl FromIterator<i32> for MyCollection {
60 /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
61 /// let mut c = MyCollection::new();
62 ///
63 /// for i in iter {
64 /// c.add(i);
65 /// }
66 ///
67 /// c
68 /// }
69 /// }
70 ///
71 /// // Now we can make a new iterator...
72 /// let iter = (0..5).into_iter();
73 ///
74 /// // ... and make a MyCollection out of it
75 /// let c = MyCollection::from_iter(iter);
76 ///
77 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
78 ///
79 /// // collect works too!
80 ///
81 /// let iter = (0..5).into_iter();
82 /// let c: MyCollection = iter.collect();
83 ///
84 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
85 /// ```
86 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_on_unimplemented(
88 message = "a value of type `{Self}` cannot be built from an iterator \
89 over elements of type `{A}`",
90 label = "value of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`"
91 )]
92 pub trait FromIterator<A>: Sized {
93 /// Creates a value from an iterator.
94 ///
95 /// See the [module-level documentation] for more.
96 ///
97 /// [module-level documentation]: crate::iter
98 ///
99 /// # Examples
100 ///
101 /// Basic usage:
102 ///
103 /// ```
104 /// use std::iter::FromIterator;
105 ///
106 /// let five_fives = std::iter::repeat(5).take(5);
107 ///
108 /// let v = Vec::from_iter(five_fives);
109 ///
110 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
111 /// ```
112 #[stable(feature = "rust1", since = "1.0.0")]
113 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
114 }
115
116 /// Conversion into an [`Iterator`].
117 ///
118 /// By implementing `IntoIterator` for a type, you define how it will be
119 /// converted to an iterator. This is common for types which describe a
120 /// collection of some kind.
121 ///
122 /// One benefit of implementing `IntoIterator` is that your type will [work
123 /// with Rust's `for` loop syntax](crate::iter#for-loops-and-intoiterator).
124 ///
125 /// See also: [`FromIterator`].
126 ///
127 /// # Examples
128 ///
129 /// Basic usage:
130 ///
131 /// ```
132 /// let v = vec![1, 2, 3];
133 /// let mut iter = v.into_iter();
134 ///
135 /// assert_eq!(Some(1), iter.next());
136 /// assert_eq!(Some(2), iter.next());
137 /// assert_eq!(Some(3), iter.next());
138 /// assert_eq!(None, iter.next());
139 /// ```
140 /// Implementing `IntoIterator` for your type:
141 ///
142 /// ```
143 /// // A sample collection, that's just a wrapper over Vec<T>
144 /// #[derive(Debug)]
145 /// struct MyCollection(Vec<i32>);
146 ///
147 /// // Let's give it some methods so we can create one and add things
148 /// // to it.
149 /// impl MyCollection {
150 /// fn new() -> MyCollection {
151 /// MyCollection(Vec::new())
152 /// }
153 ///
154 /// fn add(&mut self, elem: i32) {
155 /// self.0.push(elem);
156 /// }
157 /// }
158 ///
159 /// // and we'll implement IntoIterator
160 /// impl IntoIterator for MyCollection {
161 /// type Item = i32;
162 /// type IntoIter = std::vec::IntoIter<Self::Item>;
163 ///
164 /// fn into_iter(self) -> Self::IntoIter {
165 /// self.0.into_iter()
166 /// }
167 /// }
168 ///
169 /// // Now we can make a new collection...
170 /// let mut c = MyCollection::new();
171 ///
172 /// // ... add some stuff to it ...
173 /// c.add(0);
174 /// c.add(1);
175 /// c.add(2);
176 ///
177 /// // ... and then turn it into an Iterator:
178 /// for (i, n) in c.into_iter().enumerate() {
179 /// assert_eq!(i as i32, n);
180 /// }
181 /// ```
182 ///
183 /// It is common to use `IntoIterator` as a trait bound. This allows
184 /// the input collection type to change, so long as it is still an
185 /// iterator. Additional bounds can be specified by restricting on
186 /// `Item`:
187 ///
188 /// ```rust
189 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
190 /// where
191 /// T: IntoIterator,
192 /// T::Item: std::fmt::Debug,
193 /// {
194 /// collection
195 /// .into_iter()
196 /// .map(|item| format!("{:?}", item))
197 /// .collect()
198 /// }
199 /// ```
200 #[rustc_diagnostic_item = "IntoIterator"]
201 #[cfg_attr(not(bootstrap), rustc_skip_array_during_method_dispatch)]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub trait IntoIterator {
204 /// The type of the elements being iterated over.
205 #[stable(feature = "rust1", since = "1.0.0")]
206 type Item;
207
208 /// Which kind of iterator are we turning this into?
209 #[stable(feature = "rust1", since = "1.0.0")]
210 type IntoIter: Iterator<Item = Self::Item>;
211
212 /// Creates an iterator from a value.
213 ///
214 /// See the [module-level documentation] for more.
215 ///
216 /// [module-level documentation]: crate::iter
217 ///
218 /// # Examples
219 ///
220 /// Basic usage:
221 ///
222 /// ```
223 /// let v = vec![1, 2, 3];
224 /// let mut iter = v.into_iter();
225 ///
226 /// assert_eq!(Some(1), iter.next());
227 /// assert_eq!(Some(2), iter.next());
228 /// assert_eq!(Some(3), iter.next());
229 /// assert_eq!(None, iter.next());
230 /// ```
231 #[lang = "into_iter"]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 fn into_iter(self) -> Self::IntoIter;
234 }
235
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<I: Iterator> IntoIterator for I {
238 type Item = I::Item;
239 type IntoIter = I;
240
241 fn into_iter(self) -> I {
242 self
243 }
244 }
245
246 /// Extend a collection with the contents of an iterator.
247 ///
248 /// Iterators produce a series of values, and collections can also be thought
249 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
250 /// to extend a collection by including the contents of that iterator. When
251 /// extending a collection with an already existing key, that entry is updated
252 /// or, in the case of collections that permit multiple entries with equal
253 /// keys, that entry is inserted.
254 ///
255 /// # Examples
256 ///
257 /// Basic usage:
258 ///
259 /// ```
260 /// // You can extend a String with some chars:
261 /// let mut message = String::from("The first three letters are: ");
262 ///
263 /// message.extend(&['a', 'b', 'c']);
264 ///
265 /// assert_eq!("abc", &message[29..32]);
266 /// ```
267 ///
268 /// Implementing `Extend`:
269 ///
270 /// ```
271 /// // A sample collection, that's just a wrapper over Vec<T>
272 /// #[derive(Debug)]
273 /// struct MyCollection(Vec<i32>);
274 ///
275 /// // Let's give it some methods so we can create one and add things
276 /// // to it.
277 /// impl MyCollection {
278 /// fn new() -> MyCollection {
279 /// MyCollection(Vec::new())
280 /// }
281 ///
282 /// fn add(&mut self, elem: i32) {
283 /// self.0.push(elem);
284 /// }
285 /// }
286 ///
287 /// // since MyCollection has a list of i32s, we implement Extend for i32
288 /// impl Extend<i32> for MyCollection {
289 ///
290 /// // This is a bit simpler with the concrete type signature: we can call
291 /// // extend on anything which can be turned into an Iterator which gives
292 /// // us i32s. Because we need i32s to put into MyCollection.
293 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
294 ///
295 /// // The implementation is very straightforward: loop through the
296 /// // iterator, and add() each element to ourselves.
297 /// for elem in iter {
298 /// self.add(elem);
299 /// }
300 /// }
301 /// }
302 ///
303 /// let mut c = MyCollection::new();
304 ///
305 /// c.add(5);
306 /// c.add(6);
307 /// c.add(7);
308 ///
309 /// // let's extend our collection with three more numbers
310 /// c.extend(vec![1, 2, 3]);
311 ///
312 /// // we've added these elements onto the end
313 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
314 /// ```
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub trait Extend<A> {
317 /// Extends a collection with the contents of an iterator.
318 ///
319 /// As this is the only required method for this trait, the [trait-level] docs
320 /// contain more details.
321 ///
322 /// [trait-level]: Extend
323 ///
324 /// # Examples
325 ///
326 /// Basic usage:
327 ///
328 /// ```
329 /// // You can extend a String with some chars:
330 /// let mut message = String::from("abc");
331 ///
332 /// message.extend(['d', 'e', 'f'].iter());
333 ///
334 /// assert_eq!("abcdef", &message);
335 /// ```
336 #[stable(feature = "rust1", since = "1.0.0")]
337 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
338
339 /// Extends a collection with exactly one element.
340 #[unstable(feature = "extend_one", issue = "72631")]
341 fn extend_one(&mut self, item: A) {
342 self.extend(Some(item));
343 }
344
345 /// Reserves capacity in a collection for the given number of additional elements.
346 ///
347 /// The default implementation does nothing.
348 #[unstable(feature = "extend_one", issue = "72631")]
349 fn extend_reserve(&mut self, additional: usize) {
350 let _ = additional;
351 }
352 }
353
354 #[stable(feature = "extend_for_unit", since = "1.28.0")]
355 impl Extend<()> for () {
356 fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
357 iter.into_iter().for_each(drop)
358 }
359 fn extend_one(&mut self, _item: ()) {}
360 }