1
Fork 0
turbonss/src/padding.zig

33 lines
1.3 KiB
Zig
Raw Normal View History

2022-02-19 18:18:14 +02:00
const std = @import("std");
2022-02-19 22:12:49 +02:00
const assert = std.debug.assert;
2022-02-19 18:18:14 +02:00
2022-02-20 13:17:05 +02:00
// rounds up an int to the nearest factor of nbits.
2022-02-19 21:23:33 +02:00
pub fn roundUp(comptime T: type, comptime nbits: u8, n: T) T {
2022-02-19 22:12:49 +02:00
comptime assert(nbits < @bitSizeOf(T));
2022-02-19 21:23:33 +02:00
const factor = comptime (1 << nbits) - 1;
return ((n + factor) & ~@as(T, factor));
2022-02-19 18:18:14 +02:00
}
2022-02-20 13:17:05 +02:00
// 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;
}
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
}