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
#![no_std]
#![feature(step_trait)]
use core::iter::Step;
use core::ops::{
Bound::{Excluded, Included, Unbounded},
RangeBounds,
};
pub struct IncBy<T: Copy + Default + Step, const STEP: usize> {
start: T,
end: T,
}
pub struct DecBy<T: Copy + Default + Step, const STEP: usize> {
start: T,
end: T,
}
impl<T: Copy + Default + Step, const STEP: usize> IncBy<T, STEP> {
#[inline(always)]
fn new<R: RangeBounds<T>>(bounds: R) -> IncBy<T, STEP> {
let start = match bounds.start_bound() {
Included(&idx) => idx,
Excluded(&idx) => idx,
Unbounded => Default::default(),
};
let end = match bounds.end_bound() {
Included(&idx) => Step::forward(idx, STEP),
Excluded(&idx) => Step::forward(idx, STEP - 1),
Unbounded => Default::default(),
};
IncBy { start, end }
}
}
impl<T: Copy + Default + Step, const STEP: usize> DecBy<T, STEP> {
#[inline(always)]
fn new<R: RangeBounds<T>>(bounds: R) -> DecBy<T, STEP> {
let start = match bounds.end_bound() {
Included(&idx) => idx,
Excluded(&idx) => Step::forward(idx, 1),
Unbounded => Step::forward(Default::default(), 1),
};
let end = match bounds.start_bound() {
Included(&idx) => Step::forward(idx, STEP),
Excluded(&idx) => Step::forward(idx, STEP + 1),
Unbounded => Default::default(),
};
DecBy { start, end }
}
}
impl<T: Copy + Default + Step, const STEP: usize> Iterator for IncBy<T, STEP> {
type Item = T;
#[inline(always)]
fn next(&mut self) -> Option<T> {
if self.start <= Step::backward(self.end, STEP) {
let res = Some(self.start);
self.start = Step::forward(self.start, STEP);
res
} else {
None
}
}
}
impl<T: Copy + Default + Step, const STEP: usize> Iterator for DecBy<T, STEP> {
type Item = T;
#[inline(always)]
fn next(&mut self) -> Option<T> {
if Step::forward(self.start, STEP) <= self.end {
self.end = Step::backward(self.end, STEP);
Some(self.end)
} else {
None
}
}
}
pub trait IntoIncBy<T: Copy + Default + Step>: RangeBounds<T> {
fn inc_by<const STEP: usize>(self) -> IncBy<T, STEP>;
}
pub trait IntoDecBy<T: Copy + Default + Step>: RangeBounds<T> {
fn dec_by<const STEP: usize>(self) -> DecBy<T, STEP>;
}
impl<T: Copy + Default + Step, R: RangeBounds<T>> IntoIncBy<T> for R {
#[inline(always)]
fn inc_by<const STEP: usize>(self) -> IncBy<T, STEP> {
IncBy::<T, STEP>::new(self)
}
}
impl<T: Copy + Default + Step, R: RangeBounds<T>> IntoDecBy<T> for R {
#[inline(always)]
fn dec_by<const STEP: usize>(self) -> DecBy<T, STEP> {
DecBy::<T, STEP>::new(self)
}
}