1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use duration::FloatDuration;
use std::iter;
#[derive(Debug, Clone)]
pub struct Subdivide {
start: FloatDuration,
step_size: FloatDuration,
len: usize,
index: usize,
}
impl Subdivide {
fn new(start: FloatDuration, end: FloatDuration, steps: usize) -> Subdivide {
assert!(steps >= 2, "subdivide requires at least two steps");
let step_size = (end - start) / (steps - 1) as f64;
Subdivide {
start: start,
step_size: step_size,
len: steps,
index: 0,
}
}
pub fn step_size(&self) -> FloatDuration {
self.step_size
}
}
impl Iterator for Subdivide {
type Item = FloatDuration;
#[inline]
fn next(&mut self) -> Option<FloatDuration> {
if self.index >= self.len {
None
} else {
let index = self.index;
self.index += 1;
Some(self.start + self.step_size * (index as f64))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let left = self.len - self.index;
(left, Some(left))
}
}
impl DoubleEndedIterator for Subdivide {
fn next_back(&mut self) -> Option<FloatDuration> {
if self.index >= self.len {
None
} else {
self.len -= 1;
let index = self.len;
Some(self.start + self.step_size * (index as f64))
}
}
}
impl ExactSizeIterator for Subdivide {}
pub fn subdivide(begin: FloatDuration, end: FloatDuration, steps: usize) -> Subdivide {
Subdivide::new(begin, end, steps)
}
pub fn subdivide_with_step(begin: FloatDuration,
end: FloatDuration,
steps: usize)
-> iter::Zip<Subdivide, iter::Repeat<FloatDuration>> {
let sub = subdivide(begin, end, steps);
let step_size = sub.step_size();
sub.zip(iter::repeat(step_size))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_subdivide() {
let s = subdivide(FloatDuration::zero(), FloatDuration::minutes(1.0), 3);
let s_rev = s.clone().rev();
assert_eq!(s.collect::<Vec<_>>(),
vec![FloatDuration::zero(),
FloatDuration::seconds(30.0),
FloatDuration::minutes(1.0)]);
assert_eq!(s_rev.collect::<Vec<_>>(),
vec![FloatDuration::minutes(1.0),
FloatDuration::seconds(30.0),
FloatDuration::zero()]);
assert_eq!(subdivide(FloatDuration::zero(), FloatDuration::zero(), 3).collect::<Vec<_>>(),
vec![FloatDuration::zero(),
FloatDuration::zero(),
FloatDuration::zero()]);
}
#[should_panic]
#[test]
fn test_subdivide_panic() {
subdivide(FloatDuration::zero(), FloatDuration::minutes(1.0), 1);
}
}