From c0280515375051cfaa69756e259a72aef607b0d4 Mon Sep 17 00:00:00 2001 From: Abdelrahman Said Date: Wed, 19 Mar 2025 23:57:44 +0000 Subject: [PATCH] Complete uuid4 implementation --- README.md | 2 +- src/uuid4.c | 38 +++++++++++++++++++------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 92f2b0d..d30d33f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # UUID4 Generator -Incomplete test implementation of a UUID4 generator +Test implementation of a UUID4 generator diff --git a/src/uuid4.c b/src/uuid4.c index 83eef1a..2263916 100644 --- a/src/uuid4.c +++ b/src/uuid4.c @@ -1,5 +1,4 @@ #include "wapp.h" -#include #include typedef struct uuid4 UUID4; @@ -9,34 +8,35 @@ struct uuid4 { }; UUID4 gen_uuid4(XOR256State *state); -void print_uuid4(UUID4 uuid); +void stringify_uuid4(UUID4 uuid, char *dst, u64 len); int main(void) { XOR256State state = wapp_init_xor_256_state(); + UUID4 uuid = gen_uuid4(&state); + char buf[40] = {0}; - for (int i = 0; i < 100000; ++i) { - UUID4 uuid = gen_uuid4(&state); - print_uuid4(uuid); - } + for (int i = 0; i < 1000; ++i) { + UUID4 uuid = gen_uuid4(&state); + stringify_uuid4(uuid, buf, 40); + printf("%s\n", buf); + } return 0; } UUID4 gen_uuid4(XOR256State *state) { - persistent u64 and_mask = 0xffffffffffff0fff; - persistent u64 or_mask = 0x0000000000004000; - UUID4 uuid = { .high = wapp_xorshift_256_generate(state), .low = wapp_xorshift_256_generate(state) }; - uuid.high &= and_mask; - uuid.high |= or_mask; - return uuid; + UUID4 uuid = { .high = wapp_xorshift_256_generate(state), .low = wapp_xorshift_256_generate(state) }; + uuid.high = (uuid.high & 0xffffffffffff0fff) | 0x0000000000004000; + uuid.low = (uuid.low & 0xbfffffffffffffff) | 0x8000000000000000; + return uuid; } -void print_uuid4(UUID4 uuid) { - u64 a = uuid.high >> 32; - u64 b = (uuid.high << 32) >> 48; - u64 c = (uuid.high << 48) >> 48; - u64 d = uuid.low >> 48; - u64 e = (uuid.low << 16) >> 16; +void stringify_uuid4(UUID4 uuid, char *dst, u64 len) { + u64 a = uuid.high >> 32; + u64 b = (uuid.high << 32) >> 48; + u64 c = (uuid.high << 48) >> 48; + u64 d = uuid.low >> 48; + u64 e = (uuid.low << 16) >> 16; - printf("%.8llx-%.4llx-%.4llx-%.4llx-%.12llx\n", a, b, c, d, e); + snprintf(dst, len, "%.8llx-%.4llx-%.4llx-%.4llx-%.12llx", a, b, c, d, e); }