Skip to content

Commit

Permalink
Added Equals and GetHashCode methods to SparseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 26, 2024
1 parent 3b283ce commit 25e17fe
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Pgvector/SparseVector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,32 @@ public float[] ToArray()

return result;
}

public bool Equals(SparseVector? other)
=> other is not null && Dimensions == other.Dimensions && Indices.Span.SequenceEqual(other.Indices.Span) && Values.Span.SequenceEqual(other.Values.Span);

public override bool Equals(object? obj)
=> obj is SparseVector vector && Equals(vector);

public static bool operator ==(SparseVector? x, SparseVector? y)
=> (x is null && y is null) || (x is not null && x.Equals(y));

public static bool operator !=(SparseVector? x, SparseVector? y) => !(x == y);

public override int GetHashCode()
{
var hashCode = new HashCode();

hashCode.Add(Dimensions);

var indices = Indices.Span;
for (var i = 0; i < indices.Length; i++)
hashCode.Add(indices[i]);

var values = Values.Span;
for (var i = 0; i < values.Length; i++)
hashCode.Add(values[i]);

return hashCode.ToHashCode();
}
}
21 changes: 21 additions & 0 deletions tests/Pgvector.CSharp.Tests/SparseVectorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,25 @@ public void DictionaryConstructor()
Assert.Equal(new float[] { 1, 0, 2, 0, 3, 0 }, v.ToArray());
Assert.Equal(new int[] { 0, 2, 4 }, v.Indices.ToArray());
}

[Fact]
public void Equal()
{
var a = new SparseVector(new float[] { 1, 1, 1 });
var b = new SparseVector(new float[] { 1, 1, 1 });
var c = new SparseVector(new float[] { 1, 2, 3 });

Assert.Equal(a, b);
Assert.NotEqual(a, c);

Assert.True(a == b);
Assert.False(a == c);

Assert.False(a != b);
Assert.True(a != c);

Assert.False(a == null);
Assert.False(null == a);
Assert.True((Vector?)null == null);
}
}

0 comments on commit 25e17fe

Please sign in to comment.