Odd sawtooth function
|
/ | / /
/ |/ /
--/----/----/--
/ /| /
/ / | /
|
Limit x to the half-open interval [-r, r).
pub fn wrap(x: anytype, r: anytype) @TypeOf(x)
pub fn wrap(x: anytype, r: anytype) @TypeOf(x) {
const info_x = @typeInfo(@TypeOf(x));
const info_r = @typeInfo(@TypeOf(r));
if (info_x == .int and info_x.int.signedness != .signed) {
@compileError("x must be floating point, comptime integer, or signed integer.");
}
switch (info_r) {
.int => {
// in the rare usecase of r not being comptime_int or float,
// take the penalty of having an intermediary type conversion,
// otherwise the alternative is to unwind iteratively to avoid overflow
const R = @Int(.signed, info_r.int.bits + 1);
const radius: if (info_r.int.signedness == .signed) @TypeOf(r) else R = r;
return @intCast(@mod(x - radius, 2 * @as(R, r)) - r); // provably impossible to overflow
},
else => {
return @mod(x - r, 2 * r) - r;
},
}
}