Skip to content

Commit

Permalink
Makes DnsLabels comparison case insensitive.
Browse files Browse the repository at this point in the history
  • Loading branch information
alanedwardes committed Feb 10, 2024
1 parent 5fb2de3 commit e293541
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Ae.Dns.Protocol/DnsLabels.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Ae.Dns.Protocol
{
Expand Down Expand Up @@ -43,6 +44,12 @@ namespace Ae.Dns.Protocol
/// <inheritdoc/>
public override string ToString() => _labels == null ? "<none>" : string.Join(".", _labels);

/// <inheritdoc/>
public override bool Equals(object? obj) => obj is DnsLabels labels && this == labels;

/// <inheritdoc/>
public override int GetHashCode() => HashCode.Combine(LabelsNeverNull);

/// <summary>
/// Convert a string to <see cref="DnsLabels"/>.
/// </summary>
Expand All @@ -54,5 +61,21 @@ namespace Ae.Dns.Protocol
/// </summary>
/// <param name="labels"></param>
public static implicit operator string(DnsLabels labels) => string.Join(".", labels.LabelsNeverNull);

/// <summary>
/// Test whether this instance equals the other instance.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator ==(DnsLabels a, DnsLabels b) => a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase);

/// <summary>
/// Test whether this instance does not equal the other instance.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator !=(DnsLabels a, DnsLabels b) => !(a == b);
}
}
22 changes: 22 additions & 0 deletions tests/Ae.Dns.Tests/Protocol/DnsLabelsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
});
}
}
}

0 comments on commit e293541

Please sign in to comment.