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
use core::ops::{Range, RangeInclusive};
pub trait AsRangeArg {
fn start(&self) -> usize;
fn end(&self) -> usize;
}
impl AsRangeArg for Range<usize> {
fn start(&self) -> usize {
self.start
}
fn end(&self) -> usize {
self.end
}
}
impl AsRangeArg for RangeInclusive<usize> {
fn start(&self) -> usize {
*self.start()
}
fn end(&self) -> usize {
*self.end() + 1
}
}
impl AsRangeArg for usize {
fn start(&self) -> usize {
0
}
fn end(&self) -> usize {
*self
}
}
impl AsRangeArg for (usize, usize) {
fn start(&self) -> usize {
self.0
}
fn end(&self) -> usize {
self.1
}
}
pub fn range<R: AsRangeArg>(range: R) -> Count {
Count(range.start(), range.end())
}
#[derive(Debug, Clone, Copy)]
pub struct Count(pub(super) usize, pub(super) usize);
#[derive(Debug)]
pub struct CountIntoIter {
epoch: usize,
idx: usize,
end: usize,
}
impl Iterator for CountIntoIter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
#[cfg(not(feature = "no-std"))]
crate::set_count(self.idx);
if self.epoch >= self.end {
return None;
}
let epoch = Some(self.epoch);
self.epoch += 1;
epoch
}
}
impl IntoIterator for Count {
type Item = usize;
type IntoIter = CountIntoIter;
fn into_iter(self) -> Self::IntoIter {
CountIntoIter {
epoch: self.0,
#[cfg(not(feature = "no-std"))]
idx: crate::get_count(),
#[cfg(feature = "no-std")]
idx: 0,
end: self.1,
}
}
}
#[cfg(test)]
mod tests {
use crate::{range, Count, CountIntoIter};
fn count_iter(iter: &mut CountIntoIter) {
iter.next();
assert_eq!(iter.epoch, 1);
assert_eq!(iter.idx, 0);
assert_eq!(iter.end, 10);
iter.next();
assert_eq!(iter.epoch, 2);
assert_eq!(iter.idx, 0);
assert_eq!(iter.end, 10);
}
#[test]
fn test_count_into_iter() {
let mut iter = CountIntoIter {
epoch: 0,
idx: 0,
end: 10,
};
count_iter(&mut iter);
}
#[test]
fn test_count() {
let count: Count = Count(0, 10);
count_iter(&mut count.into_iter());
}
#[test]
fn test_range_inclusive() {
let count: Count = range(0..=9);
count_iter(&mut count.into_iter());
for (idx, other) in count.into_iter().zip(0..=9) {
assert_eq!(idx, other)
}
}
}