5 use super::{FusedIterator, TrustedLen};
7 /// An iterator that repeats an element endlessly.
9 /// This `struct` is created by the [`repeat`] function. See its documentation for more.
11 /// [`repeat`]: fn.repeat.html
12 #[derive(Clone, Debug)]
13 #[stable(feature = "rust1", since = "1.0.0")]
14 pub struct Repeat<A> {
18 #[stable(feature = "rust1", since = "1.0.0")]
19 impl<A: Clone> Iterator for Repeat<A> {
23 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
25 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
28 #[stable(feature = "rust1", since = "1.0.0")]
29 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
31 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
34 #[stable(feature = "fused", since = "1.26.0")]
35 impl<A: Clone> FusedIterator for Repeat<A> {}
37 #[unstable(feature = "trusted_len", issue = "37572")]
38 unsafe impl<A: Clone> TrustedLen for Repeat<A> {}
40 /// Creates a new iterator that endlessly repeats a single element.
42 /// The `repeat()` function repeats a single value over and over and over and
43 /// over and over and đ.
45 /// Infinite iterators like `repeat()` are often used with adapters like
46 /// [`take`], in order to make them finite.
48 /// [`take`]: trait.Iterator.html#method.take
50 /// If the element type of the iterator you need does not implement `Clone`,
51 /// or if you do not want to keep the repeated element in memory, you can
52 /// instead use the [`repeat_with`] function.
54 /// [`repeat_with`]: fn.repeat_with.html
63 /// // the number four 4ever:
64 /// let mut fours = iter::repeat(4);
66 /// assert_eq!(Some(4), fours.next());
67 /// assert_eq!(Some(4), fours.next());
68 /// assert_eq!(Some(4), fours.next());
69 /// assert_eq!(Some(4), fours.next());
70 /// assert_eq!(Some(4), fours.next());
72 /// // yup, still four
73 /// assert_eq!(Some(4), fours.next());
76 /// Going finite with [`take`]:
81 /// // that last example was too many fours. Let's only have four fours.
82 /// let mut four_fours = iter::repeat(4).take(4);
84 /// assert_eq!(Some(4), four_fours.next());
85 /// assert_eq!(Some(4), four_fours.next());
86 /// assert_eq!(Some(4), four_fours.next());
87 /// assert_eq!(Some(4), four_fours.next());
89 /// // ... and now we're done
90 /// assert_eq!(None, four_fours.next());
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
98 /// An iterator that repeats elements of type `A` endlessly by
99 /// applying the provided closure `F: FnMut() -> A`.
101 /// This `struct` is created by the [`repeat_with`] function.
102 /// See its documentation for more.
104 /// [`repeat_with`]: fn.repeat_with.html
105 #[derive(Copy, Clone, Debug)]
106 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
107 pub struct RepeatWith<F> {
111 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
112 impl<A, F: FnMut() -> A> Iterator for RepeatWith<F> {
116 fn next(&mut self) -> Option<A> { Some((self.repeater)()) }
119 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
122 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
123 impl<A, F: FnMut() -> A> FusedIterator for RepeatWith<F> {}
125 #[unstable(feature = "trusted_len", issue = "37572")]
126 unsafe impl<A, F: FnMut() -> A> TrustedLen for RepeatWith<F> {}
128 /// Creates a new iterator that repeats elements of type `A` endlessly by
129 /// applying the provided closure, the repeater, `F: FnMut() -> A`.
131 /// The `repeat_with()` function calls the repeater over and over and over and
132 /// over and over and đ.
134 /// Infinite iterators like `repeat_with()` are often used with adapters like
135 /// [`take`], in order to make them finite.
137 /// [`take`]: trait.Iterator.html#method.take
139 /// If the element type of the iterator you need implements `Clone`, and
140 /// it is OK to keep the source element in memory, you should instead use
141 /// the [`repeat`] function.
143 /// [`repeat`]: fn.repeat.html
145 /// An iterator produced by `repeat_with()` is not a `DoubleEndedIterator`.
146 /// If you need `repeat_with()` to return a `DoubleEndedIterator`,
147 /// please open a GitHub issue explaining your use case.
156 /// // let's assume we have some value of a type that is not `Clone`
157 /// // or which don't want to have in memory just yet because it is expensive:
158 /// #[derive(PartialEq, Debug)]
159 /// struct Expensive;
161 /// // a particular value forever:
162 /// let mut things = iter::repeat_with(|| Expensive);
164 /// assert_eq!(Some(Expensive), things.next());
165 /// assert_eq!(Some(Expensive), things.next());
166 /// assert_eq!(Some(Expensive), things.next());
167 /// assert_eq!(Some(Expensive), things.next());
168 /// assert_eq!(Some(Expensive), things.next());
171 /// Using mutation and going finite:
176 /// // From the zeroth to the third power of two:
177 /// let mut curr = 1;
178 /// let mut pow2 = iter::repeat_with(|| { let tmp = curr; curr *= 2; tmp })
181 /// assert_eq!(Some(1), pow2.next());
182 /// assert_eq!(Some(2), pow2.next());
183 /// assert_eq!(Some(4), pow2.next());
184 /// assert_eq!(Some(8), pow2.next());
186 /// // ... and now we're done
187 /// assert_eq!(None, pow2.next());
190 #[stable(feature = "iterator_repeat_with", since = "1.28.0")]
191 pub fn repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> {
192 RepeatWith { repeater }
195 /// An iterator that yields nothing.
197 /// This `struct` is created by the [`empty`] function. See its documentation for more.
199 /// [`empty`]: fn.empty.html
200 #[stable(feature = "iter_empty", since = "1.2.0")]
201 pub struct Empty<T>(marker::PhantomData<T>);
203 #[stable(feature = "core_impl_debug", since = "1.9.0")]
204 impl<T> fmt::Debug for Empty<T> {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 #[stable(feature = "iter_empty", since = "1.2.0")]
211 impl<T> Iterator for Empty<T> {
214 fn next(&mut self) -> Option<T> {
218 fn size_hint(&self) -> (usize, Option<usize>){
223 #[stable(feature = "iter_empty", since = "1.2.0")]
224 impl<T> DoubleEndedIterator for Empty<T> {
225 fn next_back(&mut self) -> Option<T> {
230 #[stable(feature = "iter_empty", since = "1.2.0")]
231 impl<T> ExactSizeIterator for Empty<T> {
232 fn len(&self) -> usize {
237 #[unstable(feature = "trusted_len", issue = "37572")]
238 unsafe impl<T> TrustedLen for Empty<T> {}
240 #[stable(feature = "fused", since = "1.26.0")]
241 impl<T> FusedIterator for Empty<T> {}
243 // not #[derive] because that adds a Clone bound on T,
244 // which isn't necessary.
245 #[stable(feature = "iter_empty", since = "1.2.0")]
246 impl<T> Clone for Empty<T> {
247 fn clone(&self) -> Empty<T> {
248 Empty(marker::PhantomData)
252 // not #[derive] because that adds a Default bound on T,
253 // which isn't necessary.
254 #[stable(feature = "iter_empty", since = "1.2.0")]
255 impl<T> Default for Empty<T> {
256 fn default() -> Empty<T> {
257 Empty(marker::PhantomData)
261 /// Creates an iterator that yields nothing.
270 /// // this could have been an iterator over i32, but alas, it's just not.
271 /// let mut nope = iter::empty::<i32>();
273 /// assert_eq!(None, nope.next());
275 #[stable(feature = "iter_empty", since = "1.2.0")]
276 pub const fn empty<T>() -> Empty<T> {
277 Empty(marker::PhantomData)
280 /// An iterator that yields an element exactly once.
282 /// This `struct` is created by the [`once`] function. See its documentation for more.
284 /// [`once`]: fn.once.html
285 #[derive(Clone, Debug)]
286 #[stable(feature = "iter_once", since = "1.2.0")]
288 inner: ::option::IntoIter<T>
291 #[stable(feature = "iter_once", since = "1.2.0")]
292 impl<T> Iterator for Once<T> {
295 fn next(&mut self) -> Option<T> {
299 fn size_hint(&self) -> (usize, Option<usize>) {
300 self.inner.size_hint()
304 #[stable(feature = "iter_once", since = "1.2.0")]
305 impl<T> DoubleEndedIterator for Once<T> {
306 fn next_back(&mut self) -> Option<T> {
307 self.inner.next_back()
311 #[stable(feature = "iter_once", since = "1.2.0")]
312 impl<T> ExactSizeIterator for Once<T> {
313 fn len(&self) -> usize {
318 #[unstable(feature = "trusted_len", issue = "37572")]
319 unsafe impl<T> TrustedLen for Once<T> {}
321 #[stable(feature = "fused", since = "1.26.0")]
322 impl<T> FusedIterator for Once<T> {}
324 /// Creates an iterator that yields an element exactly once.
326 /// This is commonly used to adapt a single value into a [`chain`] of other
327 /// kinds of iteration. Maybe you have an iterator that covers almost
328 /// everything, but you need an extra special case. Maybe you have a function
329 /// which works on iterators, but you only need to process one value.
331 /// [`chain`]: trait.Iterator.html#method.chain
340 /// // one is the loneliest number
341 /// let mut one = iter::once(1);
343 /// assert_eq!(Some(1), one.next());
345 /// // just one, that's all we get
346 /// assert_eq!(None, one.next());
349 /// Chaining together with another iterator. Let's say that we want to iterate
350 /// over each file of the `.foo` directory, but also a configuration file,
356 /// use std::path::PathBuf;
358 /// let dirs = fs::read_dir(".foo").unwrap();
360 /// // we need to convert from an iterator of DirEntry-s to an iterator of
361 /// // PathBufs, so we use map
362 /// let dirs = dirs.map(|file| file.unwrap().path());
364 /// // now, our iterator just for our config file
365 /// let config = iter::once(PathBuf::from(".foorc"));
367 /// // chain the two iterators together into one big iterator
368 /// let files = dirs.chain(config);
370 /// // this will give us all of the files in .foo as well as .foorc
372 /// println!("{:?}", f);
375 #[stable(feature = "iter_once", since = "1.2.0")]
376 pub fn once<T>(value: T) -> Once<T> {
377 Once { inner: Some(value).into_iter() }
380 /// An iterator that repeats elements of type `A` endlessly by
381 /// applying the provided closure `F: FnMut() -> A`.
383 /// This `struct` is created by the [`once_with`] function.
384 /// See its documentation for more.
386 /// [`once_with`]: fn.once_with.html
387 #[derive(Copy, Clone, Debug)]
388 #[unstable(feature = "iter_once_with", issue = "57581")]
389 pub struct OnceWith<F> {
393 #[unstable(feature = "iter_once_with", issue = "57581")]
394 impl<A, F: FnOnce() -> A> Iterator for OnceWith<F> {
398 fn next(&mut self) -> Option<A> {
399 self.gen.take().map(|f| f())
403 fn size_hint(&self) -> (usize, Option<usize>) {
404 self.gen.iter().size_hint()
408 #[unstable(feature = "iter_once_with", issue = "57581")]
409 impl<A, F: FnOnce() -> A> DoubleEndedIterator for OnceWith<F> {
410 fn next_back(&mut self) -> Option<A> {
415 #[unstable(feature = "iter_once_with", issue = "57581")]
416 impl<A, F: FnOnce() -> A> ExactSizeIterator for OnceWith<F> {
417 fn len(&self) -> usize {
418 self.gen.iter().len()
422 #[unstable(feature = "iter_once_with", issue = "57581")]
423 impl<A, F: FnOnce() -> A> FusedIterator for OnceWith<F> {}
425 #[unstable(feature = "iter_once_with", issue = "57581")]
426 unsafe impl<A, F: FnOnce() -> A> TrustedLen for OnceWith<F> {}
428 /// Creates an iterator that lazily generates a value exactly once by invoking
429 /// the provided closure.
431 /// This is commonly used to adapt a single value generator into a [`chain`] of
432 /// other kinds of iteration. Maybe you have an iterator that covers almost
433 /// everything, but you need an extra special case. Maybe you have a function
434 /// which works on iterators, but you only need to process one value.
436 /// Unlike [`once`], this function will lazily generate the value on request.
438 /// [`once`]: fn.once.html
439 /// [`chain`]: trait.Iterator.html#method.chain
448 /// // one is the loneliest number
449 /// let mut one = iter::once_with(|| 1);
451 /// assert_eq!(Some(1), one.next());
453 /// // just one, that's all we get
454 /// assert_eq!(None, one.next());
457 /// Chaining together with another iterator. Let's say that we want to iterate
458 /// over each file of the `.foo` directory, but also a configuration file,
464 /// use std::path::PathBuf;
466 /// let dirs = fs::read_dir(".foo").unwrap();
468 /// // we need to convert from an iterator of DirEntry-s to an iterator of
469 /// // PathBufs, so we use map
470 /// let dirs = dirs.map(|file| file.unwrap().path());
472 /// // now, our iterator just for our config file
473 /// let config = iter::once_with(|| PathBuf::from(".foorc"));
475 /// // chain the two iterators together into one big iterator
476 /// let files = dirs.chain(config);
478 /// // this will give us all of the files in .foo as well as .foorc
480 /// println!("{:?}", f);
484 #[unstable(feature = "iter_once_with", issue = "57581")]
485 pub fn once_with<A, F: FnOnce() -> A>(gen: F) -> OnceWith<F> {
486 OnceWith { gen: Some(gen) }
489 /// Creates a new iterator where each iteration calls the provided closure
490 /// `F: FnMut(&mut St) -> Option<T>`.
492 /// This allows creating a custom iterator with any behavior
493 /// without using the more verbose syntax of creating a dedicated type
494 /// and implementing the `Iterator` trait for it.
496 /// In addition to its captures and environment,
497 /// the closure is given a mutable reference to some state
498 /// that is preserved across iterations.
499 /// That state starts as the given `initial_state` value.
501 /// Note that the `Unfold` iterator doesnât make assumptions about the behavior of the closure,
502 /// and therefore conservatively does not implement [`FusedIterator`],
503 /// or override [`Iterator::size_hint`] from its default `(0, None)`.
505 /// [`FusedIterator`]: trait.FusedIterator.html
506 /// [`Iterator::size_hint`]: trait.Iterator.html#method.size_hint
510 /// Letâs re-implement the counter iterator from [module-level documentation]:
512 /// [module-level documentation]: index.html
515 /// #![feature(iter_unfold)]
516 /// let counter = std::iter::unfold(0, |count| {
517 /// // Increment our count. This is why we started at zero.
520 /// // Check to see if we've finished counting or not.
527 /// assert_eq!(counter.collect::<Vec<_>>(), &[1, 2, 3, 4, 5]);
530 #[unstable(feature = "iter_unfold", issue = "55977")]
531 pub fn unfold<St, T, F>(initial_state: St, f: F) -> Unfold<St, F>
532 where F: FnMut(&mut St) -> Option<T>
535 state: initial_state,
540 /// An iterator where each iteration calls the provided closure `F: FnMut(&mut St) -> Option<T>`.
542 /// This `struct` is created by the [`unfold`] function.
543 /// See its documentation for more.
545 /// [`unfold`]: fn.unfold.html
547 #[unstable(feature = "iter_unfold", issue = "55977")]
548 pub struct Unfold<St, F> {
553 #[unstable(feature = "iter_unfold", issue = "55977")]
554 impl<St, T, F> Iterator for Unfold<St, F>
555 where F: FnMut(&mut St) -> Option<T>
560 fn next(&mut self) -> Option<Self::Item> {
561 (self.f)(&mut self.state)
565 #[unstable(feature = "iter_unfold", issue = "55977")]
566 impl<St: fmt::Debug, F> fmt::Debug for Unfold<St, F> {
567 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
568 f.debug_struct("Unfold")
569 .field("state", &self.state)
574 /// Creates a new iterator where each successive item is computed based on the preceding one.
576 /// The iterator starts with the given first item (if any)
577 /// and calls the given `FnMut(&T) -> Option<T>` closure to compute each itemâs successor.
580 /// #![feature(iter_unfold)]
581 /// use std::iter::successors;
583 /// let powers_of_10 = successors(Some(1_u16), |n| n.checked_mul(10));
584 /// assert_eq!(powers_of_10.collect::<Vec<_>>(), &[1, 10, 100, 1_000, 10_000]);
586 #[unstable(feature = "iter_unfold", issue = "55977")]
587 pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F>
588 where F: FnMut(&T) -> Option<T>
590 // If this function returned `impl Iterator<Item=T>`
591 // it could be based on `unfold` and not need a dedicated type.
592 // However having a named `Successors<T, F>` type allows it to be `Clone` when `T` and `F` are.
599 /// An new iterator where each successive item is computed based on the preceding one.
601 /// This `struct` is created by the [`successors`] function.
602 /// See its documentation for more.
604 /// [`successors`]: fn.successors.html
606 #[unstable(feature = "iter_unfold", issue = "55977")]
607 pub struct Successors<T, F> {
612 #[unstable(feature = "iter_unfold", issue = "55977")]
613 impl<T, F> Iterator for Successors<T, F>
614 where F: FnMut(&T) -> Option<T>
619 fn next(&mut self) -> Option<Self::Item> {
620 self.next.take().map(|item| {
621 self.next = (self.succ)(&item);
627 fn size_hint(&self) -> (usize, Option<usize>) {
628 if self.next.is_some() {
636 #[unstable(feature = "iter_unfold", issue = "55977")]
637 impl<T, F> FusedIterator for Successors<T, F>
638 where F: FnMut(&T) -> Option<T>
641 #[unstable(feature = "iter_unfold", issue = "55977")]
642 impl<T: fmt::Debug, F> fmt::Debug for Successors<T, F> {
643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
644 f.debug_struct("Successors")
645 .field("next", &self.next)