Skip to content

Commit

Permalink
Implement Equals/GetHashCode for UnixDomainSocketEndPoint (#69722)
Browse files Browse the repository at this point in the history
* Added impl of Equals/GetHashCode for UnixDomainSocketEP

* Fixed typo

* Fixed missing underscore

* Clarify new fields using comments

* Review feedback

* Review feedback

* Added platform verification

* Fixed sporadic test failure due to hashcode collision
  • Loading branch information
sakno authored Jun 8, 2022
1 parent 5678b79 commit fc8ce9b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.IO;

Expand Down Expand Up @@ -124,12 +125,18 @@ public override string ToString()
}
}

public override bool Equals([NotNullWhen(true)] object? obj)
=> obj is UnixDomainSocketEndPoint ep && _path == ep._path;

public override int GetHashCode() => _path.GetHashCode();

internal UnixDomainSocketEndPoint CreateBoundEndPoint()
{
if (IsAbstract(_path))
{
return this;
}

return new UnixDomainSocketEndPoint(_path, Path.GetFullPath(_path));
}

Expand All @@ -139,6 +146,7 @@ internal UnixDomainSocketEndPoint CreateUnboundEndPoint()
{
return this;
}

return new UnixDomainSocketEndPoint(_path, null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,39 @@ public void UnixDomainSocketEndPoint_RelativePathDeletesFile()
}).Dispose();
}

[ConditionalFact(nameof(PlatformSupportsUnixDomainSockets))]
public void AbstractPathEquality()
{
string abstractPath = '\0' + Guid.NewGuid().ToString();
UnixDomainSocketEndPoint endPoint1 = new(abstractPath);
UnixDomainSocketEndPoint endPoint2 = new(abstractPath);
UnixDomainSocketEndPoint endPoint3 = new('\0' + Guid.NewGuid().ToString());

Assert.Equal(endPoint1, endPoint2);
Assert.Equal(endPoint1.GetHashCode(), endPoint2.GetHashCode());

Assert.NotEqual(endPoint1, endPoint3);
Assert.NotEqual(endPoint2, endPoint3);
}

[ConditionalFact(nameof(PlatformSupportsUnixDomainSockets))]
public void FilePathEquality()
{
string path1 = "relative" + Path.DirectorySeparatorChar + "path";
string path2 = new(path1); // make a copy to avoid reference equality
string path3 = GetRandomNonExistingFilePath();

UnixDomainSocketEndPoint endPoint1 = new(path1);
UnixDomainSocketEndPoint endPoint2 = new(path2);
UnixDomainSocketEndPoint endPoint3 = new(path3);

Assert.Equal(endPoint1, endPoint2);
Assert.Equal(endPoint1.GetHashCode(), endPoint2.GetHashCode());

Assert.NotEqual(endPoint1, endPoint3);
Assert.NotEqual(endPoint2, endPoint3);
}

private static string GetRandomNonExistingFilePath()
{
string result;
Expand Down

0 comments on commit fc8ce9b

Please sign in to comment.