>From 24f07ca5d3f01189ea96084d0c461033d5f89c39 Mon Sep 17 00:00:00 2001
From: Denis Erokhin <erohin-d@datagile.ru>
Date: Tue, 19 Sep 2023 11:42:15 +0300
Subject: [PATCH v1 3/3] Optimize memory allocation during tsvector binary
 receiving

---
 src/backend/utils/adt/tsvector.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/tsvector.c b/src/backend/utils/adt/tsvector.c
index dff0bfe41f..6ff1d59c19 100644
--- a/src/backend/utils/adt/tsvector.c
+++ b/src/backend/utils/adt/tsvector.c
@@ -476,6 +476,7 @@ tsvectorrecv(PG_FUNCTION_ARGS)
 		const char *lexeme;
 		uint16		npos;
 		size_t		lex_len;
+		Size		required_len;
 
 		lexeme = pq_getmsgstring(buf);
 		npos = (uint16) pq_getmsgint(buf, sizeof(uint16));
@@ -497,10 +498,15 @@ tsvectorrecv(PG_FUNCTION_ARGS)
 		 *
 		 * But make sure the buffer is large enough first.
 		 */
-		while (hdrlen + SHORTALIGN(datalen + lex_len) +
-			   sizeof(uint16) + npos * sizeof(WordEntryPos) >= len)
+		required_len = hdrlen + 
+			(npos > 0 
+				? (SHORTALIGN(datalen + lex_len) + sizeof(uint16) + npos * sizeof(WordEntryPos)) 
+				: (datalen + lex_len));
+		if (required_len > len)
 		{
-			len *= 2;
+			do
+				len *= 2;
+			while (required_len > len);
 			vec = (TSVector) repalloc(vec, len);
 		}
 
@@ -546,6 +552,7 @@ tsvectorrecv(PG_FUNCTION_ARGS)
 
 			datalen += sizeof(uint16) + npos * sizeof(WordEntryPos);
 		}
+		Assert(datalen == required_len);
 	}
 
 	SET_VARSIZE(vec, hdrlen + datalen);
-- 
2.39.2.windows.1

