54 lines
1.7 KiB
C
54 lines
1.7 KiB
C
// vim:fileencoding=utf-8:foldmethod=marker
|
|
|
|
#include "uuid.h"
|
|
#include "../common/aliases/aliases.h"
|
|
#include "../common/assert/assert.h"
|
|
#include "../base/strings/str8/str8.h"
|
|
#include "../prng/xorshift/xorshift.h"
|
|
#include <inttypes.h>
|
|
|
|
#define UUID_STR_FORMAT ("%.8" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.12" PRIx64)
|
|
#define UUID_HEX_FORMAT ("%.16" PRIx64 "%.16" PRIx64)
|
|
|
|
WpUuid wpUuidGenUuid4(void) {
|
|
wp_persist WpXor256State state = {0};
|
|
wp_persist b8 initialised = false;
|
|
|
|
if (!initialised) {
|
|
initialised = true;
|
|
state = wpPrngXorshiftInit();
|
|
}
|
|
|
|
WpUuid uuid = {
|
|
.high = wpPrngXorshift256(&state),
|
|
.low = wpPrngXorshift256(&state),
|
|
};
|
|
|
|
uuid.high = (uuid.high & 0xffffffffffff0fff) | 0x0000000000004000;
|
|
uuid.low = (uuid.low & 0x3fffffffffffffff) | 0x8000000000000000;
|
|
|
|
return uuid;
|
|
}
|
|
|
|
void wpUuidToStr8(const WpUuid *uuid, WpStr8 *buf) {
|
|
wpDebugAssert(uuid != NULL, "`uuid` should not be NULL");
|
|
wpRuntimeAssert(buf != NULL && buf->capacity >= WP_UUID_STR_BUF_LENGTH,
|
|
"String buffer is NULL or doesn't have sufficient capacity");
|
|
|
|
u64 group1 = uuid->high >> 32;
|
|
u64 group2 = (uuid->high << 32) >> 48;
|
|
u64 group3 = (uuid->high << 48) >> 48;
|
|
u64 group4 = uuid->low >> 48;
|
|
u64 group5 = (uuid->low << 16) >> 16;
|
|
|
|
wpStr8Format(buf, UUID_STR_FORMAT, group1, group2, group3, group4, group5);
|
|
}
|
|
|
|
void wpUuidToHex(const WpUuid *uuid, WpStr8 *buf) {
|
|
wpDebugAssert(uuid != NULL, "`uuid` should not be NULL");
|
|
wpRuntimeAssert(buf != NULL && buf->capacity >= WP_UUID_HEX_BUF_LENGTH,
|
|
"String buffer is NULL or doesn't have sufficient capacity");
|
|
|
|
wpStr8Format(buf, UUID_HEX_FORMAT, uuid->high, uuid->low);
|
|
}
|