v5-0002-Buffer-random-numbers.patch
application/octet-stream
Filename: v5-0002-Buffer-random-numbers.patch
Type: application/octet-stream
Part: 1
Message:
Re: UUID v7
Patch
Format: format-patch
Series: patch v5-0002
Subject: Buffer random numbers
| File | + | − |
|---|---|---|
| src/backend/utils/adt/uuid.c | 20 | 3 |
From b8b61133c36babae861ec3d0f38597314308de93 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 v5 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 fed0b1bc52..a4e6349440 100644
--- a/src/backend/utils/adt/uuid.c
+++ b/src/backend/utils/adt/uuid.c
@@ -405,6 +405,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)
{
@@ -428,7 +446,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)
{
@@ -450,7 +467,7 @@ gen_uuid_v7(PG_FUNCTION_ARGS)
/* Time did not change from the previous generation, we must increment counter */
++sequence_counter;
/* 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")));
@@ -465,7 +482,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)