From 7af5c60f22f9bd6064204f84467cfa62bedd1147 Mon Sep 17 00:00:00 2001 From: Edward Thomson Date: Mon, 21 Oct 2013 17:13:04 -0400 Subject: [PATCH] Teach LambdaEqualityHelper to deal with null equality contribution --- LibGit2Sharp.Tests/EqualityFixture.cs | 52 ++++++++++++++++++++ LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj | 1 + LibGit2Sharp/Core/LambdaEqualityHelper.cs | 3 +- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 LibGit2Sharp.Tests/EqualityFixture.cs diff --git a/LibGit2Sharp.Tests/EqualityFixture.cs b/LibGit2Sharp.Tests/EqualityFixture.cs new file mode 100644 index 000000000..168d5fb99 --- /dev/null +++ b/LibGit2Sharp.Tests/EqualityFixture.cs @@ -0,0 +1,52 @@ +using LibGit2Sharp.Tests.TestHelpers; +using Xunit; + +namespace LibGit2Sharp.Tests +{ + public class EqualityFixture : BaseFixture + { + [Fact] + public void EqualityHelperCanTestNullInEquals() + { + var one = new ObjectWithEquality(); + var two = new ObjectWithEquality(); + var three = new ObjectWithEquality(ObjectId.Zero); + var four = new ObjectWithEquality(ObjectId.Zero); + + Assert.True(one.Equals(one)); + Assert.True(two.Equals(two)); + Assert.True(three.Equals(four)); + Assert.True(four.Equals(three)); + Assert.False(one.Equals(three)); + Assert.False(three.Equals(one)); + } + + [Fact] + public void EqualityHelperCanTestNullInHashCode() + { + var one = new ObjectWithEquality(); + var two = new ObjectWithEquality(); + var three = new ObjectWithEquality(ObjectId.Zero); + var four = new ObjectWithEquality(ObjectId.Zero); + + Assert.Equal(one.GetHashCode(), two.GetHashCode()); + Assert.Equal(three.GetHashCode(), four.GetHashCode()); + Assert.NotEqual(one.GetHashCode(), three.GetHashCode()); + } + + private class ObjectWithEquality : GitObject + { + private readonly ObjectId id; + + public ObjectWithEquality(ObjectId id = null) + { + this.id = id; + } + + public override ObjectId Id + { + get { return id; } + } + } + } +} diff --git a/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj b/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj index 3d84d498c..6a356cb85 100644 --- a/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj +++ b/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj @@ -59,6 +59,7 @@ + diff --git a/LibGit2Sharp/Core/LambdaEqualityHelper.cs b/LibGit2Sharp/Core/LambdaEqualityHelper.cs index 55ae7bcaf..120e705de 100644 --- a/LibGit2Sharp/Core/LambdaEqualityHelper.cs +++ b/LibGit2Sharp/Core/LambdaEqualityHelper.cs @@ -47,7 +47,8 @@ public int GetHashCode(T instance) { foreach (Func accessor in equalityContributorAccessors) { - hashCode = (hashCode*397) ^ accessor(instance).GetHashCode(); + object item = accessor(instance); + hashCode = (hashCode*397) ^ (item != null ? item.GetHashCode() : 0); } }