fix: Removes Standart XxHash in favor of the built in one (#1598)

This commit is contained in:
Kamron Batman 2023-11-17 16:11:35 -08:00 committed by GitHub
parent e9642d61f1
commit 1769d47ba5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 28 deletions

View file

@ -14,22 +14,12 @@
*************************************************************************/
using System;
using System.IO.Hashing;
using System.Numerics;
using System.Runtime.CompilerServices;
using Standart.Hash.xxHash;
namespace Server;
/// <summary>
/// Represents supported non-cryptographic fast hash algorithms.
/// </summary>
public enum FastHashAlgorithm
{
None, // Used for collisions where full-data is serialized instead
XxHash3_64, // xxHash3 64bit
XxHash_32, // xxHash 32bit
}
public static class HashUtility
{
// *************** DO NOT CHANGE THIS NUMBER ****************
@ -38,27 +28,51 @@ public static class HashUtility
private const ulong xxHash3Seed = 9609125370673258709ul; // Randomly generated 64-bit prime number
private const uint xxHash1Seed = 665738807u; // Randomly generated 32-bit prime number
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ComputeHash64(string? data, FastHashAlgorithm algorithm = FastHashAlgorithm.XxHash3_64) =>
algorithm switch
[ThreadStatic]
private static XxHash3 _xxHash3;
[ThreadStatic]
private static XxHash32 _xxHash32;
public static unsafe ulong ComputeHash64(string? str)
{
if (str == null)
{
FastHashAlgorithm.XxHash3_64 => ComputeXXHash3_64(data),
_ => throw new NotSupportedException($"Hash {algorithm} is not supported.")
};
return 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ComputeXXHash3_64(string? data) => data == null ? 0 : xxHash3.ComputeHash(data, xxHash3Seed);
var hasher = _xxHash3 ??= new XxHash3(unchecked((long)xxHash3Seed));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ComputeHash32(string? data, FastHashAlgorithm algorithm = FastHashAlgorithm.XxHash_32) =>
algorithm switch
fixed (char* src = &str.GetPinnableReference())
{
FastHashAlgorithm.XxHash_32 => ComputeXXHash_32(data),
_ => throw new NotSupportedException($"Hash {algorithm} is not supported.")
};
hasher.Append(new ReadOnlySpan<byte>(src, str.Length * 2));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ComputeXXHash_32(string? data) => data == null ? 0 : xxHash32.ComputeHash(data, xxHash1Seed);
var result = hasher.GetCurrentHashAsUInt64();
hasher.Reset();
return result;
}
public static unsafe uint ComputeHash32(string? str)
{
if (str == null)
{
return 0;
}
var hasher = _xxHash32 ??= new XxHash32(unchecked((int)xxHash1Seed));
fixed (char* src = &str.GetPinnableReference())
{
hasher.Append(new ReadOnlySpan<byte>(src, str.Length * 2));
}
var result = hasher.GetCurrentHashAsUInt32();
hasher.Reset();
return result;
}
public static unsafe int GetNetFrameworkHashCode(this string? str)
{