From 68370cc8c9d1079c0ef5617ef9ca5a67afb30b30 Mon Sep 17 00:00:00 2001
From: "Andrey M. Borodin" <x4mmm@night.local>
Date: Mon, 21 Aug 2023 11:34:55 +0300
Subject: [PATCH v8 2/3] Buffer random numbers

This allows to generate uuids 10 times faster
---
 src/backend/utils/adt/uuid.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/uuid.c b/src/backend/utils/adt/uuid.c
index 3455b9f564..6b1ea457cb 100644
--- a/src/backend/utils/adt/uuid.c
+++ b/src/backend/utils/adt/uuid.c
@@ -406,6 +406,24 @@ uuid_hash_extended(PG_FUNCTION_ARGS)
 	return hash_any_extended(key->data, UUID_LEN, PG_GETARG_INT64(1));
 }
 
+#define UUID_RND_CACHE_LEN 512
+int rnd_cache_ptr = UUID_RND_CACHE_LEN;
+unsigned char random_cache[UUID_RND_CACHE_LEN];
+
+static bool
+cached_strong_random(void *buf, size_t len)
+{
+	if (len + rnd_cache_ptr >= UUID_RND_CACHE_LEN)
+	{
+		if (!pg_strong_random(random_cache, UUID_RND_CACHE_LEN))
+			return false;
+		rnd_cache_ptr = 0;
+	}
+	memcpy(buf, &random_cache[rnd_cache_ptr], len);
+	rnd_cache_ptr += len;
+	return true;
+}
+
 Datum
 gen_random_uuid(PG_FUNCTION_ARGS)
 {
@@ -429,7 +447,6 @@ gen_random_uuid(PG_FUNCTION_ARGS)
 static uint32_t sequence_counter;
 static uint64_t previous_timestamp = 0;
 
-
 Datum
 gen_uuid_v7(PG_FUNCTION_ARGS)
 {
@@ -456,7 +473,7 @@ gen_uuid_v7(PG_FUNCTION_ARGS)
 		tms = previous_timestamp;
 
 		/* fill everything after the timestamp and counter with random bytes */
-		if (!pg_strong_random(&uuid->data[8], UUID_LEN - 8))
+		if (!cached_strong_random(&uuid->data[8], UUID_LEN - 8))
 			ereport(ERROR,
 					(errcode(ERRCODE_INTERNAL_ERROR),
 					errmsg("could not generate random values")));
@@ -471,7 +488,7 @@ gen_uuid_v7(PG_FUNCTION_ARGS)
 	else
 	{
 		/* fill everything after the timestamp with random bytes */
-		if (!pg_strong_random(&uuid->data[6], UUID_LEN - 6))
+		if (!cached_strong_random(&uuid->data[6], UUID_LEN - 6))
 			ereport(ERROR,
 					(errcode(ERRCODE_INTERNAL_ERROR),
 					errmsg("could not generate random values")));
-- 
2.37.1 (Apple Git-137.1)

