~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
41 lines · 1.4 KB Raw History
//! xxh3-128 via the vendored reference xxHash (Cyan4973/xxHash v0.8.3,
//! pinned in build.zig.zon). needed for gloom bloom filters, whose wire
//! format hashes DIDs with xxh3-128 — a hand-ported hash would risk silent
//! false negatives, so we bind the canonical implementation and verify it
//! against independently generated vectors.

const std = @import("std");

const XXH128_hash_t = extern struct {
    low64: u64,
    high64: u64,
};

extern fn XXH3_128bits(data: [*]const u8, len: usize) XXH128_hash_t;

pub const Hash128 = struct {
    lo: u64,
    hi: u64,
};

pub fn hash(data: []const u8) Hash128 {
    const h = XXH3_128bits(data.ptr, data.len);
    return .{ .lo = h.low64, .hi = h.high64 };
}

// === tests ===
// vectors generated with python xxhash (independent of the C library)

test "xxh3-128 reference vectors" {
    const empty = hash("");
    try std.testing.expectEqual(@as(u64, 0x99aa06d3014798d8), empty.hi);
    try std.testing.expectEqual(@as(u64, 0x6001c324468d497f), empty.lo);

    const did = hash("did:plc:streamsampleaccount");
    try std.testing.expectEqual(@as(u64, 0xb60ab1dc6bcdfbc4), did.hi);
    try std.testing.expectEqual(@as(u64, 0xb4d6e89485049a70), did.lo);

    const fox = hash("the quick brown fox");
    try std.testing.expectEqual(@as(u64, 0x2830e9c6299d0ff9), fox.hi);
    try std.testing.expectEqual(@as(u64, 0xab2ec4cf7e8d85d2), fox.lo);
}