Skip to content

Commit

Permalink
Type checking can be much simpler
Browse files Browse the repository at this point in the history
  • Loading branch information
bens committed Mar 17, 2024
1 parent 73d7573 commit bb63c43
Showing 1 changed file with 2 additions and 34 deletions.
36 changes: 2 additions & 34 deletions zbench.zig
Original file line number Diff line number Diff line change
Expand Up @@ -115,40 +115,8 @@ pub const Benchmark = struct {
),
};

// 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,
};
// Check the benchmark parameter has a well typed run function.
_ = @as(fn (T, std.mem.Allocator) void, T.run);

try self.benchmarks.append(self.allocator, Definition{
.name = name,
Expand Down

0 comments on commit bb63c43

Please sign in to comment.