-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use stable hash comparer for nuget/oss model
This makes it eaiser to merge PRs when stats are run/updated, since otherwise keys move around since the hashes aren't really stable OOB.
- Loading branch information
Showing
3 changed files
with
49 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace Devlooped.Sponsors; | ||
|
||
public class FnvHashComparer : IEqualityComparer<string> | ||
{ | ||
// FNV-1a 32 bit prime and offset basis | ||
const uint FnvPrime = 0x01000193; | ||
const uint FnvOffsetBasis = 0x811C9DC5; | ||
|
||
public static IEqualityComparer<string> Default { get; } = new FnvHashComparer(); | ||
|
||
public bool Equals(string? x, string? y) | ||
{ | ||
// If both are null, or both are same instance, consider them equal | ||
if (x == y) return true; | ||
if (x == null || y == null) return false; | ||
return x.Equals(y, StringComparison.Ordinal); // Use Ordinal for performance | ||
} | ||
|
||
public int GetHashCode(string obj) | ||
{ | ||
// Convert the 32-bit unsigned hash to a signed int for .NET's GetHashCode | ||
return unchecked((int)Fnv1aHash(obj)); | ||
} | ||
|
||
// Method to compute FNV-1a hash for a string | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
static uint Fnv1aHash(string str) | ||
{ | ||
var hash = FnvOffsetBasis; | ||
foreach (var c in str) | ||
{ | ||
hash ^= c; // XOR the character | ||
hash *= FnvPrime; // Multiply by the FNV prime | ||
} | ||
return hash; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters