Skip to content

Commit 597e3f8

Browse files
committed
Updated to_buf and size_buffer to no longer depend on array code
1 parent f5d62f4 commit 597e3f8

File tree

1 file changed

+44
-14
lines changed

1 file changed

+44
-14
lines changed

include/pgvector/pqxx.hpp

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,31 @@ template <> struct string_traits<pgvector::Vector> {
4747
}
4848

4949
static std::string_view to_buf(std::span<char> buf, const pgvector::Vector& value, ctx c = {}) {
50-
auto len = pqxx::into_buf(buf, static_cast<std::vector<float>>(value), c);
51-
// replace array brackets
52-
buf[0] = '[';
53-
buf[len - 1] = ']';
54-
return {std::data(buf), len};
50+
auto values = static_cast<std::vector<float>>(value);
51+
52+
size_t here = 0;
53+
buf[here++] = '[';
54+
55+
for (size_t i = 0; i < values.size(); i++) {
56+
if (i != 0) {
57+
buf[here++] = ',';
58+
}
59+
60+
here += pqxx::into_buf(buf.subspan(here), values[i], c);
61+
}
62+
63+
buf[here++] = ']';
64+
65+
return {std::data(buf), here};
5566
}
5667

5768
static size_t size_buffer(const pgvector::Vector& value) noexcept {
58-
return string_traits<std::vector<float>>::size_buffer(
59-
static_cast<std::vector<float>>(value));
69+
size_t size = 2; // [ and ]
70+
for (const auto v : static_cast<std::vector<float>>(value)) {
71+
size += 1; // ,
72+
size += string_traits<float>::size_buffer(v);
73+
}
74+
return size;
6075
}
6176
};
6277

@@ -86,16 +101,31 @@ template <> struct string_traits<pgvector::HalfVector> {
86101
}
87102

88103
static std::string_view to_buf(std::span<char> buf, const pgvector::HalfVector& value, ctx c = {}) {
89-
auto len = pqxx::into_buf(buf, static_cast<std::vector<float>>(value), c);
90-
// replace array brackets
91-
buf[0] = '[';
92-
buf[len - 1] = ']';
93-
return {std::data(buf), len};
104+
auto values = static_cast<std::vector<float>>(value);
105+
106+
size_t here = 0;
107+
buf[here++] = '[';
108+
109+
for (size_t i = 0; i < values.size(); i++) {
110+
if (i != 0) {
111+
buf[here++] = ',';
112+
}
113+
114+
here += pqxx::into_buf(buf.subspan(here), values[i], c);
115+
}
116+
117+
buf[here++] = ']';
118+
119+
return {std::data(buf), here};
94120
}
95121

96122
static size_t size_buffer(const pgvector::HalfVector& value) noexcept {
97-
return string_traits<std::vector<float>>::size_buffer(
98-
static_cast<std::vector<float>>(value));
123+
size_t size = 2; // [ and ]
124+
for (const auto v : static_cast<std::vector<float>>(value)) {
125+
size += 1; // ,
126+
size += string_traits<float>::size_buffer(v);
127+
}
128+
return size;
99129
}
100130
};
101131

0 commit comments

Comments
 (0)