From e29354199d5d64bf31279d18fc2e6045d81e0886 Mon Sep 17 00:00:00 2001 From: Alan Edwardes Date: Sat, 10 Feb 2024 15:27:16 +0000 Subject: [PATCH] Makes DnsLabels comparison case insensitive. --- src/Ae.Dns.Protocol/DnsLabels.cs | 23 +++++++++++++++++++ tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs | 22 ++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/Ae.Dns.Protocol/DnsLabels.cs b/src/Ae.Dns.Protocol/DnsLabels.cs index dd6e470..92c2d58 100644 --- a/src/Ae.Dns.Protocol/DnsLabels.cs +++ b/src/Ae.Dns.Protocol/DnsLabels.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; namespace Ae.Dns.Protocol { @@ -43,6 +44,12 @@ namespace Ae.Dns.Protocol /// public override string ToString() => _labels == null ? "" : string.Join(".", _labels); + /// + public override bool Equals(object? obj) => obj is DnsLabels labels && this == labels; + + /// + public override int GetHashCode() => HashCode.Combine(LabelsNeverNull); + /// /// Convert a string to . /// @@ -54,5 +61,21 @@ namespace Ae.Dns.Protocol /// /// public static implicit operator string(DnsLabels labels) => string.Join(".", labels.LabelsNeverNull); + + /// + /// Test whether this instance equals the other instance. + /// + /// + /// + /// + public static bool operator ==(DnsLabels a, DnsLabels b) => a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase); + + /// + /// Test whether this instance does not equal the other instance. + /// + /// + /// + /// + public static bool operator !=(DnsLabels a, DnsLabels b) => !(a == b); } } diff --git a/tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs b/tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs index 5b05ba7..84250b3 100644 --- a/tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs +++ b/tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs @@ -60,5 +60,27 @@ public void TestCastStringEmpty() { Assert.Empty((string)DnsLabels.Empty); } + + [Fact] + public void TestEquality() + { + Assert.True(new DnsLabels("test.com") == new DnsLabels("test.com")); + Assert.True(new DnsLabels("test.com") == new DnsLabels("TEST.COM")); + Assert.False(new DnsLabels("test.com") != new DnsLabels("TEST.COM")); + Assert.False(new DnsLabels("test.com") != new DnsLabels("test.com")); + Assert.True(new DnsLabels("test.com").Equals(new DnsLabels("test.com"))); + Assert.True(new DnsLabels("test.com").Equals(new DnsLabels("TEST.COM"))); + } + + [Fact] + public void TestGetHashCode() + { + Assert.Distinct(new[] + { + DnsLabels.Empty.GetHashCode(), + new DnsLabels("test.com").GetHashCode(), + new DnsLabels("test.org").GetHashCode() + }); + } } }