Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix .NET 3.5 InternableString.GetHashCode to match the full implementation #8340

Merged
merged 3 commits into from
Feb 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/StringTools/InternableString.Simple.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,29 +200,45 @@ public override unsafe string ToString()
/// <returns>A stable hashcode of the string represented by this instance.</returns>
public override int GetHashCode()
{
int hashCode = 5381;
uint hash = (5381 << 16) + 5381;
bool isOddIndex = false;

if (_firstString != null)
{
foreach (char ch in _firstString)
{
unchecked
{
hashCode = hashCode * 33 ^ ch;
}
hash = HashOneCharacter(hash, ch, isOddIndex);
isOddIndex = !isOddIndex;
}
}
else if (_builder != null)
{
for (int i = 0; i < _builder.Length; i++)
{
unchecked
{
hashCode = hashCode * 33 ^ _builder[i];
}
hash = HashOneCharacter(hash, _builder[i], isOddIndex);
isOddIndex = !isOddIndex;
}
}
return hashCode;
return (int)hash;
}

/// <summary>
/// A helper to hash one character.
/// </summary>
/// <param name="hash">The running hash code.</param>
/// <param name="ch">The character to hash.</param>
/// <param name="isOddIndex">True if the index of the character in the string is odd.</param>
/// <returns></returns>
private static uint HashOneCharacter(uint hash, char ch, bool isOddIndex)
ladipro marked this conversation as resolved.
Show resolved Hide resolved
{
if (isOddIndex)
{
// The hash code was rotated for the previous character, just xor.
return hash ^ ((uint)ch << 16);
}

uint rotatedHash = (hash << 5) | (hash >> (32 - 5));
return (rotatedHash + hash) ^ ch;
}
}
}