sandbox
Loading...
Searching...
No Matches
uuid.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_MATH_UUID_HPP_
3#define LIBSBX_MATH_UUID_HPP_
4
5#include <cinttypes>
6#include <concepts>
7
8#include <fmt/format.h>
9
10#include <libsbx/math/random.hpp>
11
12namespace sbx::math {
13
14template<std::unsigned_integral Type>
16
17public:
18
19 using value_type = Type;
20
22 : _value{random::next<value_type>(1u)} { }
23
24 static constexpr auto nil() -> basic_uuid {
25 return basic_uuid{0u};
26 }
27
28 static constexpr auto from_value(const value_type value) -> basic_uuid {
29 return basic_uuid{value};
30 }
31
32 static constexpr auto create() -> basic_uuid {
33 return basic_uuid{random::next<value_type>()};
34 }
35
36 constexpr auto operator==(const basic_uuid& other) const noexcept -> bool {
37 return _value == other._value;
38 }
39
40 constexpr auto operator<(const basic_uuid& other) const noexcept -> bool {
41 return _value < other._value;
42 }
43
44 constexpr auto value() const noexcept -> value_type {
45 return _value;
46 }
47
48private:
49
50 basic_uuid(const value_type value)
51 : _value{value} { }
52
53 value_type _value;
54
55}; // class uuid
56
58
59} // namespace sbx::math
60
61template<std::unsigned_integral Type>
62struct fmt::formatter<sbx::math::basic_uuid<Type>> {
63
64 template<typename ParseContext>
65 constexpr auto parse(ParseContext& context) -> decltype(context.begin()) {
66 return context.begin();
67 }
68
69 template<typename FormatContext>
70 auto format(const sbx::math::basic_uuid<Type>& uuid, FormatContext& context) const -> decltype(context.out()) {
71 static constexpr auto width = sizeof(Type) * 2;
72
74 return fmt::format_to(context.out(), "[nil]");
75 }
76
77 return fmt::format_to(context.out(), "{:0{}x}", uuid.value(), width);
78 }
79}; // struct fmt::formatter<sbx::math::uuid>
80
81template<std::unsigned_integral Type>
82struct YAML::convert<sbx::math::basic_uuid<Type>> {
83
84 static auto encode(const sbx::math::basic_uuid<Type>& rhs) -> YAML::Node {
85 return Node{rhs.value()};
86 }
87
88 static auto decode(const YAML::Node& node, sbx::math::basic_uuid<Type>& rhs) -> bool {
89 if (!node.IsScalar()) {
90 return false;
91 }
92
94
95 return true;
96 }
97
98}; // struct YAML::convert<sbx::math::basic_vector3<Type>>
99
100template<std::unsigned_integral Type>
101auto operator<<(YAML::Emitter& out, const sbx::math::basic_uuid<Type>& vector) -> YAML::Emitter& {
102 return out << YAML::convert<sbx::math::basic_uuid<Type>>::encode(vector);
103}
104
105template<std::unsigned_integral Type>
106struct std::hash<sbx::math::basic_uuid<Type>> {
107 auto operator()(const sbx::math::basic_uuid<Type>& uuid) const noexcept -> std::size_t {
108 return uuid.value();
109 }
110}; // struct std::hash<sbx::math::uuid>
111
112#endif // LIBSBX_MATH_UUID_HPP_
113
Definition: tests.cpp:6
Definition: uuid.hpp:15