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

Make CodeownersEntry.GetHashCode support Enumerables #5636

Merged
merged 1 commit into from
Mar 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
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;
}
}
}
}