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

Comparers #929

Merged
merged 5 commits into from Jan 11, 2018
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/Discord.Net.Core/Utils/Comparers.cs
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;

namespace Discord
{
public static class DiscordComparers
{
// TODO: simplify with '??=' slated for C# 8.0
public static IEqualityComparer<IUser> UserComparer => _userComparer ?? (_userComparer = new EntityEqualityComparer<IUser, ulong>());
public static IEqualityComparer<IGuild> GuildComparer => _guildComparer ?? (_guildComparer = new EntityEqualityComparer<IGuild, ulong>());
public static IEqualityComparer<IChannel> ChannelComparer => _channelComparer ?? (_channelComparer = new EntityEqualityComparer<IChannel, ulong>());
public static IEqualityComparer<IRole> RoleComparer => _roleComparer ?? (_roleComparer = new EntityEqualityComparer<IRole, ulong>());

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMessage comparer as well?

Copy link
Contributor Author

@Joe4evr Joe4evr Jan 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call.

EDIT: Wait, wasn't there something that it's not guaranteed message IDs will remain globally unique?

Decided to make a specialized implementation just to be safe.

private static IEqualityComparer<IUser> _userComparer;
private static IEqualityComparer<IGuild> _guildComparer;
private static IEqualityComparer<IChannel> _channelComparer;
private static IEqualityComparer<IRole> _roleComparer;

private sealed class EntityEqualityComparer<TEntity, TId> : EqualityComparer<TEntity>
where TEntity : IEntity<TId>
where TId : IEquatable<TId>
{
public override bool Equals(TEntity x, TEntity y)
{
bool xNull = x == null;
bool yNull = y == null;

if (xNull && yNull)
return true;

if (xNull ^ yNull)
return false;

return x.Id.Equals(y.Id);
}

public override int GetHashCode(TEntity obj)
{
return obj?.Id.GetHashCode() ?? 0;
}
}
}
}