Skip to content

Commit

Permalink
Give C# ByteString a sensible GetHashCode implementation.
Browse files Browse the repository at this point in the history
Fixes #2511.
  • Loading branch information
jskeet committed Dec 16, 2016
1 parent a95e38c commit b18bc9b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
13 changes: 13 additions & 0 deletions csharp/src/Google.Protobuf.Test/ByteStringTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,5 +167,18 @@ public void FromBase64_Empty()
// Optimization which also fixes issue 61.
Assert.AreSame(ByteString.Empty, ByteString.FromBase64(""));
}

[Test]
public void GetHashCode_Regression()
{
// We used to have an awful hash algorithm where only the last four
// bytes were relevant. This is a regression test for
// https://github.com/google/protobuf/issues/2511

ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4);
ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4);
Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode());
}

}
}
2 changes: 1 addition & 1 deletion csharp/src/Google.Protobuf/ByteString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ public override int GetHashCode()
int ret = 23;
foreach (byte b in bytes)
{
ret = (ret << 8) | b;
ret = (ret * 31) + b;
}
return ret;
}
Expand Down

0 comments on commit b18bc9b

Please sign in to comment.