From 76ffe8f1027a936fe85ea5ad30469601eb8dfff6 Mon Sep 17 00:00:00 2001 From: Mr444-dev <63791256+Mr444-dev@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:14:31 +0100 Subject: [PATCH] Validate sparse vector dictionary bounds --- src/Pgvector/SparseVector.cs | 11 +++++++++++ tests/Pgvector.CSharp.Tests/SparseVectorTests.cs | 15 +++++++++++++++ 2 files changed, 26 insertions(+) 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() {