Coverage Report

Created: 2025-09-04 06:37

/rust/registry/src/index.crates.io-6f17d22bba15001f/itertools-0.11.0/src/sources.rs
Line
Count
Source (jump to first uncovered line)
1
//! Iterators that are sources (produce elements from parameters,
2
//! not from another iterator).
3
#![allow(deprecated)]
4
5
use std::fmt;
6
use std::mem;
7
8
/// See [`repeat_call`](crate::repeat_call) for more information.
9
#[derive(Clone)]
10
#[deprecated(note="Use std repeat_with() instead", since="0.8.0")]
11
pub struct RepeatCall<F> {
12
    f: F,
13
}
14
15
impl<F> fmt::Debug for RepeatCall<F>
16
{
17
    debug_fmt_fields!(RepeatCall, );
18
}
19
20
/// An iterator source that produces elements indefinitely by calling
21
/// a given closure.
22
///
23
/// Iterator element type is the return type of the closure.
24
///
25
/// ```
26
/// use itertools::repeat_call;
27
/// use itertools::Itertools;
28
/// use std::collections::BinaryHeap;
29
///
30
/// let mut heap = BinaryHeap::from(vec![2, 5, 3, 7, 8]);
31
///
32
/// // extract each element in sorted order
33
/// for element in repeat_call(|| heap.pop()).while_some() {
34
///     print!("{}", element);
35
/// }
36
///
37
/// itertools::assert_equal(
38
///     repeat_call(|| 1).take(5),
39
///     vec![1, 1, 1, 1, 1]
40
/// );
41
/// ```
42
#[deprecated(note="Use std repeat_with() instead", since="0.8.0")]
43
0
pub fn repeat_call<F, A>(function: F) -> RepeatCall<F>
44
0
    where F: FnMut() -> A
45
0
{
46
0
    RepeatCall { f: function }
47
0
}
48
49
impl<A, F> Iterator for RepeatCall<F>
50
    where F: FnMut() -> A
51
{
52
    type Item = A;
53
54
    #[inline]
55
0
    fn next(&mut self) -> Option<Self::Item> {
56
0
        Some((self.f)())
57
0
    }
58
59
0
    fn size_hint(&self) -> (usize, Option<usize>) {
60
0
        (usize::max_value(), None)
61
0
    }
62
}
63
64
/// Creates a new unfold source with the specified closure as the "iterator
65
/// function" and an initial state to eventually pass to the closure
66
///
67
/// `unfold` is a general iterator builder: it has a mutable state value,
68
/// and a closure with access to the state that produces the next value.
69
///
70
/// This more or less equivalent to a regular struct with an [`Iterator`]
71
/// implementation, and is useful for one-off iterators.
72
///
73
/// ```
74
/// // an iterator that yields sequential Fibonacci numbers,
75
/// // and stops at the maximum representable value.
76
///
77
/// use itertools::unfold;
78
///
79
/// let mut fibonacci = unfold((1u32, 1u32), |(x1, x2)| {
80
///     // Attempt to get the next Fibonacci number
81
///     let next = x1.saturating_add(*x2);
82
///
83
///     // Shift left: ret <- x1 <- x2 <- next
84
///     let ret = *x1;
85
///     *x1 = *x2;
86
///     *x2 = next;
87
///
88
///     // If addition has saturated at the maximum, we are finished
89
///     if ret == *x1 && ret > 1 {
90
///         None
91
///     } else {
92
///         Some(ret)
93
///     }
94
/// });
95
///
96
/// itertools::assert_equal(fibonacci.by_ref().take(8),
97
///                         vec![1, 1, 2, 3, 5, 8, 13, 21]);
98
/// assert_eq!(fibonacci.last(), Some(2_971_215_073))
99
/// ```
100
0
pub fn unfold<A, St, F>(initial_state: St, f: F) -> Unfold<St, F>
101
0
    where F: FnMut(&mut St) -> Option<A>
102
0
{
103
0
    Unfold {
104
0
        f,
105
0
        state: initial_state,
106
0
    }
107
0
}
108
109
impl<St, F> fmt::Debug for Unfold<St, F>
110
    where St: fmt::Debug,
111
{
112
    debug_fmt_fields!(Unfold, state);
113
}
114
115
/// See [`unfold`](crate::unfold) for more information.
116
#[derive(Clone)]
117
#[must_use = "iterators are lazy and do nothing unless consumed"]
118
pub struct Unfold<St, F> {
119
    f: F,
120
    /// Internal state that will be passed to the closure on the next iteration
121
    pub state: St,
122
}
123
124
impl<A, St, F> Iterator for Unfold<St, F>
125
    where F: FnMut(&mut St) -> Option<A>
126
{
127
    type Item = A;
128
129
    #[inline]
130
0
    fn next(&mut self) -> Option<Self::Item> {
131
0
        (self.f)(&mut self.state)
132
0
    }
133
}
134
135
/// An iterator that infinitely applies function to value and yields results.
136
///
137
/// This `struct` is created by the [`iterate()`](crate::iterate) function.
138
/// See its documentation for more.
139
#[derive(Clone)]
140
#[must_use = "iterators are lazy and do nothing unless consumed"]
141
pub struct Iterate<St, F> {
142
    state: St,
143
    f: F,
144
}
145
146
impl<St, F> fmt::Debug for Iterate<St, F>
147
    where St: fmt::Debug,
148
{
149
    debug_fmt_fields!(Iterate, state);
150
}
151
152
impl<St, F> Iterator for Iterate<St, F>
153
    where F: FnMut(&St) -> St
154
{
155
    type Item = St;
156
157
    #[inline]
158
0
    fn next(&mut self) -> Option<Self::Item> {
159
0
        let next_state = (self.f)(&self.state);
160
0
        Some(mem::replace(&mut self.state, next_state))
161
0
    }
162
163
    #[inline]
164
0
    fn size_hint(&self) -> (usize, Option<usize>) {
165
0
        (usize::max_value(), None)
166
0
    }
167
}
168
169
/// Creates a new iterator that infinitely applies function to value and yields results.
170
///
171
/// ```
172
/// use itertools::iterate;
173
///
174
/// itertools::assert_equal(iterate(1, |&i| i * 3).take(5), vec![1, 3, 9, 27, 81]);
175
/// ```
176
0
pub fn iterate<St, F>(initial_value: St, f: F) -> Iterate<St, F>
177
0
    where F: FnMut(&St) -> St
178
0
{
179
0
    Iterate {
180
0
        state: initial_value,
181
0
        f,
182
0
    }
183
0
}