Skip to content

Instantly share code, notes, and snippets.

@HurricanKai
Created October 23, 2023 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HurricanKai/9296711e83a2a6ce75e27aece842f820 to your computer and use it in GitHub Desktop.
Save HurricanKai/9296711e83a2a6ce75e27aece842f820 to your computer and use it in GitHub Desktop.
const std = @import("std");
current_off: comptime_int,
const Self = @This();
pub fn init() Self {
return .{
.current_off = 0,
};
}
pub fn reserve(comptime self: *Self, comptime size: comptime_int) comptime_int {
const offset = self.current_off;
self.current_off = offset + size;
@compileLog("Current off now = ", self.current_off);
return offset;
}
pub fn alignForward(comptime self: *Self, comptime alignment: comptime_int) void {
self.current_off = alignForwardComptime(self.current_off, alignment);
@compileLog("Current off now = ", self.current_off);
}
fn alignForwardComptime(comptime value: comptime_int, comptime alignment: comptime_int) comptime_int {
@setEvalBranchQuota(alignment);
comptime {
for (value..(value + alignment)) |i| {
if (@rem(i, alignment) == 0) {
return i;
}
}
unreachable; // value until value + alignment - 1 will always contain at least one number
}
}
test "Basic Functionality" {
comptime var builder = init();
var num: u64 = 0;
const res1 = builder.reserve(4);
try std.testing.expectEqual(num, @as(u64, res1));
num += 4;
try std.testing.expectEqual(num, @as(u64, builder.current_off));
const res2 = builder.reserve(12);
try std.testing.expectEqual(num, @as(u64, res2));
num += 12;
try std.testing.expectEqual(num, @as(u64, builder.current_off));
}
test "Basic Alignment" {
@compileLog("AAA");
comptime var builder = init();
var num: u64 = 0;
const res1 = builder.reserve(4);
try std.testing.expectEqual(num, @as(u64, res1));
num += 4;
try std.testing.expectEqual(num, @as(u64, builder.current_off));
builder.alignForward(8);
num = std.mem.alignForward(u64, num, 8);
try std.testing.expectEqual(num, @as(u64, builder.current_off));
const res2 = builder.reserve(12);
try std.testing.expectEqual(num, @as(u64, res2));
num += 12;
try std.testing.expectEqual(num, @as(u64, builder.current_off));
@compileLog("BBB");
}
test "Alignment Helper" {
const num = 123;
const alignment = 16;
try std.testing.expectEqual(std.mem.alignForward(u64, num, alignment), alignForwardComptime(num, alignment));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment