Add UUIDv4 generator
This commit is contained in:
59
src/uuid/uuid.c
Normal file
59
src/uuid/uuid.c
Normal file
@@ -0,0 +1,59 @@
|
||||
#include "uuid.h"
|
||||
#include "../common/aliases/aliases.h"
|
||||
#include "../core/strings/str8/str8.h"
|
||||
#include "../prng/xorshift/xorshift.h"
|
||||
#include <stdbool.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
#define UUID_STR_FORMAT ("%.8" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.12" PRIx64)
|
||||
|
||||
typedef struct uuid4 UUID4;
|
||||
struct uuid4 {
|
||||
u64 high;
|
||||
u64 low;
|
||||
};
|
||||
|
||||
internal UUID4 generate_uuid4(void);
|
||||
internal void uuid4_to_uuid(const UUID4* uuid4, UUID *uuid);
|
||||
|
||||
UUID *wapp_uuid_init_uuid4(UUID *uuid) {
|
||||
if (!uuid) {
|
||||
goto RETURN_INIT_UUID4;
|
||||
}
|
||||
|
||||
UUID4 uuid4 = generate_uuid4();
|
||||
uuid4_to_uuid(&uuid4, uuid);
|
||||
|
||||
RETURN_INIT_UUID4:
|
||||
return uuid;
|
||||
}
|
||||
|
||||
internal UUID4 generate_uuid4(void) {
|
||||
persistent XOR256State state = {0};
|
||||
persistent bool initialised = false;
|
||||
|
||||
if (!initialised) {
|
||||
initialised = true;
|
||||
state = wapp_prng_xorshift_init_state();
|
||||
}
|
||||
|
||||
UUID4 uuid = (UUID4){
|
||||
.high = wapp_prng_xorshift_256(&state),
|
||||
.low = wapp_prng_xorshift_256(&state),
|
||||
};
|
||||
|
||||
uuid.high = (uuid.high & 0xffffffffffff0fff) | 0x0000000000004000;
|
||||
uuid.low = (uuid.low & 0x3fffffffffffffff) | 0x8000000000000000;
|
||||
|
||||
return uuid;
|
||||
}
|
||||
|
||||
internal void uuid4_to_uuid(const UUID4* uuid4, UUID *uuid) {
|
||||
u64 grp1 = uuid4->high >> 32;
|
||||
u64 grp2 = (uuid4->high << 32) >> 48;
|
||||
u64 grp3 = (uuid4->high << 48) >> 48;
|
||||
u64 grp4 = uuid4->low >> 48;
|
||||
u64 grp5 = (uuid4->low << 16) >> 16;
|
||||
|
||||
wapp_str8_format(&(uuid->uuid), UUID_STR_FORMAT, grp1, grp2, grp3, grp4, grp5);
|
||||
}
|
||||
Reference in New Issue
Block a user