Skip to content

Commit 140e444

Browse files
committed
Improved Bit code [skip ci]
1 parent a64323d commit 140e444

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

pgvector/utils/bit.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,11 @@
55
class Bit:
66
def __init__(self, value):
77
if isinstance(value, bytes):
8-
count = unpack_from('>i', value)[0]
9-
buf = np.frombuffer(value[4:], dtype=np.uint8)
10-
self._value = np.unpackbits(buf, count=count).astype(bool)
8+
self._value = __class__.from_binary(value)._value
119
elif isinstance(value, str):
12-
self._value = np.array([v != '0' for v in value], dtype=bool)
10+
self._value = __class__.from_text(value)._value
1311
else:
14-
self._value = np.array(value, dtype=bool)
12+
self._value = np.asarray(value, dtype=bool)
1513

1614
def __str__(self):
1715
return self.to_text()
@@ -26,6 +24,14 @@ def to_binary(self):
2624
value = self._value
2725
return pack('>i', len(value)) + np.packbits(value).tobytes()
2826

27+
def from_text(value):
28+
return Bit(np.asarray([v != '0' for v in value], dtype=bool))
29+
30+
def from_binary(value):
31+
count = unpack_from('>i', value)[0]
32+
buf = np.frombuffer(value[4:], dtype=np.uint8)
33+
return Bit(np.unpackbits(buf, count=count).astype(bool))
34+
2935
# TODO move rest
3036

3137
def to_db(value):

0 commit comments

Comments
 (0)