Sunshine master
Self-hosted game stream host for Moonlight.
uuid.h
Go to the documentation of this file.
1
5#pragma once
6
7// standard includes
8#include <random>
9
13namespace uuid_util {
17 union uuid_t {
18 std::uint8_t b8[16];
19 std::uint16_t b16[8];
20 std::uint32_t b32[4];
21 std::uint64_t b64[2];
22
29 static uuid_t generate(std::default_random_engine &engine) {
30 std::uniform_int_distribution<std::uint8_t> dist(0, std::numeric_limits<std::uint8_t>::max());
31
32 uuid_t buf;
33 for (auto &el : buf.b8) {
34 el = dist(engine);
35 }
36
37 buf.b8[7] &= (std::uint8_t) 0b00101111;
38 buf.b8[9] &= (std::uint8_t) 0b10011111;
39
40 return buf;
41 }
42
48 static uuid_t generate() {
49 std::random_device r;
50
51 std::default_random_engine engine {r()};
52
53 return generate(engine);
54 }
55
61 [[nodiscard]] std::string string() const {
62 std::string result;
63
64 result.reserve(sizeof(uuid_t) * 2 + 4);
65
66 auto hex = util::hex(*this, true);
67 auto hex_view = hex.to_string_view();
68
69 std::string_view slices[] = {
70 hex_view.substr(0, 8),
71 hex_view.substr(8, 4),
72 hex_view.substr(12, 4),
73 hex_view.substr(16, 4)
74 };
75 auto last_slice = hex_view.substr(20, 12);
76
77 for (auto &slice : slices) {
78 std::copy(std::begin(slice), std::end(slice), std::back_inserter(result));
79
80 result.push_back('-');
81 }
82
83 std::copy(std::begin(last_slice), std::end(last_slice), std::back_inserter(result));
84
85 return result;
86 }
87
94 constexpr bool operator==(const uuid_t &other) const {
95 return b64[0] == other.b64[0] && b64[1] == other.b64[1];
96 }
97
104 constexpr bool operator<(const uuid_t &other) const {
105 return (b64[0] < other.b64[0] || (b64[0] == other.b64[0] && b64[1] < other.b64[1]));
106 }
107
114 constexpr bool operator>(const uuid_t &other) const {
115 return (b64[0] > other.b64[0] || (b64[0] == other.b64[0] && b64[1] > other.b64[1]));
116 }
117 };
118} // namespace uuid_util
UUID utilities.
Definition uuid.h:13
UUID value exposed through multiple integer views.
Definition uuid.h:17
std::string string() const
Format the UUID using canonical text form.
Definition uuid.h:61
constexpr bool operator<(const uuid_t &other) const
Order UUID values by their 64-bit word representation.
Definition uuid.h:104
std::uint16_t b16[8]
UUID viewed as 16-bit words.
Definition uuid.h:19
static uuid_t generate()
Generate a UUID value.
Definition uuid.h:48
constexpr bool operator>(const uuid_t &other) const
Order UUID values by their 64-bit word representation.
Definition uuid.h:114
std::uint64_t b64[2]
UUID viewed as 64-bit words.
Definition uuid.h:21
std::uint8_t b8[16]
UUID bytes.
Definition uuid.h:18
static uuid_t generate(std::default_random_engine &engine)
Generate a UUID value.
Definition uuid.h:29
std::uint32_t b32[4]
UUID viewed as 32-bit words.
Definition uuid.h:20
constexpr bool operator==(const uuid_t &other) const
Compare two UUID values for equality.
Definition uuid.h:94