]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/sources.rs
Merge branch 'refactor-select' of https://github.com/aravind-pg/rust into update...
[rust.git] / src / libcore / iter / sources.rs
1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use fmt;
12 use marker;
13 use usize;
14
15 use super::{FusedIterator, TrustedLen};
16
17 /// An iterator that repeats an element endlessly.
18 ///
19 /// This `struct` is created by the [`repeat`] function. See its documentation for more.
20 ///
21 /// [`repeat`]: fn.repeat.html
22 #[derive(Clone, Debug)]
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub struct Repeat<A> {
25     element: A
26 }
27
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<A: Clone> Iterator for Repeat<A> {
30     type Item = A;
31
32     #[inline]
33     fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
34     #[inline]
35     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
36 }
37
38 #[stable(feature = "rust1", since = "1.0.0")]
39 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
40     #[inline]
41     fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
42 }
43
44 #[stable(feature = "fused", since = "1.26.0")]
45 impl<A: Clone> FusedIterator for Repeat<A> {}
46
47 #[unstable(feature = "trusted_len", issue = "37572")]
48 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}
49
50 /// Creates a new iterator that endlessly repeats a single element.
51 ///
52 /// The `repeat()` function repeats a single value over and over and over and
53 /// over and over and 🔁.
54 ///
55 /// Infinite iterators like `repeat()` are often used with adapters like
56 /// [`take`], in order to make them finite.
57 ///
58 /// [`take`]: trait.Iterator.html#method.take
59 ///
60 /// If the element type of the iterator you need does not implement `Clone`,
61 /// or if you do not want to keep the repeated element in memory, you can
62 /// instead use the [`repeat_with`] function.
63 ///
64 /// [`repeat_with`]: fn.repeat_with.html
65 ///
66 /// # Examples
67 ///
68 /// Basic usage:
69 ///
70 /// ```
71 /// use std::iter;
72 ///
73 /// // the number four 4ever:
74 /// let mut fours = iter::repeat(4);
75 ///
76 /// assert_eq!(Some(4), fours.next());
77 /// assert_eq!(Some(4), fours.next());
78 /// assert_eq!(Some(4), fours.next());
79 /// assert_eq!(Some(4), fours.next());
80 /// assert_eq!(Some(4), fours.next());
81 ///
82 /// // yup, still four
83 /// assert_eq!(Some(4), fours.next());
84 /// ```
85 ///
86 /// Going finite with [`take`]:
87 ///
88 /// ```
89 /// use std::iter;
90 ///
91 /// // that last example was too many fours. Let's only have four fours.
92 /// let mut four_fours = iter::repeat(4).take(4);
93 ///
94 /// assert_eq!(Some(4), four_fours.next());
95 /// assert_eq!(Some(4), four_fours.next());
96 /// assert_eq!(Some(4), four_fours.next());
97 /// assert_eq!(Some(4), four_fours.next());
98 ///
99 /// // ... and now we're done
100 /// assert_eq!(None, four_fours.next());
101 /// ```
102 #[inline]
103 #[stable(feature = "rust1", since = "1.0.0")]
104 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
105     Repeat{element: elt}
106 }
107
108 /// An iterator that repeats elements of type `A` endlessly by
109 /// applying the provided closure `F: FnMut() -> A`.
110 ///
111 /// This `struct` is created by the [`repeat_with`] function.
112 /// See its documentation for more.
113 ///
114 /// [`repeat_with`]: fn.repeat_with.html
115 #[derive(Copy, Clone, Debug)]
116 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
117 pub struct RepeatWith<F> {
118     repeater: F
119 }
120
121 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
122 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
123     type Item = A;
124
125     #[inline]
126     fn next(&mut self) -> Option<A> { Some((self.repeater)()) }
127
128     #[inline]
129     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
130 }
131
132 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
133 impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
134     #[inline]
135     fn next_back(&mut self) -> Option<A> { self.next() }
136 }
137
138 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
139 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
140
141 #[unstable(feature = "trusted_len", issue = "37572")]
142 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
143
144 /// Creates a new iterator that repeats elements of type `A` endlessly by
145 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
146 ///
147 /// The `repeat_with()` function calls the repeater over and over and over and
148 /// over and over and 🔁.
149 ///
150 /// Infinite iterators like `repeat_with()` are often used with adapters like
151 /// [`take`], in order to make them finite.
152 ///
153 /// [`take`]: trait.Iterator.html#method.take
154 ///
155 /// If the element type of the iterator you need implements `Clone`, and
156 /// it is OK to keep the source element in memory, you should instead use
157 /// the [`repeat`] function.
158 ///
159 /// [`repeat`]: fn.repeat.html
160 ///
161 /// An iterator produced by `repeat_with()` is a `DoubleEndedIterator`.
162 /// It is important to note that reversing `repeat_with(f)` will produce
163 /// the exact same sequence as the non-reversed iterator. In other words,
164 /// `repeat_with(f).rev().collect::<Vec<_>>()` is equivalent to
165 /// `repeat_with(f).collect::<Vec<_>>()`.
166 ///
167 /// # Examples
168 ///
169 /// Basic usage:
170 ///
171 /// ```
172 /// #![feature(iterator_repeat_with)]
173 ///
174 /// use std::iter;
175 ///
176 /// // let's assume we have some value of a type that is not `Clone`
177 /// // or which don't want to have in memory just yet because it is expensive:
178 /// #[derive(PartialEq, Debug)]
179 /// struct Expensive;
180 ///
181 /// // a particular value forever:
182 /// let mut things = iter::repeat_with(|| Expensive);
183 ///
184 /// assert_eq!(Some(Expensive), things.next());
185 /// assert_eq!(Some(Expensive), things.next());
186 /// assert_eq!(Some(Expensive), things.next());
187 /// assert_eq!(Some(Expensive), things.next());
188 /// assert_eq!(Some(Expensive), things.next());
189 /// ```
190 ///
191 /// Using mutation and going finite:
192 ///
193 /// ```rust
194 /// #![feature(iterator_repeat_with)]
195 ///
196 /// use std::iter;
197 ///
198 /// // From the zeroth to the third power of two:
199 /// let mut curr = 1;
200 /// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
201 ///                     .take(4);
202 ///
203 /// assert_eq!(Some(1), pow2.next());
204 /// assert_eq!(Some(2), pow2.next());
205 /// assert_eq!(Some(4), pow2.next());
206 /// assert_eq!(Some(8), pow2.next());
207 ///
208 /// // ... and now we're done
209 /// assert_eq!(None, pow2.next());
210 /// ```
211 #[inline]
212 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
213 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
214     RepeatWith { repeater }
215 }
216
217 /// An iterator that yields nothing.
218 ///
219 /// This `struct` is created by the [`empty`] function. See its documentation for more.
220 ///
221 /// [`empty`]: fn.empty.html
222 #[stable(feature = "iter_empty", since = "1.2.0")]
223 pub struct Empty<T>(marker::PhantomData<T>);
224
225 #[stable(feature = "core_impl_debug", since = "1.9.0")]
226 impl<T> fmt::Debug for Empty<T> {
227     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
228         f.pad("Empty")
229     }
230 }
231
232 #[stable(feature = "iter_empty", since = "1.2.0")]
233 impl<T> Iterator for Empty<T> {
234     type Item = T;
235
236     fn next(&mut self) -> Option<T> {
237         None
238     }
239
240     fn size_hint(&self) -> (usize, Option<usize>){
241         (0, Some(0))
242     }
243 }
244
245 #[stable(feature = "iter_empty", since = "1.2.0")]
246 impl<T> DoubleEndedIterator for Empty<T> {
247     fn next_back(&mut self) -> Option<T> {
248         None
249     }
250 }
251
252 #[stable(feature = "iter_empty", since = "1.2.0")]
253 impl<T> ExactSizeIterator for Empty<T> {
254     fn len(&self) -> usize {
255         0
256     }
257 }
258
259 #[unstable(feature = "trusted_len", issue = "37572")]
260 unsafe impl<T> TrustedLen for Empty<T> {}
261
262 #[stable(feature = "fused", since = "1.26.0")]
263 impl<T> FusedIterator for Empty<T> {}
264
265 // not #[derive] because that adds a Clone bound on T,
266 // which isn't necessary.
267 #[stable(feature = "iter_empty", since = "1.2.0")]
268 impl<T> Clone for Empty<T> {
269     fn clone(&self) -> Empty<T> {
270         Empty(marker::PhantomData)
271     }
272 }
273
274 // not #[derive] because that adds a Default bound on T,
275 // which isn't necessary.
276 #[stable(feature = "iter_empty", since = "1.2.0")]
277 impl<T> Default for Empty<T> {
278     fn default() -> Empty<T> {
279         Empty(marker::PhantomData)
280     }
281 }
282
283 /// Creates an iterator that yields nothing.
284 ///
285 /// # Examples
286 ///
287 /// Basic usage:
288 ///
289 /// ```
290 /// use std::iter;
291 ///
292 /// // this could have been an iterator over i32, but alas, it's just not.
293 /// let mut nope = iter::empty::<i32>();
294 ///
295 /// assert_eq!(None, nope.next());
296 /// ```
297 #[stable(feature = "iter_empty", since = "1.2.0")]
298 pub fn empty<T>() -> Empty<T> {
299     Empty(marker::PhantomData)
300 }
301
302 /// An iterator that yields an element exactly once.
303 ///
304 /// This `struct` is created by the [`once`] function. See its documentation for more.
305 ///
306 /// [`once`]: fn.once.html
307 #[derive(Clone, Debug)]
308 #[stable(feature = "iter_once", since = "1.2.0")]
309 pub struct Once<T> {
310     inner: ::option::IntoIter<T>
311 }
312
313 #[stable(feature = "iter_once", since = "1.2.0")]
314 impl<T> Iterator for Once<T> {
315     type Item = T;
316
317     fn next(&mut self) -> Option<T> {
318         self.inner.next()
319     }
320
321     fn size_hint(&self) -> (usize, Option<usize>) {
322         self.inner.size_hint()
323     }
324 }
325
326 #[stable(feature = "iter_once", since = "1.2.0")]
327 impl<T> DoubleEndedIterator for Once<T> {
328     fn next_back(&mut self) -> Option<T> {
329         self.inner.next_back()
330     }
331 }
332
333 #[stable(feature = "iter_once", since = "1.2.0")]
334 impl<T> ExactSizeIterator for Once<T> {
335     fn len(&self) -> usize {
336         self.inner.len()
337     }
338 }
339
340 #[unstable(feature = "trusted_len", issue = "37572")]
341 unsafe impl<T> TrustedLen for Once<T> {}
342
343 #[stable(feature = "fused", since = "1.26.0")]
344 impl<T> FusedIterator for Once<T> {}
345
346 /// Creates an iterator that yields an element exactly once.
347 ///
348 /// This is commonly used to adapt a single value into a [`chain`] of other
349 /// kinds of iteration. Maybe you have an iterator that covers almost
350 /// everything, but you need an extra special case. Maybe you have a function
351 /// which works on iterators, but you only need to process one value.
352 ///
353 /// [`chain`]: trait.Iterator.html#method.chain
354 ///
355 /// # Examples
356 ///
357 /// Basic usage:
358 ///
359 /// ```
360 /// use std::iter;
361 ///
362 /// // one is the loneliest number
363 /// let mut one = iter::once(1);
364 ///
365 /// assert_eq!(Some(1), one.next());
366 ///
367 /// // just one, that's all we get
368 /// assert_eq!(None, one.next());
369 /// ```
370 ///
371 /// Chaining together with another iterator. Let's say that we want to iterate
372 /// over each file of the `.foo` directory, but also a configuration file,
373 /// `.foorc`:
374 ///
375 /// ```no_run
376 /// use std::iter;
377 /// use std::fs;
378 /// use std::path::PathBuf;
379 ///
380 /// let dirs = fs::read_dir(".foo").unwrap();
381 ///
382 /// // we need to convert from an iterator of DirEntry-s to an iterator of
383 /// // PathBufs, so we use map
384 /// let dirs = dirs.map(|file| file.unwrap().path());
385 ///
386 /// // now, our iterator just for our config file
387 /// let config = iter::once(PathBuf::from(".foorc"));
388 ///
389 /// // chain the two iterators together into one big iterator
390 /// let files = dirs.chain(config);
391 ///
392 /// // this will give us all of the files in .foo as well as .foorc
393 /// for f in files {
394 ///     println!("{:?}", f);
395 /// }
396 /// ```
397 #[stable(feature = "iter_once", since = "1.2.0")]
398 pub fn once<T>(value: T) -> Once<T> {
399     Once { inner: Some(value).into_iter() }
400 }