diff --git a/src/Pgvector/SparseVector.cs b/src/Pgvector/SparseVector.cs index 7a52c18..427852b 100644 --- a/src/Pgvector/SparseVector.cs +++ b/src/Pgvector/SparseVector.cs @@ -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(); + } } diff --git a/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs b/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs index a09939f..050757a 100644 --- a/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs +++ b/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs @@ -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); + } }