Skip to content

Commit

Permalink
string persistent hashcode
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasteles committed Sep 4, 2023
1 parent 2452b19 commit 3fbe005
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,28 @@ public static class StringExtensions
[Pure]
public static string RemoveNonDigitOrLetter(this string value) =>
new(value.Where(char.IsLetterOrDigit).ToArray());


/// <summary>
/// Returns a persistent hashcode for the string
/// </summary>
[Pure]
public static int GetStableHashCode(this string str)
{
unchecked
{
int hash1 = 5381;
int hash2 = hash1;

for (int i = 0; i < str.Length && str[i] != '\0'; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1 || str[i + 1] == '\0')
break;
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}

return hash1 + (hash2 * 1566083941);
}
}
}

0 comments on commit 3fbe005

Please sign in to comment.