diff --git a/src/Pgvector/SparseVector.cs b/src/Pgvector/SparseVector.cs index 448ccf9..5843666 100644 --- a/src/Pgvector/SparseVector.cs +++ b/src/Pgvector/SparseVector.cs @@ -55,6 +55,11 @@ public SparseVector(ReadOnlyMemory v) public SparseVector(IDictionary dictionary, int dimensions) { + if (dimensions < 0) + { + throw new ArgumentOutOfRangeException(nameof(dimensions)); + } + var count = 0; var capacity = dictionary.Count; var indices = new int[capacity]; @@ -64,6 +69,12 @@ public SparseVector(IDictionary dictionary, int dimensions) { if (e.Value != 0) { + if (e.Key < 0 || e.Key >= dimensions) + { + throw new ArgumentOutOfRangeException( + nameof(dictionary), e.Key, "Dictionary keys must be within the vector dimensions."); + } + indices[count] = e.Key; values[count] = e.Value; count++; diff --git a/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs b/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs index 2b66115..a288438 100644 --- a/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs +++ b/tests/Pgvector.CSharp.Tests/SparseVectorTests.cs @@ -40,6 +40,21 @@ public void DictionaryConstructor() Assert.Equal(new float[] { 1, 2, 3 }, v.Values.ToArray()); } + [Theory] + [InlineData(-1)] + [InlineData(6)] + public void DictionaryConstructorRejectsIndicesOutsideDimensions(int index) + { + var dictionary = new Dictionary { [index] = 1 }; + Assert.Throws(() => new SparseVector(dictionary, 6)); + } + + [Fact] + public void DictionaryConstructorRejectsNegativeDimensions() + { + Assert.Throws(() => new SparseVector(new Dictionary(), -1)); + } + [Fact] public void Equal() {