Skip to content

Instantly share code, notes, and snippets.

@nodefish
Created September 21, 2018 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nodefish/cfdfcef54e4e10c4151f60e3948b1a2b to your computer and use it in GitHub Desktop.
Save nodefish/cfdfcef54e4e10c4151f60e3948b1a2b to your computer and use it in GitHub Desktop.
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
fn abs(comptime x: comptime_int) comptime_int {
return if (x < 0) -x else x;
}
pub fn range(comptime inclusive: bool, comptime a: comptime_int, comptime b: comptime_int, comptime step: comptime_int) [@divTrunc(abs(b - a), step) + if (inclusive) 1 else 0](if (a < 0) isize else usize) {
comptime assert(a < b);
comptime assert(a + step <= b);
comptime var res: [@divTrunc(abs(b - a), step) + if (inclusive) 1 else 0](if (a < 0) isize else usize) = undefined;
comptime var idx = 0;
while (idx < res.len) {
res[idx] = a + step * idx;
idx += 1;
}
return res;
}
test "static ranges" {
warn("\n");
for (comptime range(false, 10000, 60000, 10000)) |val| {
warn("{}, ", val);
}
warn("\n");
for (comptime range(false, -1, 7, 2)) |val| {
warn("{}, ", val);
}
warn("\n");
for (comptime range(false, -120, 77, 80)) |val| {
warn("{}, ", val);
}
warn("\n");
for (comptime range(false, -9, 13, 1)) |val| {
warn("{}, ", val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment