forked from dstaley/hashab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-against-lib.zig
More file actions
68 lines (56 loc) · 1.75 KB
/
test-against-lib.zig
File metadata and controls
68 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const std = @import("std");
const c = @cImport({
@cInclude("dlfcn.h");
@cInclude("calcHashAB.h");
});
const CalcHashABFn = *const fn ([*]u8, [*]u8, [*]u8, [*]const u8) callconv(.c) void;
const rnd_bytes: *const [23]u8 = "ABCDEFGHIJKLMNOPQRSTUVW";
// Fixed seed for deterministic test generation
const TEST_SEED: u64 = 0xDEADBEEFCAFEBABE;
fn getLibraryFn() !CalcHashABFn {
const handle = c.dlopen("./libhashab32.so", c.RTLD_NOW);
if (handle == null) {
return error.LibraryLoadFailed;
}
const sym = c.dlsym(handle, "calcHashAB");
if (sym == null) {
return error.SymbolNotFound;
}
return @ptrCast(@alignCast(sym));
}
fn generateTestInput(comptime test_index: usize) struct { sha1: [20]u8, uuid: [8]u8 } {
var h = std.crypto.hash.Blake3.init(.{});
h.update(std.mem.asBytes(&TEST_SEED));
const idx: u64 = test_index;
h.update(std.mem.asBytes(&idx));
var buf: [28]u8 = undefined;
h.final(&buf);
return .{
.sha1 = buf[0..20].*,
.uuid = buf[20..28].*,
};
}
fn runTest(comptime test_index: usize) !void {
const libCalcHashAB = try getLibraryFn();
const input = generateTestInput(test_index);
var sha1 = input.sha1;
var uuid = input.uuid;
var expected: [57]u8 = undefined;
var result: [57]u8 = undefined;
// Call library function (expected)
libCalcHashAB(&expected, &sha1, &uuid, rnd_bytes);
// Call C source function (result)
c.calcHashAB(&result, &sha1, &uuid, rnd_bytes);
try std.testing.expectEqualSlices(u8, &expected, &result);
}
comptime {
@setEvalBranchQuota(10000);
for (0..10000) |i| {
_ = struct {
const index = i;
test {
try runTest(index);
}
};
}
}