devela/code/util/cfor.rs
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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
// devela::code::util::cfor
//
// Original source code by Joachim EnggÄrd Nebel, licensed as MIT,
// https://crates.io/crates/const_for/0.1.4
//
// WAIT: [for-loops in constants](https://github.com/rust-lang/rust/issues/87575)
// IMPROVE: doesn't work in certain circumstances.
/// A for loop that is usable in *compile-time* contexts.
///
/// It aims to work exactly like a normal for loop over a standard exclusive range,
/// eg. `0..10` or `-5..5`. Unfortunately it doesn't support other types of ranges
/// like `..10` or `2..=10`. So generally just use it like a regular for loop.
///
/// `.rev()` and `.step_by(x)` are implemented via macros instead of the
/// non-const iter trait, and makes the loop behave as expected.
///
/// # Examples
/// ```
/// # use devela::cfor;
/// let mut a = 0;
/// cfor!(i in 0..5 => {
/// a += i
/// });
/// assert!(a == 10)
/// ```
///
/// This is equivalent to the following regular for loop, except it is usable in const context.
/// ```
/// let mut a = 0;
/// for i in 0..5 {
/// a += i
/// }
/// assert!(a == 10)
/// ```
///
/// ## Custom step size
/// A custom step size can be set:
/// ```
/// # use devela::cfor;
/// let mut v = Vec::new();
/// cfor!(i in (0..5).step_by(2) => {
/// v.push(i)
/// });
/// assert!(v == vec![0, 2, 4])
/// ```
/// The loop behaves as if the function was called on the range,
/// including requiring a usize, but it is implemented by a macro.
///
/// ## Reversed
/// Iteration can be reversed:
/// ```
/// # use devela::cfor;
/// let mut v = Vec::new();
/// cfor!(i in (0..5).rev() => {
/// v.push(i)
/// });
/// assert!(v == vec![4, 3, 2, 1, 0])
/// ```
/// The loop behaves as if the function was called on the range, but it is implemented by a macro.
///
/// ## Reversed and custom step size
/// It is possible to combine rev and step_by, but each can only be appended once.
/// So the following two examples are the only legal combinations.
/// ```
/// # use devela::cfor;
/// // Reverse, then change step size
/// let mut v = Vec::new();
/// cfor!(i in (0..10).rev().step_by(4) => {
/// v.push(i)
/// });
/// assert!(v == vec![9, 5, 1]);
///
/// // Change step size, then reverse
/// let mut v = Vec::new();
/// cfor!(i in (0..10).step_by(4).rev() => {
/// v.push(i)
/// });
/// assert!(v == vec![8, 4, 0])
/// ```
///
/// ## Notes
/// You can use mutable and wildcard variables as the loop variable, and they act as expected.
///
/// ```
/// // Mutable variable
/// # use devela::cfor;
/// let mut v = Vec::new();
/// cfor!(mut i in (0..4) => {
/// i *= 2;
/// v.push(i)
/// });
/// assert!(v == vec![0, 2, 4, 6]);
///
/// // Wildcard variable
/// let mut a = 0;
/// cfor!(_ in 0..5 =>
/// a += 1
/// );
/// assert!(a == 5)
/// ```
///
/// The body of the loop can be any statement. This means that the following is legal,
/// even though it is not in a regular for loop.
/// ```
/// # use devela::cfor;
/// let mut a = 0;
/// cfor!(_ in 0..5 => a += 1);
///
/// unsafe fn unsafe_function() {}
/// cfor!(_ in 0..5 => unsafe {
/// unsafe_function()
/// });
/// ```
#[macro_export]
#[cfg_attr(cargo_primary_package, doc(hidden))]
macro_rules! cfor {
($var:pat_param in ($range:expr).step_by($step:expr) => $body:stmt) => {
{
let _: usize = $step;
let mut __ite = $range.start;
let __end = $range.end;
let mut __is_first = true;
let __step = $step;
loop {
if !__is_first {
__ite += __step
}
__is_first = false;
let $var = __ite;
if __ite >= __end {
break
}
$body
}
}
};
($var:pat_param in ($range:expr).rev().step_by($step:expr) => $body:stmt) => {
{
let _: usize = $step;
let mut __ite = $range.end;
let __start = $range.start;
let mut __is_first = true;
let __step = $step;
loop {
if !__is_first {
if __step + __start >= __ite {
break
}
__ite -= __step
}
__is_first = false;
if __ite <= __start {
break
}
// cannot underflow as __ite > __start
let $var = __ite - 1;
$body
}
}
};
($var:pat_param in ($range:expr).rev() => $body:stmt) => {
cfor!($var in ($range).rev().step_by(1) => $body)
};
($var:pat_param in ($range:expr).step_by($step:expr).rev() => $body:stmt) => {
cfor!($var in ($range.start..$range.end - ($range.end - $range.start - 1) % $step)
.rev().step_by($step) => $body)
};
($var:pat_param in $range:expr => $body:stmt) => {
cfor!($var in ($range).step_by(1) => $body)
};
}
#[doc(inline)]
pub use cfor;
#[cfg(all(test, feature = "alloc"))]
mod tests {
use super::cfor;
use crate::{vec_ as vec, Vec};
macro_rules! validate_loop {
(@impl $($loop:tt)*) => {
let mut c_values_hit = Vec::new();
cfor!(i in $($loop)* => {
c_values_hit.push(i);
});
let mut r_values_hit = Vec::new();
for i in $($loop)* {
r_values_hit.push(i);
};
assert!(c_values_hit == r_values_hit);
};
($step: expr, $($loop:tt)*) => {
validate_loop!(@impl ($($loop)*).step_by(1));
validate_loop!(@impl ($($loop)*).step_by(1).rev());
validate_loop!(@impl ($($loop)*).rev().step_by(1));
};
($($loop:tt)*) => {
validate_loop!(@impl $($loop)*);
validate_loop!(@impl ($($loop)*).rev());
validate_loop!(1, $($loop)*);
validate_loop!(2, $($loop)*);
validate_loop!(3, $($loop)*);
validate_loop!(8, $($loop)*);
validate_loop!(15, $($loop)*);
validate_loop!(17, $($loop)*);
validate_loop!(45, $($loop)*);
validate_loop!(150, $($loop)*);
};
}
#[test]
#[allow(unused_parens, reason = "(0..10)")]
fn equivalent_to_regular_for() {
validate_loop!(-10..10);
validate_loop!(0..10);
validate_loop!(-10..10);
validate_loop!((0..10));
validate_loop!(50..10);
validate_loop!(-15..-12);
validate_loop!(-14..0);
validate_loop!(-100..-50);
validate_loop!(-14..80);
validate_loop!(1..80);
}
#[test]
fn capture_range_at_beginning() {
let mut a = 113;
cfor!(i in 0..a-100 => {
a += i;
});
let mut b = 113;
for i in 0..b - 100 {
b += i;
}
assert_eq!(a, b);
let mut a = 0;
let mut step = 1;
cfor!(_ in (0..10).step_by(step) => {
a += step;
step += 1;
});
let mut b = 0;
let mut step = 1;
for _ in (0..10).step_by(step) {
b += step;
step += 1;
}
assert_eq!(a, b);
}
#[test]
const fn available_in_const() {
let mut a = 0;
cfor!(_ in 0..25 => {
a += 1
});
cfor!(_ in (0..25).rev() => {
a += 1
});
cfor!(_ in (0..100).step_by(2) =>
a += 1
);
cfor!(mut i in (0..3) => {
i += 1;
a += i
});
cfor!(_ in (0..7).rev() => {
a += 1
});
assert!(a == 25 + 25 + 50 + 6 + 7);
}
#[test]
fn no_underflow() {
cfor!(_ in (0u64..1).rev() => {});
let mut iterations: u64 = 0;
cfor!(_ in (i8::MIN..0).rev() => iterations += 1);
assert_eq!(iterations, 128);
}
#[test]
fn signed_can_go_negative() {
let mut actual = Vec::new();
cfor!(i in (-10..11).rev().step_by(5) => actual.push(i));
assert_eq!(actual, vec![10, 5, 0, -5, -10]);
}
}