]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/sources.rs
980f3fc7443ace45bc39f6827abd13a74b5616a5
[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 #[unstable(feature = "fused", issue = "35602")]
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 #[unstable(feature = "iterator_repeat_with", issue = "0")]
116 pub struct RepeatWith<F> {
117     repeater: F
118 }
119
120 #[unstable(feature = "iterator_repeat_with", issue = "0")]
121 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
122     type Item = A;
123
124     #[inline]
125     fn next(&mut self) -> Option<A> { Some((self.repeater)()) }
126
127     #[inline]
128     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
129 }
130
131 #[unstable(feature = "iterator_repeat_with", issue = "0")]
132 impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
133     #[inline]
134     fn next_back(&mut self) -> Option<A> { self.next() }
135 }
136
137 #[unstable(feature = "fused", issue = "35602")]
138 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
139
140 #[unstable(feature = "trusted_len", issue = "37572")]
141 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
142
143 /// Creates a new that repeats elements of type `A` endlessly by
144 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
145 ///
146 /// The `repeat_with()` function calls the repeater over and over and over and
147 /// over and over and 🔁.
148 ///
149 /// Infinite iterators like `repeat_with()` are often used with adapters like
150 /// [`take`], in order to make them finite.
151 ///
152 /// [`take`]: trait.Iterator.html#method.take
153 ///
154 /// If the element type of the iterator you need implements `Clone`, and
155 /// it is OK to keep the source element in memory, you should instead use
156 /// the [`repeat`] function.
157 ///
158 /// [`repeat`]: fn.repeat.html
159 ///
160 /// # Examples
161 ///
162 /// Basic usage:
163 ///
164 /// ```
165 /// use std::iter;
166 ///
167 /// // let's assume we have some value of a type that is not `Clone`
168 /// // or which don't want to have in memory just yet because it is expensive:
169 /// #[derive(PartialEq, Debug)]
170 /// struct Expensive;
171 ///
172 /// // a particular value forever:
173 /// let mut things = iter::repeat_with(|| Expensive);
174 ///
175 /// assert_eq!(Some(Expensive), things.next());
176 /// assert_eq!(Some(Expensive), things.next());
177 /// assert_eq!(Some(Expensive), things.next());
178 /// assert_eq!(Some(Expensive), things.next());
179 /// assert_eq!(Some(Expensive), things.next());
180 /// ```
181 ///
182 /// Using mutation and going finite:
183 ///
184 /// ```rust
185 /// use std::iter;
186 ///
187 /// // From the zeroth to the third power of two:
188 /// let mut curr = 1;
189 /// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
190 ///                     .take(4);
191 ///
192 /// assert_eq!(Some(1), pow2.next());
193 /// assert_eq!(Some(2), pow2.next());
194 /// assert_eq!(Some(4), pow2.next());
195 /// assert_eq!(Some(8), pow2.next());
196 ///
197 /// // ... and now we're done
198 /// assert_eq!(None, pow2.next());
199 /// ```
200 #[inline]
201 #[unstable(feature = "iterator_repeat_with", issue = "0")]
202 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
203     RepeatWith { repeater }
204 }
205
206 /// An iterator that yields nothing.
207 ///
208 /// This `struct` is created by the [`empty`] function. See its documentation for more.
209 ///
210 /// [`empty`]: fn.empty.html
211 #[stable(feature = "iter_empty", since = "1.2.0")]
212 pub struct Empty<T>(marker::PhantomData<T>);
213
214 #[stable(feature = "core_impl_debug", since = "1.9.0")]
215 impl<T> fmt::Debug for Empty<T> {
216     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217         f.pad("Empty")
218     }
219 }
220
221 #[stable(feature = "iter_empty", since = "1.2.0")]
222 impl<T> Iterator for Empty<T> {
223     type Item = T;
224
225     fn next(&mut self) -> Option<T> {
226         None
227     }
228
229     fn size_hint(&self) -> (usize, Option<usize>){
230         (0, Some(0))
231     }
232 }
233
234 #[stable(feature = "iter_empty", since = "1.2.0")]
235 impl<T> DoubleEndedIterator for Empty<T> {
236     fn next_back(&mut self) -> Option<T> {
237         None
238     }
239 }
240
241 #[stable(feature = "iter_empty", since = "1.2.0")]
242 impl<T> ExactSizeIterator for Empty<T> {
243     fn len(&self) -> usize {
244         0
245     }
246 }
247
248 #[unstable(feature = "trusted_len", issue = "37572")]
249 unsafe impl<T> TrustedLen for Empty<T> {}
250
251 #[unstable(feature = "fused", issue = "35602")]
252 impl<T> FusedIterator for Empty<T> {}
253
254 // not #[derive] because that adds a Clone bound on T,
255 // which isn't necessary.
256 #[stable(feature = "iter_empty", since = "1.2.0")]
257 impl<T> Clone for Empty<T> {
258     fn clone(&self) -> Empty<T> {
259         Empty(marker::PhantomData)
260     }
261 }
262
263 // not #[derive] because that adds a Default bound on T,
264 // which isn't necessary.
265 #[stable(feature = "iter_empty", since = "1.2.0")]
266 impl<T> Default for Empty<T> {
267     fn default() -> Empty<T> {
268         Empty(marker::PhantomData)
269     }
270 }
271
272 /// Creates an iterator that yields nothing.
273 ///
274 /// # Examples
275 ///
276 /// Basic usage:
277 ///
278 /// ```
279 /// use std::iter;
280 ///
281 /// // this could have been an iterator over i32, but alas, it's just not.
282 /// let mut nope = iter::empty::<i32>();
283 ///
284 /// assert_eq!(None, nope.next());
285 /// ```
286 #[stable(feature = "iter_empty", since = "1.2.0")]
287 pub fn empty<T>() -> Empty<T> {
288     Empty(marker::PhantomData)
289 }
290
291 /// An iterator that yields an element exactly once.
292 ///
293 /// This `struct` is created by the [`once`] function. See its documentation for more.
294 ///
295 /// [`once`]: fn.once.html
296 #[derive(Clone, Debug)]
297 #[stable(feature = "iter_once", since = "1.2.0")]
298 pub struct Once<T> {
299     inner: ::option::IntoIter<T>
300 }
301
302 #[stable(feature = "iter_once", since = "1.2.0")]
303 impl<T> Iterator for Once<T> {
304     type Item = T;
305
306     fn next(&mut self) -> Option<T> {
307         self.inner.next()
308     }
309
310     fn size_hint(&self) -> (usize, Option<usize>) {
311         self.inner.size_hint()
312     }
313 }
314
315 #[stable(feature = "iter_once", since = "1.2.0")]
316 impl<T> DoubleEndedIterator for Once<T> {
317     fn next_back(&mut self) -> Option<T> {
318         self.inner.next_back()
319     }
320 }
321
322 #[stable(feature = "iter_once", since = "1.2.0")]
323 impl<T> ExactSizeIterator for Once<T> {
324     fn len(&self) -> usize {
325         self.inner.len()
326     }
327 }
328
329 #[unstable(feature = "trusted_len", issue = "37572")]
330 unsafe impl<T> TrustedLen for Once<T> {}
331
332 #[unstable(feature = "fused", issue = "35602")]
333 impl<T> FusedIterator for Once<T> {}
334
335 /// Creates an iterator that yields an element exactly once.
336 ///
337 /// This is commonly used to adapt a single value into a [`chain`] of other
338 /// kinds of iteration. Maybe you have an iterator that covers almost
339 /// everything, but you need an extra special case. Maybe you have a function
340 /// which works on iterators, but you only need to process one value.
341 ///
342 /// [`chain`]: trait.Iterator.html#method.chain
343 ///
344 /// # Examples
345 ///
346 /// Basic usage:
347 ///
348 /// ```
349 /// use std::iter;
350 ///
351 /// // one is the loneliest number
352 /// let mut one = iter::once(1);
353 ///
354 /// assert_eq!(Some(1), one.next());
355 ///
356 /// // just one, that's all we get
357 /// assert_eq!(None, one.next());
358 /// ```
359 ///
360 /// Chaining together with another iterator. Let's say that we want to iterate
361 /// over each file of the `.foo` directory, but also a configuration file,
362 /// `.foorc`:
363 ///
364 /// ```no_run
365 /// use std::iter;
366 /// use std::fs;
367 /// use std::path::PathBuf;
368 ///
369 /// let dirs = fs::read_dir(".foo").unwrap();
370 ///
371 /// // we need to convert from an iterator of DirEntry-s to an iterator of
372 /// // PathBufs, so we use map
373 /// let dirs = dirs.map(|file| file.unwrap().path());
374 ///
375 /// // now, our iterator just for our config file
376 /// let config = iter::once(PathBuf::from(".foorc"));
377 ///
378 /// // chain the two iterators together into one big iterator
379 /// let files = dirs.chain(config);
380 ///
381 /// // this will give us all of the files in .foo as well as .foorc
382 /// for f in files {
383 ///     println!("{:?}", f);
384 /// }
385 /// ```
386 #[stable(feature = "iter_once", since = "1.2.0")]
387 pub fn once<T>(value: T) -> Once<T> {
388     Once { inner: Some(value).into_iter() }
389 }