From c74bb5495bad67c399f5f9a30b8675d13f0a298d Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Thu, 1 Dec 2022 14:57:47 -0800 Subject: [PATCH] Improved vector text representation - fixes #46 --- CHANGELOG.md | 4 ++++ src/vector.c | 35 ++++++++++++++++++++++++++++------- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5726567..7464a58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.3.3 (unreleased) + +- Improved vector text representation + ## 0.3.2 (2022-11-22) - Fixed `invalid memory alloc request size` error diff --git a/src/vector.c b/src/vector.c index 33e9b8f..3b4d0f2 100644 --- a/src/vector.c +++ b/src/vector.c @@ -5,6 +5,7 @@ #include "vector.h" #include "fmgr.h" #include "catalog/pg_type.h" +#include "common/shortest_dec.h" #include "lib/stringinfo.h" #include "libpq/pqformat.h" #include "utils/array.h" @@ -188,24 +189,44 @@ Datum vector_out(PG_FUNCTION_ARGS) { Vector *vector = PG_GETARG_VECTOR_P(0); - StringInfoData buf; int dim = vector->dim; + char *buf; + char *ptr; int i; + int n; - initStringInfo(&buf); + /* + * Need: + * + * dim * (FLOAT_SHORTEST_DECIMAL_LEN - 1) bytes for + * float_to_shortest_decimal_bufn + * + * dim - 1 bytes for separator + * + * 3 bytes for [, ], and \0 + */ + buf = (char *) palloc(FLOAT_SHORTEST_DECIMAL_LEN * dim + 2); + ptr = buf; - appendStringInfoChar(&buf, '['); + *ptr = '['; + ptr++; for (i = 0; i < dim; i++) { if (i > 0) - appendStringInfoString(&buf, ","); + { + *ptr = ','; + ptr++; + } - appendStringInfoString(&buf, float8out_internal(vector->x[i])); + n = float_to_shortest_decimal_bufn(vector->x[i], ptr); + ptr += n; } - appendStringInfoChar(&buf, ']'); + *ptr = ']'; + ptr++; + *ptr = '\0'; PG_FREE_IF_COPY(vector, 0); - PG_RETURN_CSTRING(buf.data); + PG_RETURN_CSTRING(buf); } /*