From 23daf4cd8538fa47fe7ebba8ea644d63c6248f30 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Tue, 6 Sep 2022 11:42:10 +0900
Subject: [PATCH v6 3/4] Expose byte_size_pretty in dbsize.c

---
 src/backend/utils/adt/dbsize.c | 25 ++++++++++++++++---------
 src/include/utils/dbsize.h     | 16 ++++++++++++++++
 2 files changed, 32 insertions(+), 9 deletions(-)
 create mode 100644 src/include/utils/dbsize.h

diff --git a/src/backend/utils/adt/dbsize.c b/src/backend/utils/adt/dbsize.c
index 34efa121b4..abe2c41db4 100644
--- a/src/backend/utils/adt/dbsize.c
+++ b/src/backend/utils/adt/dbsize.c
@@ -25,6 +25,7 @@
 #include "storage/fd.h"
 #include "utils/acl.h"
 #include "utils/builtins.h"
+#include "utils/dbsize.h"
 #include "utils/numeric.h"
 #include "utils/rel.h"
 #include "utils/relfilenumbermap.h"
@@ -549,14 +550,9 @@ pg_total_relation_size(PG_FUNCTION_ARGS)
 	PG_RETURN_INT64(size);
 }
 
-/*
- * formatting with size units
- */
-Datum
-pg_size_pretty(PG_FUNCTION_ARGS)
+void
+byte_size_pretty(char *dest, size_t destlen, int64 size)
 {
-	int64		size = PG_GETARG_INT64(0);
-	char		buf[64];
 	const struct size_pretty_unit *unit;
 
 	for (unit = size_pretty_units; unit->name != NULL; unit++)
@@ -569,8 +565,8 @@ pg_size_pretty(PG_FUNCTION_ARGS)
 			if (unit->round)
 				size = half_rounded(size);
 
-			snprintf(buf, sizeof(buf), INT64_FORMAT " %s", size, unit->name);
-			break;
+			snprintf(dest, destlen, INT64_FORMAT " %s", size, unit->name);
+			return;
 		}
 
 		/*
@@ -586,7 +582,18 @@ pg_size_pretty(PG_FUNCTION_ARGS)
 				+ (unit->round == true));
 		size /= ((int64) 1) << bits;
 	}
+}
 
+/*
+ * formatting with size units
+ */
+Datum
+pg_size_pretty(PG_FUNCTION_ARGS)
+{
+	int64		size = PG_GETARG_INT64(0);
+	char		buf[64];
+
+	byte_size_pretty(buf, sizeof(buf), size);
 	PG_RETURN_TEXT_P(cstring_to_text(buf));
 }
 
diff --git a/src/include/utils/dbsize.h b/src/include/utils/dbsize.h
new file mode 100644
index 0000000000..6bff9d4d6a
--- /dev/null
+++ b/src/include/utils/dbsize.h
@@ -0,0 +1,16 @@
+/*-----------------------------------------------------------------------
+ * dbsize.h
+ *
+ *	 Portions Copyright (c) 1999-2022, PostgreSQL Global Development Group
+ *
+ * src/include/utils/dbsize.h
+ *
+ *-----------------------------------------------------------------------
+ */
+
+#ifndef _DBSIZE_H_
+#define _DBSIZE_H_
+
+extern void byte_size_pretty(char *dest, size_t destlen, int64 size);
+
+#endif							/* _DBSIZE_H_ */
-- 
2.31.1

