LiosK / uuidv7-h

uuidv7.h - Single-file C/C++ UUIDv7 Library
Apache License 2.0
10 stars 2 forks source link

Provide a thread safe example #1

Open jhurliman opened 3 weeks ago

jhurliman commented 3 weeks ago

It would ease integration if the README also provided a thread-safe implementation of uuidv7_new() that used thread_local for thread safety.

jhurliman commented 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;
}
LiosK commented 2 weeks ago

How about https://github.com/LiosK/uuidv7-h/blob/f30ac97984987c5623c187d5054bb7e75cb6ab7e/README.md