aboutsummaryrefslogtreecommitdiff
path: root/lib/std/hash/verify.zig
diff options
context:
space:
mode:
authorMarc Tiehuis <marc@tiehu.is>2023-09-01 19:37:40 +1200
committerMarc Tiehuis <marc@tiehu.is>2023-09-02 15:37:49 +1200
commit1c148f161905469b0ad5cf4de801cf287c491174 (patch)
tree702966068829d7775a33e79d734f24bca5eab97d /lib/std/hash/verify.zig
parent26d61812a8dbad204517d00d3a1f0e52275eceeb (diff)
downloadzig-1c148f161905469b0ad5cf4de801cf287c491174.tar.gz
zig-1c148f161905469b0ad5cf4de801cf287c491174.zip
std/hash: add generic tests for idempotency/iterative api
Diffstat (limited to 'lib/std/hash/verify.zig')
-rw-r--r--lib/std/hash/verify.zig27
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/std/hash/verify.zig b/lib/std/hash/verify.zig
index bfc6a1f22c..5d853fee28 100644
--- a/lib/std/hash/verify.zig
+++ b/lib/std/hash/verify.zig
@@ -13,6 +13,15 @@ fn hashMaybeSeed(comptime hash_fn: anytype, seed: anytype, buf: []const u8) @typ
}
}
+fn initMaybeSeed(comptime Hash: anytype, seed: anytype) Hash {
+ const HashFn = @typeInfo(@TypeOf(Hash.init)).Fn;
+ if (HashFn.params.len == 1) {
+ return Hash.init(@intCast(seed));
+ } else {
+ return Hash.init();
+ }
+}
+
// Returns a verification code, the same as user by SMHasher.
//
// Hash keys of the form {0}, {0,1}, {0,1,2}... up to N=255, using 256-N as seed.
@@ -33,3 +42,21 @@ pub fn smhasher(comptime hash_fn: anytype) u32 {
return @truncate(hashMaybeSeed(hash_fn, 0, buf_all[0..]));
}
+
+pub fn iterativeApi(comptime Hash: anytype) !void {
+ // Sum(1..32) = 528
+ var buf: [528]u8 = [_]u8{0} ** 528;
+ var len: usize = 0;
+ const seed = 0;
+
+ var hasher = initMaybeSeed(Hash, seed);
+ for (1..32) |i| {
+ const r = hashMaybeSeed(Hash.hash, seed, buf[0 .. len + i]);
+ hasher.update(buf[len..][0..i]);
+ const f1 = hasher.final();
+ const f2 = hasher.final();
+ if (f1 != f2) return error.IterativeHashWasNotIdempotent;
+ if (f1 != r) return error.IterativeHashDidNotMatchDirect;
+ len += i;
+ }
+}