1
Fork 0
turbonss/src/padding.zig

33 lines
1.3 KiB
Zig

const std = @import("std");
const assert = std.debug.assert;
// rounds up an int to the nearest factor of nbits.
pub fn roundUp(comptime T: type, comptime nbits: u8, n: T) T {
comptime assert(nbits < @bitSizeOf(T));
const factor = comptime (1 << nbits) - 1;
return ((n + factor) & ~@as(T, factor));
}
// rounds up an integer to the nearest factor of nbits and returns the
// difference (padding)
pub fn roundUpPadding(comptime T: type, comptime nbits: u8, n: T) T {
return roundUp(T, nbits, n) - n;
}
const testing = std.testing;
test "padding" {
try testing.expectEqual(roundUpPadding(u12, 2, 0), 0);
try testing.expectEqual(roundUpPadding(u12, 2, 1), 3);
try testing.expectEqual(roundUpPadding(u12, 2, 2), 2);
try testing.expectEqual(roundUpPadding(u12, 2, 3), 1);
try testing.expectEqual(roundUpPadding(u12, 2, 4), 0);
try testing.expectEqual(roundUpPadding(u12, 2, 40), 0);
try testing.expectEqual(roundUpPadding(u12, 2, 41), 3);
try testing.expectEqual(roundUpPadding(u12, 2, 42), 2);
try testing.expectEqual(roundUpPadding(u12, 2, 43), 1);
try testing.expectEqual(roundUpPadding(u12, 2, 44), 0);
try testing.expectEqual(roundUpPadding(u12, 2, 4091), 1);
try testing.expectEqual(roundUpPadding(u12, 2, 4092), 0);
}