From 5a2434438bc3922e9b4fcc1a64e57b97e0ef8183 Mon Sep 17 00:00:00 2001
From: Matthias van de Meent <boekewurm+postgres@gmail.com>
Date: Wed, 3 Jan 2024 02:54:51 +0100
Subject: [PATCH v1 5/7] NodeSupport: Don't emit trailing 0s in outDatum

This reduces raw serialized size of the initdb pg_rewrite dataset by
a limited 1%, and compressed dataset by 0.5%.
---
 src/backend/nodes/outfuncs.c  | 13 ++++++++++++-
 src/backend/nodes/readfuncs.c | 13 +++++++++++++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index 73f1298dee..f6cfcc8a4c 100644
--- a/src/backend/nodes/outfuncs.c
+++ b/src/backend/nodes/outfuncs.c
@@ -410,9 +410,15 @@ outDatum(StringInfo str, Datum value, int typlen, bool typbyval)
 
 	if (typbyval)
 	{
+		int write_length = sizeof(Datum);
 		s = (char *) (&value);
 		appendStringInfo(str, "%u [ ", (unsigned int) length);
-		for (i = 0; i < (Size) sizeof(Datum); i++)
+
+		/* truncate postfix zeroes */
+		while (write_length != 0 && s[write_length - 1] == 0)
+			write_length -= 1;
+
+		for (i = 0; i < write_length; i++)
 			appendStringInfo(str, "%d ", (int) (s[i]));
 		appendStringInfoChar(str, ']');
 	}
@@ -424,6 +430,11 @@ outDatum(StringInfo str, Datum value, int typlen, bool typbyval)
 		else
 		{
 			appendStringInfo(str, "%u [ ", (unsigned int) length);
+
+			/* truncate postfix zeroes */
+			while (length != 0 && s[length - 1] == 0)
+				length -= 1;
+
 			for (i = 0; i < length; i++)
 				appendStringInfo(str, "%d ", (int) (s[i]));
 			appendStringInfoChar(str, ']');
diff --git a/src/backend/nodes/readfuncs.c b/src/backend/nodes/readfuncs.c
index dd1e505bd7..4287a7ec6e 100644
--- a/src/backend/nodes/readfuncs.c
+++ b/src/backend/nodes/readfuncs.c
@@ -852,9 +852,14 @@ readDatum(bool typbyval)
 		s = (char *) (&res);
 		for (i = 0; i < (Size) sizeof(Datum); i++)
 		{
+			if (pg_strtoken_next("]"))
+				break;
+
 			token = pg_strtok(&tokenLength);
 			s[i] = (char) atoi(token);
 		}
+		for (; i < (Size) sizeof(Datum); i++)
+			s[i] = 0;
 	}
 	else if (length <= 0)
 		res = (Datum) NULL;
@@ -863,9 +868,17 @@ readDatum(bool typbyval)
 		s = (char *) palloc(length);
 		for (i = 0; i < length; i++)
 		{
+			if (pg_strtoken_next("]"))
+				break;
+
 			token = pg_strtok(&tokenLength);
+
 			s[i] = (char) atoi(token);
 		}
+
+		for (; i < length; i++)
+			s[i] = 0;
+
 		res = PointerGetDatum(s);
 	}
 
-- 
2.40.1

