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.
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.
15 use super::{FusedIterator, TrustedLen};
17 /// An iterator that repeats an element endlessly.
19 /// This `struct` is created by the [`repeat`] function. See its documentation for more.
21 /// [`repeat`]: fn.repeat.html
22 #[derive(Clone, Debug)]
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub struct Repeat<A> {
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<A: Clone> Iterator for Repeat<A> {
33 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
35 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
38 #[stable(feature = "rust1", since = "1.0.0")]
39 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
41 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
44 #[unstable(feature = "fused", issue = "35602")]
45 impl<A: Clone> FusedIterator for Repeat<A> {}
47 #[unstable(feature = "trusted_len", issue = "37572")]
48 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}
50 /// Creates a new iterator that endlessly repeats a single element.
52 /// The `repeat()` function repeats a single value over and over and over and
53 /// over and over and 🔁.
55 /// Infinite iterators like `repeat()` are often used with adapters like
56 /// [`take`], in order to make them finite.
58 /// [`take`]: trait.Iterator.html#method.take
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.
64 /// [`repeat_with`]: fn.repeat_with.html
73 /// // the number four 4ever:
74 /// let mut fours = iter::repeat(4);
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());
82 /// // yup, still four
83 /// assert_eq!(Some(4), fours.next());
86 /// Going finite with [`take`]:
91 /// // that last example was too many fours. Let's only have four fours.
92 /// let mut four_fours = iter::repeat(4).take(4);
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());
99 /// // ... and now we're done
100 /// assert_eq!(None, four_fours.next());
103 #[stable(feature = "rust1", since = "1.0.0")]
104 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
108 /// An iterator that repeats elements of type `A` endlessly by
109 /// applying the provided closure `F: FnMut() -> A`.
111 /// This `struct` is created by the [`repeat_with`] function.
112 /// See its documentation for more.
114 /// [`repeat_with`]: fn.repeat_with.html
115 #[unstable(feature = "iterator_repeat_with", issue = "0")]
116 pub struct RepeatWith<F> {
120 #[unstable(feature = "iterator_repeat_with", issue = "0")]
121 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
125 fn next(&mut self) -> Option<A> { Some((self.repeater)()) }
128 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
131 #[unstable(feature = "iterator_repeat_with", issue = "0")]
132 impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
134 fn next_back(&mut self) -> Option<A> { self.next() }
137 #[unstable(feature = "fused", issue = "35602")]
138 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
140 #[unstable(feature = "trusted_len", issue = "37572")]
141 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
143 /// Creates a new that repeats elements of type `A` endlessly by
144 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
146 /// The `repeat_with()` function calls the repeater over and over and over and
147 /// over and over and 🔁.
149 /// Infinite iterators like `repeat_with()` are often used with adapters like
150 /// [`take`], in order to make them finite.
152 /// [`take`]: trait.Iterator.html#method.take
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.
158 /// [`repeat`]: fn.repeat.html
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;
172 /// // a particular value forever:
173 /// let mut things = iter::repeat_with(|| Expensive);
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());
182 /// Using mutation and going finite:
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 })
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());
197 /// // ... and now we're done
198 /// assert_eq!(None, pow2.next());
201 #[unstable(feature = "iterator_repeat_with", issue = "0")]
202 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
203 RepeatWith { repeater }
206 /// An iterator that yields nothing.
208 /// This `struct` is created by the [`empty`] function. See its documentation for more.
210 /// [`empty`]: fn.empty.html
211 #[stable(feature = "iter_empty", since = "1.2.0")]
212 pub struct Empty<T>(marker::PhantomData<T>);
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 {
221 #[stable(feature = "iter_empty", since = "1.2.0")]
222 impl<T> Iterator for Empty<T> {
225 fn next(&mut self) -> Option<T> {
229 fn size_hint(&self) -> (usize, Option<usize>){
234 #[stable(feature = "iter_empty", since = "1.2.0")]
235 impl<T> DoubleEndedIterator for Empty<T> {
236 fn next_back(&mut self) -> Option<T> {
241 #[stable(feature = "iter_empty", since = "1.2.0")]
242 impl<T> ExactSizeIterator for Empty<T> {
243 fn len(&self) -> usize {
248 #[unstable(feature = "trusted_len", issue = "37572")]
249 unsafe impl<T> TrustedLen for Empty<T> {}
251 #[unstable(feature = "fused", issue = "35602")]
252 impl<T> FusedIterator for Empty<T> {}
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)
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)
272 /// Creates an iterator that yields nothing.
281 /// // this could have been an iterator over i32, but alas, it's just not.
282 /// let mut nope = iter::empty::<i32>();
284 /// assert_eq!(None, nope.next());
286 #[stable(feature = "iter_empty", since = "1.2.0")]
287 pub fn empty<T>() -> Empty<T> {
288 Empty(marker::PhantomData)
291 /// An iterator that yields an element exactly once.
293 /// This `struct` is created by the [`once`] function. See its documentation for more.
295 /// [`once`]: fn.once.html
296 #[derive(Clone, Debug)]
297 #[stable(feature = "iter_once", since = "1.2.0")]
299 inner: ::option::IntoIter<T>
302 #[stable(feature = "iter_once", since = "1.2.0")]
303 impl<T> Iterator for Once<T> {
306 fn next(&mut self) -> Option<T> {
310 fn size_hint(&self) -> (usize, Option<usize>) {
311 self.inner.size_hint()
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()
322 #[stable(feature = "iter_once", since = "1.2.0")]
323 impl<T> ExactSizeIterator for Once<T> {
324 fn len(&self) -> usize {
329 #[unstable(feature = "trusted_len", issue = "37572")]
330 unsafe impl<T> TrustedLen for Once<T> {}
332 #[unstable(feature = "fused", issue = "35602")]
333 impl<T> FusedIterator for Once<T> {}
335 /// Creates an iterator that yields an element exactly once.
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.
342 /// [`chain`]: trait.Iterator.html#method.chain
351 /// // one is the loneliest number
352 /// let mut one = iter::once(1);
354 /// assert_eq!(Some(1), one.next());
356 /// // just one, that's all we get
357 /// assert_eq!(None, one.next());
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,
367 /// use std::path::PathBuf;
369 /// let dirs = fs::read_dir(".foo").unwrap();
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());
375 /// // now, our iterator just for our config file
376 /// let config = iter::once(PathBuf::from(".foorc"));
378 /// // chain the two iterators together into one big iterator
379 /// let files = dirs.chain(config);
381 /// // this will give us all of the files in .foo as well as .foorc
383 /// println!("{:?}", f);
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() }