Skip to content

Commit 3ba9733

Browse files
author
Clar Fon
committed
Move FromIterator, IntoIterator, Extend into own module
1 parent 6a28459 commit 3ba9733

File tree

2 files changed

+351
-350
lines changed

2 files changed

+351
-350
lines changed

src/libcore/iter/traits/collect.rs

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

0 commit comments

Comments
 (0)