@@ -120,27 +120,32 @@ template <> struct string_traits<pgvector::SparseVector> {
120120 std::vector<int > indices;
121121 std::vector<float > values;
122122
123- if (n > 1 ) {
124- std::istringstream ss (std::string (text.substr (1 , n - 1 )));
125- while (ss.good ()) {
126- std::string substr;
127- std::getline (ss, substr, ' ,' );
128-
129- size_t ne = substr.find (" :" );
130- if (ne == std::string::npos) {
131- throw conversion_error (" Malformed sparsevec literal" );
132- }
123+ auto cb = [&](std::string_view substr) {
124+ size_t ne = substr.find (" :" );
125+ if (ne == std::string::npos) {
126+ throw conversion_error (" Malformed sparsevec literal" );
127+ }
133128
134- int index = string_traits<int >::from_string (substr.substr (0 , ne), c);
135- float value = string_traits<float >::from_string (substr.substr (ne + 1 ), c);
129+ int index = string_traits<int >::from_string (substr.substr (0 , ne), c);
130+ float value = string_traits<float >::from_string (substr.substr (ne + 1 ), c);
136131
137- if (index < 1 ) {
138- throw conversion_error (" Index out of bounds" );
139- }
132+ if (index < 1 ) {
133+ throw conversion_error (" Index out of bounds" );
134+ }
135+
136+ indices.push_back (index - 1 );
137+ values.push_back (value);
138+ };
140139
141- indices.push_back (index - 1 );
142- values.push_back (value);
140+ if (n > 1 ) {
141+ size_t start = 1 ;
142+ for (size_t i = start; i < n - 1 ; i++) {
143+ if (text[i] == ' ,' ) {
144+ cb (text.substr (start, i - start));
145+ start = i + 1 ;
146+ }
143147 }
148+ cb (text.substr (start, n - start));
144149 }
145150
146151 return pgvector::SparseVector (dimensions, indices, values);
0 commit comments