56 lines
1.1 KiB
C++
56 lines
1.1 KiB
C++
#pragma once
|
|
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <cstdint>
|
|
#include <random>
|
|
#include <string>
|
|
#include "cpputils/datetime.h"
|
|
|
|
namespace cpputils {
|
|
namespace uuid {
|
|
|
|
extern std::string uuidToString(std::array<uint8_t, 16> const& uuid) noexcept;
|
|
|
|
class V4 {
|
|
private:
|
|
std::mt19937_64 rng;
|
|
|
|
inline uint64_t random64() { return rng(); }
|
|
|
|
public:
|
|
inline V4() : rng(std::random_device{}()) {}
|
|
|
|
std::array<uint8_t, 16> generate();
|
|
};
|
|
|
|
class V7 {
|
|
|
|
private:
|
|
std::atomic<int64_t> last_timestamp{0};
|
|
std::atomic<uint8_t> sequence{0};
|
|
std::mt19937_64 rng;
|
|
|
|
inline uint64_t random64() { return rng(); }
|
|
|
|
uint8_t next_sequence(int64_t current_timestamp);
|
|
|
|
public:
|
|
inline V7() : rng(std::random_device{}()) {}
|
|
|
|
static inline uint64_t get_timestamp_from_uuid(
|
|
std::array<uint8_t, 16> const& uuid) noexcept {
|
|
uint64_t timestamp = 0;
|
|
for (size_t i = 0; i < 6; ++i) {
|
|
timestamp = (timestamp << 8) | uuid[i];
|
|
}
|
|
return timestamp;
|
|
}
|
|
|
|
std::array<uint8_t, 16> generate(
|
|
int64_t timestamp = cpputils::datetime::now());
|
|
};
|
|
|
|
} // namespace uuid
|
|
} // namespace cpputils
|