Open jhurliman opened 3 weeks ago
Here's what I came up with:
int uuidv7_new(uint8_t* uuid_out) {
thread_local std::array<uint8_t, 16> uuid_prev = {0};
thread_local std::array<uint8_t, 10> rand_bytes = {0};
thread_local int n_rand_consumed = 10;
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
const uint64_t unix_ts_ms = uint64_t(tp.tv_sec) * 1000 + tp.tv_nsec / 1000000;
{
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<uint8_t> dis(0, 255);
// Fill remaining bytes with random values
for (int i = 0; i < n_rand_consumed; ++i) {
rand_bytes[i] = dis(gen);
}
}
// Generate the UUID
const int8_t status = uuidv7_generate(uuid_prev.data(), unix_ts_ms, rand_bytes.data(), uuid_prev.data());
n_rand_consumed = uuidv7_status_n_rand_consumed(status);
// Copy the generated UUID to the output
std::memcpy(uuid_out, uuid_prev.data(), uuid_prev.size());
return status;
}
It would ease integration if the README also provided a thread-safe implementation of
uuidv7_new()
that usedthread_local
for thread safety.