1
Fork 0
turbonss/lib/padding.zig

54 lines
1.8 KiB
Zig

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
// 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 until(comptime T: type, comptime nbits: u8, n: T) T {
return roundUp(T, nbits, n) - n;
}
// arrayList adds padding to an ArrayList(u8) for a given number of nbits
pub fn arrayList(arr: *ArrayList(u8), comptime nbits: u8) Allocator.Error!void {
const padding = until(u64, nbits, arr.items.len);
try arr.*.appendNTimes(0, padding);
}
const testing = std.testing;
test "padding" {
try testing.expectEqual(until(u12, 2, 0), 0);
try testing.expectEqual(until(u12, 2, 1), 3);
try testing.expectEqual(until(u12, 2, 2), 2);
try testing.expectEqual(until(u12, 2, 3), 1);
try testing.expectEqual(until(u12, 2, 4), 0);
try testing.expectEqual(until(u12, 2, 40), 0);
try testing.expectEqual(until(u12, 2, 41), 3);
try testing.expectEqual(until(u12, 2, 42), 2);
try testing.expectEqual(until(u12, 2, 43), 1);
try testing.expectEqual(until(u12, 2, 44), 0);
try testing.expectEqual(until(u12, 2, 4091), 1);
try testing.expectEqual(until(u12, 2, 4092), 0);
}
test "arrayList" {
var buf = try ArrayList(u8).initCapacity(testing.allocator, 16);
defer buf.deinit();
buf.appendAssumeCapacity(1);
try arrayList(&buf, 3);
try testing.expectEqual(buf.items.len, 8);
buf.appendAssumeCapacity(2);
try arrayList(&buf, 10);
try testing.expectEqual(buf.items.len, 1024);
}