From b18bc9b9448d8c97b289f03a3cbad57191f30fad Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 16 Dec 2016 10:42:13 +0000 Subject: Give C# ByteString a sensible GetHashCode implementation. Fixes #2511. --- csharp/src/Google.Protobuf.Test/ByteStringTest.cs | 13 +++++++++++++ csharp/src/Google.Protobuf/ByteString.cs | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs index 685e130a..ff2444a3 100644 --- a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs +++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs @@ -167,5 +167,18 @@ namespace Google.Protobuf // 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()); + } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs index dd7f22d6..5c652cc3 100644 --- a/csharp/src/Google.Protobuf/ByteString.cs +++ b/csharp/src/Google.Protobuf/ByteString.cs @@ -303,7 +303,7 @@ namespace Google.Protobuf int ret = 23; foreach (byte b in bytes) { - ret = (ret << 8) | b; + ret = (ret * 31) + b; } return ret; } -- cgit v1.2.3