33using System . Runtime . InteropServices ;
44using BenchmarkDotNet . Order ;
55using Genbox . FastData . Internal . Hashes ;
6+ using static System . Numerics . BitOperations ;
67
78namespace Genbox . FastData . Benchmarks . Benchmarks ;
89
@@ -45,4 +46,55 @@ public ulong XXHashTest()
4546
4647 return value ;
4748 }
49+
50+ private static class XxHash
51+ {
52+ private const ulong PRIME64_1 = 0x9E3779B185EBCA87UL ;
53+ private const ulong PRIME64_2 = 0xC2B2AE3D27D4EB4FUL ;
54+ private const ulong PRIME64_3 = 0x165667B19E3779F9UL ;
55+ private const ulong PRIME64_4 = 0x85EBCA77C2B2AE63UL ;
56+ private const ulong PRIME64_5 = 0x27D4EB2F165667C5UL ;
57+
58+ [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
59+ internal static uint ComputeHash ( ReadOnlySpan < char > s , ulong seed = PRIME64_5 ) => ComputeHash ( ref MemoryMarshal . GetReference ( s ) , s . Length , seed ) ;
60+
61+ [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
62+ private static uint ComputeHash ( ref char ptr , int length , ulong seed = PRIME64_5 )
63+ {
64+ ulong hash1 = seed + ( ulong ) length ;
65+
66+ ref ulong ptr64 = ref Unsafe . As < char , ulong > ( ref ptr ) ;
67+ while ( length >= 4 )
68+ {
69+ hash1 ^= Round ( 0 , ptr64 ) ;
70+ hash1 = ( RotateLeft ( hash1 , 27 ) * PRIME64_1 ) + PRIME64_4 ;
71+ ptr64 = ref Unsafe . Add ( ref ptr64 , 1 ) ;
72+ length -= 4 ;
73+ }
74+
75+ ref ushort ptr16 = ref Unsafe . As < ulong , ushort > ( ref ptr64 ) ;
76+ while ( length -- > 0 )
77+ {
78+ hash1 ^= ptr16 * PRIME64_5 ;
79+ hash1 = RotateLeft ( hash1 , 11 ) * PRIME64_1 ;
80+ ptr16 = ref Unsafe . Add ( ref ptr16 , 1 ) ;
81+ }
82+
83+ hash1 ^= hash1 >> 33 ;
84+ hash1 *= PRIME64_2 ;
85+ hash1 ^= hash1 >> 29 ;
86+ hash1 *= PRIME64_3 ;
87+ hash1 ^= hash1 >> 32 ;
88+ return unchecked ( ( uint ) hash1 ) ;
89+ }
90+
91+ [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
92+ private static ulong Round ( ulong acc , ulong input )
93+ {
94+ acc += input * PRIME64_2 ;
95+ acc = RotateLeft ( acc , 31 ) ;
96+ acc *= PRIME64_1 ;
97+ return acc ;
98+ }
99+ }
48100}
0 commit comments