Complete uuid4 implementation

This commit is contained in:
Abdelrahman Said 2025-03-19 23:57:44 +00:00
parent 12334f53e1
commit c028051537
2 changed files with 20 additions and 20 deletions

View File

@ -1,3 +1,3 @@
# UUID4 Generator
Incomplete test implementation of a UUID4 generator
Test implementation of a UUID4 generator

View File

@ -1,5 +1,4 @@
#include "wapp.h"
#include <inttypes.h>
#include <stdio.h>
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);
}