Skip to content

Commit

Permalink
add extra xor "c"
Browse files Browse the repository at this point in the history
this on an even number of rounds acts as a xor-encrypt-xor block, a common technique in cryptography. this helps reduce artifacts in the generic width implementation.
  • Loading branch information
francescoalemanno committed Nov 2, 2024
1 parent f620b97 commit dcbbed4
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions lib/std/hash.zig
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,12 @@ const xxhash = @import("hash/xxhash.zig");
pub const XxHash3 = xxhash.XxHash3;
pub const XxHash64 = xxhash.XxHash64;
pub const XxHash32 = xxhash.XxHash32;

/// Deprecated in favor of `int`.
pub fn uint32(input: u32) u32 {
return int(input);
}

/// Applies a bit-mangling transformation to an unsigned integer type `T`.
/// Applies a bit-mangling transformation to an integer type `T`.
/// Optimized per type: for `u16` and `u32`, Skeeto's xorshift-multiply; for `u64`, Maiga's mx3.
/// Falls back on an avalanche pattern for other integer types, ensuring high entropy.
pub fn int(input: anytype) @TypeOf(input) {
Expand Down Expand Up @@ -90,25 +89,26 @@ pub fn int(input: anytype) @TypeOf(input) {
while (mul * 3 < max) mul *= 3;
break :blk ((mul ^ (mul >> hsize)) | 1);
};
inline for (0..2) |_| {
x = (x ^ (x >> hsize + 1)) *% c;
x = (x ^ (x >> hsize - 1)) *% c;
const sh = comptime hsize | 1;
inline for (0..4) |_| {
//the extra xor here acts as a XEX, it helps greatly
x = ((x ^ (x >> sh)) *% c) ^ c;
}
x ^= (x >> hsize);
x ^= (x >> sh);
},
}
return x;
}

test int {
const expectEqual = @import("std").testing.expectEqual;
try expectEqual(0xC, int(@as(u4, 1)));
try expectEqual(0x4F, int(@as(u8, 1)));
try expectEqual(0x4F, int(@as(i8, 1)));
try expectEqual(0xD, int(@as(u4, 1)));
try expectEqual(0x11, int(@as(u8, 3)));
try expectEqual(0x11, int(@as(i8, 3)));
try expectEqual(0x2880, int(@as(u16, 1)));
try expectEqual(0x42741D6, int(@as(u32, 1)));
try expectEqual(0x71894DE00D9981F, int(@as(u64, 1)));
try expectEqual(0x50BC2BB18910C3DE0BAA2CE0D0C5B83E, int(@as(u128, 1)));
try expectEqual(0x555e8e1ae49daf5bfbe0787f46093d52, int(@as(u128, 1)));
}

test {
Expand Down

0 comments on commit dcbbed4

Please sign in to comment.