Skip to content

Commit 3ab2668

Browse files
committed
Use psprintf to simplify gtsvectorout()
The buffer allocation was correct, but looked archaic and scary: - It was weird to calculate the buffer size before determining which format string was used. With the same effort, we could've used the right-sized buffer for each branch. - Commit aa0d350 added one more possible return string ("all true bits"), but didn't adjust the code at the top of the function to calculate the returned string's max size. It was not a live bug, because the new string was smaller than the existing ones, but seemed wrong in principle. - Use of sprintf() is generally eyebrow-raising these days Switch to psprintf(). psprintf() allocates a larger buffer than what was allocated before, 128 bytes vs 80 bytes, which is acceptable as this code is not performance or space critical. Reviewed-by: Andres Freund Discussion: https://www.postgresql.org/message-id/54c29fb0-edf2-48ea-9814-44e918bbd6e8@iki.fi
1 parent d5f139c commit 3ab2668

File tree

1 file changed

+4
-13
lines changed

1 file changed

+4
-13
lines changed

src/backend/utils/adt/tsgistidx.c

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -96,34 +96,25 @@ gtsvectorin(PG_FUNCTION_ARGS)
9696
PG_RETURN_VOID(); /* keep compiler quiet */
9797
}
9898

99-
#define SINGOUTSTR "%d true bits, %d false bits"
100-
#define ARROUTSTR "%d unique words"
101-
#define EXTRALEN ( 2*13 )
102-
103-
static int outbuf_maxlen = 0;
104-
10599
Datum
106100
gtsvectorout(PG_FUNCTION_ARGS)
107101
{
108102
SignTSVector *key = (SignTSVector *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
109103
char *outbuf;
110104

111-
if (outbuf_maxlen == 0)
112-
outbuf_maxlen = 2 * EXTRALEN + Max(strlen(SINGOUTSTR), strlen(ARROUTSTR)) + 1;
113-
outbuf = palloc(outbuf_maxlen);
114-
115105
if (ISARRKEY(key))
116-
sprintf(outbuf, ARROUTSTR, (int) ARRNELEM(key));
106+
outbuf = psprintf("%d unique words", (int) ARRNELEM(key));
117107
else
118108
{
119109
if (ISALLTRUE(key))
120-
sprintf(outbuf, "all true bits");
110+
outbuf = pstrdup("all true bits");
121111
else
122112
{
123113
int siglen = GETSIGLEN(key);
124114
int cnttrue = sizebitvec(GETSIGN(key), siglen);
125115

126-
sprintf(outbuf, SINGOUTSTR, cnttrue, (int) SIGLENBIT(siglen) - cnttrue);
116+
outbuf = psprintf("%d true bits, %d false bits",
117+
cnttrue, (int) SIGLENBIT(siglen) - cnttrue);
127118
}
128119
}
129120

0 commit comments

Comments
 (0)