1
Fork 0
turbonss/src/padding.zig

54 lines
1.8 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;
const Allocator = std.mem.Allocator;
2023-02-02 17:04:21 +02:00
const ArrayListAligned = std.ArrayListAligned;
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)
2022-03-20 09:42:51 +02:00
pub fn until(comptime T: type, comptime nbits: u8, n: T) T {
2022-02-20 13:17:05 +02:00
return roundUp(T, nbits, n) - n;
}
2023-02-02 17:04:21 +02:00
// arrayList adds padding to an ArrayListAligned(u8, 8) for a given number of nbits
pub fn arrayList(arr: *ArrayListAligned(u8, 8), comptime nbits: u8) Allocator.Error!void {
2022-03-20 09:42:51 +02:00
const padding = until(u64, nbits, arr.items.len);
try arr.*.appendNTimes(0, padding);
}
2022-02-19 18:18:14 +02:00
const testing = std.testing;
test "padding" {
2022-03-20 09:42:51 +02:00
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);
2022-02-19 18:18:14 +02:00
}
2022-07-12 12:59:47 +03:00
test "padding arrayList" {
2023-02-02 17:04:21 +02:00
var buf = try ArrayListAligned(u8, 8).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);
}