Skip to content

Commit

Permalink
Fix comparing bounds of different length
Browse files Browse the repository at this point in the history
  • Loading branch information
bezysoftware committed Oct 29, 2024
1 parent 5c6a424 commit 96f9071
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Negentropy/Bound.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public int CompareTo(Bound? other)
return Timestamp.CompareTo(other.Timestamp);
}

return StructuralComparisons.StructuralComparer.Compare(Id, other.Id);
return ByteArrayComparer.Instance.Compare(Id, other.Id);
}
}
}
23 changes: 23 additions & 0 deletions src/Negentropy/ByteArrayComparer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Negentropy
{
internal class ByteArrayComparer : IComparer<byte[]>
{
public int Compare(byte[]? x, byte[]? y)
{
if (x == null || y == null) throw new InvalidOperationException();

for (int i = 0; i < Math.Min(x.Length, y.Length); i++)
{
if (x[i] < y[i]) return -1;
if (x[i] > y[i]) return 1;
}

if (x.Length > y.Length) return 1;
if (x.Length < y.Length) return -1;

return 0;
}

public static ByteArrayComparer Instance { get; } = new ByteArrayComparer();
}
}
34 changes: 34 additions & 0 deletions test/Negentropy.Tests/BoundTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using FluentAssertions;

namespace Negentropy.Tests
{
public class BoundTests
{
[Theory]
[InlineData(0, 0, 0)]
[InlineData(1000, 1000, 0)]
[InlineData(1, 2, -1)]
[InlineData(2, 1, 1)]
public void CompareBoundsByTimestamp(long t1, long t2, int expectation)
{
var b1 = new Bound(t1);
var b2 = new Bound(t2);

b1.CompareTo(b2).Should().Be(expectation);
}

[Theory]
[InlineData("0000", "0000", 0)]
[InlineData("0000", "0010", -1)]
[InlineData("0100", "0000", 1)]
[InlineData("1111", "111100", -1)]
[InlineData("111100", "1111", 1)]
public void CompareBoundsById(string x, string y, int expectation)
{
var b1 = new Bound(Convert.FromHexString(x), 0);
var b2 = new Bound(Convert.FromHexString(y), 0);

b1.CompareTo(b2).Should().Be(expectation);
}
}
}

0 comments on commit 96f9071

Please sign in to comment.