Skip to content

Commit

Permalink
CodeownersEntry.GetHashCode now properly supports enumerables (#5636)
Browse files Browse the repository at this point in the history
  • Loading branch information
Konrad Jamrozik authored Mar 6, 2023
1 parent 83e289a commit aba9602
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion tools/code-owners-parser/CodeOwnersParser/CodeownersEntry.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

Expand Down Expand Up @@ -184,7 +185,43 @@ public override bool Equals(object? obj)
// @formatter:on
}

/// <summary>
/// Implementation of GetHashCode that properly hashes collections.
/// Implementation based on
/// https://stackoverflow.com/a/10567544/986533
///
/// This implementation is candidate to be moved to:
/// https://github.com/Azure/azure-sdk-tools/issues/5281
/// </summary>
public override int GetHashCode()
=> HashCode.Combine(PathExpression, Owners, PRLabels, ServiceLabels);
{
int hashCode = 0;
// ReSharper disable NonReadonlyMemberInGetHashCode
hashCode = AddHashCodeForObject(hashCode, PathExpression);
hashCode = AddHashCodeForEnumerable(hashCode, Owners);
hashCode = AddHashCodeForEnumerable(hashCode, PRLabels);
hashCode = AddHashCodeForEnumerable(hashCode, ServiceLabels);
// ReSharper restore NonReadonlyMemberInGetHashCode
return hashCode;

// ReSharper disable once VariableHidesOuterVariable
int AddHashCodeForEnumerable(int hashCode, IEnumerable enumerable)
{
foreach (var item in enumerable)
{
hashCode = AddHashCodeForObject(hashCode, item);
}
return hashCode;
}

int AddHashCodeForObject(int hc, object item)
{
// Based on https://stackoverflow.com/a/10567544/986533
hc ^= item.GetHashCode();
hc = (hc << 7) |
(hc >> (32 - 7)); // rotate hashCode to the left to swipe over all bits
return hc;
}
}
}
}

0 comments on commit aba9602

Please sign in to comment.