21 static uuid_t generate(std::default_random_engine &engine) {
22 std::uniform_int_distribution<std::uint8_t> dist(0, std::numeric_limits<std::uint8_t>::max());
25 for (
auto &el : buf.b8) {
29 buf.b8[7] &= (std::uint8_t) 0b00101111;
30 buf.b8[9] &= (std::uint8_t) 0b10011111;
38 std::default_random_engine engine {r()};
40 return generate(engine);
44 parse(std::string& uuid_str) {
45 if (uuid_str.length() != 36) {
46 throw std::invalid_argument(
"Invalid UUID string length");
50 unsigned int temp16_1;
51 unsigned int temp32_1, temp32_2;
54 unsigned int data1, data2;
56 uuid_str.c_str(),
"%8x-%4x-%4x-%4x-%8x%4x",
57 &uuid.b32[0], &data1, &data2, &temp16_1, &temp32_1, &temp32_2
61 uuid.b16[2] =
static_cast<std::uint16_t
>(data1);
62 uuid.b16[3] =
static_cast<std::uint16_t
>(data2);
65 uuid.b8[8] = (temp16_1 >> 8) & 0xFF;
66 uuid.b8[9] = temp16_1 & 0xFF;
67 uuid.b8[10] = (temp32_1 >> 24) & 0xFF;
68 uuid.b8[11] = (temp32_1 >> 16) & 0xFF;
69 uuid.b8[12] = (temp32_1 >> 8) & 0xFF;
70 uuid.b8[13] = temp32_1 & 0xFF;
71 uuid.b8[14] = (temp32_2 >> 8) & 0xFF;
72 uuid.b8[15] = temp32_2 & 0xFF;
77 [[nodiscard]] std::string string()
const {
80 result.reserve(
sizeof(
uuid_t) * 2 + 4);
82 auto hex = util::hex(*
this,
true);
83 auto hex_view = hex.to_string_view();
85 std::string_view slices[] = {
86 hex_view.substr(0, 8),
87 hex_view.substr(8, 4),
88 hex_view.substr(12, 4),
89 hex_view.substr(16, 4)
91 auto last_slice = hex_view.substr(20, 12);
93 for (
auto &slice : slices) {
94 std::copy(std::begin(slice), std::end(slice), std::back_inserter(result));
96 result.push_back(
'-');
99 std::copy(std::begin(last_slice), std::end(last_slice), std::back_inserter(result));
104 constexpr bool operator==(
const uuid_t &other)
const {
105 return b64[0] == other.b64[0] && b64[1] == other.b64[1];
108 constexpr bool operator<(
const uuid_t &other)
const {
109 return (b64[0] < other.b64[0] || (b64[0] == other.b64[0] && b64[1] < other.b64[1]));
112 constexpr bool operator>(
const uuid_t &other)
const {
113 return (b64[0] > other.b64[0] || (b64[0] == other.b64[0] && b64[1] > other.b64[1]));