Skip to content

Commit

Permalink
Add some more thorough type checking for parameterised benchmarks
Browse files Browse the repository at this point in the history
  • Loading branch information
bens committed Mar 17, 2024
1 parent 019dccb commit 73d7573
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion zbench.zig
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,55 @@ pub const Benchmark = struct {
benchmark: anytype,
config: Optional(Config),
) !void {
// Check the benchmark parameter is the proper type.
const T: type = switch (@typeInfo(@TypeOf(benchmark))) {
.Pointer => |ptr| if (ptr.is_const) ptr.child else @compileError(
"benchmark must be a const ptr to a struct with a 'run' method",
),
else => @compileError(
"benchmark must be a const ptr to a struct with a 'run' method",
),
};

// Check the type of the benchmark parameter has a run function.
comptime switch (@typeInfo(T)) {
.Struct => |str| {
var run_found: bool = false;
for (str.decls) |decl| if (std.mem.eql(u8, decl.name, "run")) {
run_found = true;
};
if (!run_found) @compileError(
"benchmark must be a const ptr to a struct with a 'run' method",
);
},
else => @compileError(
"benchmark must be a const ptr to a struct with a 'run' method",
),
};

// Check the run function has the proper type
comptime switch (@typeInfo(@TypeOf(@field(T, "run")))) {
.Fn => |info| {
if (info.params.len != 2) @compileError(
"benchmark run function must have two parameters",
);
if (info.params[0].type != T) @compileError(
"benchmark run function's first parameter must be self",
);
if (info.params[1].type != std.mem.Allocator) @compileError(
"benchmark run function's second parameter must be an Allocator",
);
if (info.return_type != void) @compileError(
"benchmark run function must return void",
);
},
else => unreachable,
};

try self.benchmarks.append(self.allocator, Definition{
.name = name,
.defn = .{ .parameterised = .{
.func = @ptrCast(&(@TypeOf(benchmark.*).run)),
.func = @ptrCast(&T.run),
.context = @ptrCast(benchmark),
} },
.config = optional(Config, config, self.common_config),
Expand Down

0 comments on commit 73d7573

Please sign in to comment.