1
Fork 0
turbonss/src/padding.zig

31 lines
1.2 KiB
Zig
Raw Normal View History

2022-02-19 18:18:14 +02:00
const std = @import("std");
// rounds up a u12 to the nearest factor of 4 and returns the difference
// (padding)
2022-02-19 21:23:33 +02:00
pub fn roundUpPadding(comptime T: type, comptime nbits: u8, n: T) T {
return roundUp(T, nbits, n) - n;
2022-02-19 18:18:14 +02:00
}
// rounds up a u12 to the nearest factor of 4.
2022-02-19 21:23:33 +02:00
pub fn roundUp(comptime T: type, comptime nbits: u8, n: T) T {
const factor = comptime (1 << nbits) - 1;
return ((n + factor) & ~@as(T, factor));
2022-02-19 18:18:14 +02:00
}
const testing = std.testing;
test "padding" {
2022-02-19 21:23:33 +02:00
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);
2022-02-19 18:18:14 +02:00
}