Skip to content

Commit 09860fd

Browse files
committed
refactor
1 parent 7b62f44 commit 09860fd

File tree

9 files changed

+6671
-4736
lines changed

9 files changed

+6671
-4736
lines changed

std/assembly/util/hash.ts

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// @ts-ignore: decorator
2+
@inline
13
export function HASH<T>(key: T): u64 {
24
if (isString<T>()) {
35
return hashStr(changetype<string>(key));
@@ -8,7 +10,9 @@ export function HASH<T>(key: T): u64 {
810
if (sizeof<T>() == 4) return hash32(reinterpret<u32>(f32(key)));
911
if (sizeof<T>() == 8) return hash64(reinterpret<u64>(f64(key)));
1012
} else {
11-
if (sizeof<T>() <= 4) return hash32(u32(key), sizeof<T>());
13+
if (sizeof<T>() == 1) return hash8(u64(key));
14+
if (sizeof<T>() == 2) return hash16(u64(key));
15+
if (sizeof<T>() == 4) return hash32(u64(key));
1216
if (sizeof<T>() == 8) return hash64(u64(key));
1317
}
1418
return unreachable();
@@ -30,11 +34,33 @@ export function HASH<T>(key: T): u64 {
3034
// @ts-ignore: decorator
3135
@inline const XXH64_SEED: u64 = 0;
3236

33-
// @ts-ignore: decorator
34-
@inline
35-
function hash32(key: u32, len: u64 = 4): u64 {
36-
var h: u64 = XXH64_SEED + XXH64_P5 + len;
37-
h ^= u64(key) * XXH64_P1;
37+
function hash8(key: u64): u64 {
38+
var h: u64 = XXH64_SEED + XXH64_P5 + 1;
39+
h ^= key * XXH64_P1;
40+
h = rotl(h, 23) * XXH64_P2 + XXH64_P3;
41+
h ^= h >> 33;
42+
h *= XXH64_P2;
43+
h ^= h >> 29;
44+
h *= XXH64_P3;
45+
h ^= h >> 32;
46+
return h;
47+
}
48+
49+
function hash16(key: u64): u64 {
50+
var h: u64 = XXH64_SEED + XXH64_P5 + 2;
51+
h ^= key * XXH64_P1;
52+
h = rotl(h, 23) * XXH64_P2 + XXH64_P3;
53+
h ^= h >> 33;
54+
h *= XXH64_P2;
55+
h ^= h >> 29;
56+
h *= XXH64_P3;
57+
h ^= h >> 32;
58+
return h;
59+
}
60+
61+
function hash32(key: u64): u64 {
62+
var h: u64 = XXH64_SEED + XXH64_P5 + 4;
63+
h ^= key * XXH64_P1;
3864
h = rotl(h, 23) * XXH64_P2 + XXH64_P3;
3965
h ^= h >> 33;
4066
h *= XXH64_P2;
@@ -44,8 +70,6 @@ function hash32(key: u32, len: u64 = 4): u64 {
4470
return h;
4571
}
4672

47-
// @ts-ignore: decorator
48-
@inline
4973
function hash64(key: u64): u64 {
5074
var h: u64 = XXH64_SEED + XXH64_P5 + 8;
5175
h ^= rotl(key * XXH64_P2, 31) * XXH64_P1;
@@ -70,8 +94,6 @@ function mix2(h: u64, s: u64): u64 {
7094
return (h ^ (rotl(s, 31) * XXH64_P1)) * XXH64_P1 + XXH64_P4;
7195
}
7296

73-
// @ts-ignore: decorator
74-
@inline
7597
function hashStr(key: string): u64 {
7698
if (key === null) {
7799
return XXH64_SEED;

0 commit comments

Comments
 (0)