Skip to content

Commit b1e3669

Browse files
committed
Added checks to from_binary [skip ci]
1 parent f610d5e commit b1e3669

3 files changed

Lines changed: 21 additions & 2 deletions

File tree

pgvector/bit.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,11 @@ def from_binary(cls, value: bytes) -> Bit:
8989
if not isinstance(value, bytes):
9090
raise ValueError('expected bytes')
9191

92+
length, = unpack_from('>i', value)
93+
94+
if len(value) != 4 + (length + 7) // 8:
95+
raise ValueError('invalid length')
96+
9297
bit = cls.__new__(cls)
9398
bit._value = value
9499
return bit

pgvector/halfvec.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,14 @@ def from_text(cls, value: str) -> HalfVector:
5858

5959
@classmethod
6060
def from_binary(cls, value: bytes) -> HalfVector:
61-
# TODO check dimensions/length and unused
61+
dim, unused = struct.unpack_from('>HH', value)
62+
63+
if len(value) != 4 + 2 * dim:
64+
raise ValueError('invalid length')
65+
66+
if unused != 0:
67+
raise ValueError('expected unused to be 0')
68+
6269
vec = cls.__new__(cls)
6370
vec._value = value
6471
return vec

pgvector/vector.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,14 @@ def from_text(cls, value: str) -> Vector:
5858

5959
@classmethod
6060
def from_binary(cls, value: bytes) -> Vector:
61-
# TODO check dimensions/length and unused
61+
dim, unused = struct.unpack_from('>HH', value)
62+
63+
if len(value) != 4 + 4 * dim:
64+
raise ValueError('invalid length')
65+
66+
if unused != 0:
67+
raise ValueError('expected unused to be 0')
68+
6269
vec = cls.__new__(cls)
6370
vec._value = value
6471
return vec

0 commit comments

Comments
 (0)