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 #[derive(Copy, Clone, Debug)]
116 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
117 pub struct RepeatWith<F> {
121 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
122 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
126 fn next(&mut self) -> Option<A> { Some((self.repeater)()) }
129 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
132 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
133 impl<A, F: FnMut() -> A> DoubleEndedIterator for RepeatWith<F> {
135 fn next_back(&mut self) -> Option<A> { self.next() }
138 #[unstable(feature = "fused", issue = "35602")]
139 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
141 #[unstable(feature = "trusted_len", issue = "37572")]
142 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
144 /// Creates a new iterator that repeats elements of type `A` endlessly by
145 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
147 /// The `repeat_with()` function calls the repeater over and over and over and
148 /// over and over and 🔁.
150 /// Infinite iterators like `repeat_with()` are often used with adapters like
151 /// [`take`], in order to make them finite.
153 /// [`take`]: trait.Iterator.html#method.take
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.
159 /// [`repeat`]: fn.repeat.html
161 /// An iterator produced by `repeat_with()` is a `DoubleEndedIterator`.
162 /// It is important to not 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<_>>()`.
172 /// #![feature(iterator_repeat_with)]
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;
181 /// // a particular value forever:
182 /// let mut things = iter::repeat_with(|| Expensive);
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());
191 /// Using mutation and going finite:
194 /// #![feature(iterator_repeat_with)]
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 })
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());
208 /// // ... and now we're done
209 /// assert_eq!(None, pow2.next());
212 #[unstable(feature = "iterator_repeat_with", issue = "48169")]
213 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
214 RepeatWith { repeater }
217 /// An iterator that yields nothing.
219 /// This `struct` is created by the [`empty`] function. See its documentation for more.
221 /// [`empty`]: fn.empty.html
222 #[stable(feature = "iter_empty", since = "1.2.0")]
223 pub struct Empty<T>(marker::PhantomData<T>);
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 {
232 #[stable(feature = "iter_empty", since = "1.2.0")]
233 impl<T> Iterator for Empty<T> {
236 fn next(&mut self) -> Option<T> {
240 fn size_hint(&self) -> (usize, Option<usize>){
245 #[stable(feature = "iter_empty", since = "1.2.0")]
246 impl<T> DoubleEndedIterator for Empty<T> {
247 fn next_back(&mut self) -> Option<T> {
252 #[stable(feature = "iter_empty", since = "1.2.0")]
253 impl<T> ExactSizeIterator for Empty<T> {
254 fn len(&self) -> usize {
259 #[unstable(feature = "trusted_len", issue = "37572")]
260 unsafe impl<T> TrustedLen for Empty<T> {}
262 #[unstable(feature = "fused", issue = "35602")]
263 impl<T> FusedIterator for Empty<T> {}
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)
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)
283 /// Creates an iterator that yields nothing.
292 /// // this could have been an iterator over i32, but alas, it's just not.
293 /// let mut nope = iter::empty::<i32>();
295 /// assert_eq!(None, nope.next());
297 #[stable(feature = "iter_empty", since = "1.2.0")]
298 pub fn empty<T>() -> Empty<T> {
299 Empty(marker::PhantomData)
302 /// An iterator that yields an element exactly once.
304 /// This `struct` is created by the [`once`] function. See its documentation for more.
306 /// [`once`]: fn.once.html
307 #[derive(Clone, Debug)]
308 #[stable(feature = "iter_once", since = "1.2.0")]
310 inner: ::option::IntoIter<T>
313 #[stable(feature = "iter_once", since = "1.2.0")]
314 impl<T> Iterator for Once<T> {
317 fn next(&mut self) -> Option<T> {
321 fn size_hint(&self) -> (usize, Option<usize>) {
322 self.inner.size_hint()
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()
333 #[stable(feature = "iter_once", since = "1.2.0")]
334 impl<T> ExactSizeIterator for Once<T> {
335 fn len(&self) -> usize {
340 #[unstable(feature = "trusted_len", issue = "37572")]
341 unsafe impl<T> TrustedLen for Once<T> {}
343 #[unstable(feature = "fused", issue = "35602")]
344 impl<T> FusedIterator for Once<T> {}
346 /// Creates an iterator that yields an element exactly once.
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.
353 /// [`chain`]: trait.Iterator.html#method.chain
362 /// // one is the loneliest number
363 /// let mut one = iter::once(1);
365 /// assert_eq!(Some(1), one.next());
367 /// // just one, that's all we get
368 /// assert_eq!(None, one.next());
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,
378 /// use std::path::PathBuf;
380 /// let dirs = fs::read_dir(".foo").unwrap();
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());
386 /// // now, our iterator just for our config file
387 /// let config = iter::once(PathBuf::from(".foorc"));
389 /// // chain the two iterators together into one big iterator
390 /// let files = dirs.chain(config);
392 /// // this will give us all of the files in .foo as well as .foorc
394 /// println!("{:?}", f);
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() }