libs/base/src/base/guid.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #pragma once | ||
| 2 | |||
| 3 | #include <string> | ||
| 4 | #include <optional> | ||
| 5 | #include <array> | ||
| 6 | |||
| 7 | #include "base/ints.h" | ||
| 8 | #include "assert/assert.h" | ||
| 9 | |||
| 10 | namespace eu | ||
| 11 | { | ||
| 12 | /// Represents a universally unique identifier. | ||
| 13 | struct Guid | ||
| 14 | { | ||
| 15 | std::array<u8, 16> data; | ||
| 16 | |||
| 17 | |||
| 18 | /// Does nothing. | ||
| 19 | /// @see \ref eu::nil_guid | ||
| 20 | Guid() = default; | ||
| 21 | |||
| 22 | /// Set the guid data. | ||
| 23 | constexpr explicit Guid(std::array<u8, 16> d) | ||
| 24 | : data(std::move(d)) | ||
| 25 | { | ||
| 26 | } | ||
| 27 | |||
| 28 | 9 | constexpr explicit Guid(u32 a, u16 b, u16 c, u16 d, u64 e) | |
| 29 | 9 | : data{{ | |
| 30 | // a | ||
| 31 | 9 | static_cast<u8>((a >> 24) & 0xFF), | |
| 32 | 9 | static_cast<u8>((a >> 16) & 0xFF), | |
| 33 | 9 | static_cast<u8>((a >> 8) & 0xFF), | |
| 34 | static_cast<u8>(a & 0xFF), | ||
| 35 | // b | ||
| 36 | 9 | static_cast<u8>((b >> 8) & 0xFF), | |
| 37 | static_cast<u8>(b & 0xFF), | ||
| 38 | // c | ||
| 39 | 9 | static_cast<u8>((c >> 8) & 0xFF), | |
| 40 | static_cast<u8>(c & 0xFF), | ||
| 41 | // d | ||
| 42 | 9 | static_cast<u8>((d >> 8) & 0xFF), | |
| 43 | static_cast<u8>(d & 0xFF), | ||
| 44 | // e | ||
| 45 | 9 | static_cast<u8>((e >> 40) & 0xFF), | |
| 46 | 9 | static_cast<u8>((e >> 32) & 0xFF), | |
| 47 | 9 | static_cast<u8>((e >> 24) & 0xFF), | |
| 48 | 9 | static_cast<u8>((e >> 16) & 0xFF), | |
| 49 | 9 | static_cast<u8>((e >> 8) & 0xFF), | |
| 50 | static_cast<u8>(e & 0xFF), | ||
| 51 | }} | ||
| 52 | { | ||
| 53 | 9 | ASSERT((e >> 48) == 0); | |
| 54 | 9 | } | |
| 55 | |||
| 56 | [[nodiscard]] static std::optional<Guid> generate(); | ||
| 57 | }; | ||
| 58 | |||
| 59 | bool operator==(const Guid& lhs, const Guid& rhs); | ||
| 60 | bool operator!=(const Guid& lhs, const Guid& rhs); | ||
| 61 | |||
| 62 | /// Parse a guid from a string | ||
| 63 | [[nodiscard]] std::optional<Guid> guid_from(const std::string& str); | ||
| 64 | |||
| 65 | /// Convert a guid to a string representation, prefer fmt. | ||
| 66 | [[nodiscard]] std::string string_from(const Guid& g); | ||
| 67 | |||
| 68 | /// A nil guid, all bits are set to 0. | ||
| 69 | constexpr Guid nil_guid = Guid | ||
| 70 | { | ||
| 71 | std::array<u8, 16> | ||
| 72 | { | ||
| 73 | 0, 0, 0, 0, | ||
| 74 | 0, 0, | ||
| 75 | 0, 0, | ||
| 76 | 0, 0, | ||
| 77 | 0, 0, 0, 0, 0, 0 | ||
| 78 | } | ||
| 79 | }; | ||
| 80 | |||
| 81 | // todo(Gustav): add std::map and std::unoredered map support | ||
| 82 | |||
| 83 | ADD_CATCH_FORMATTER_DEF(Guid) | ||
| 84 | } | ||
| 85 | |||
| 86 | 4 | ADD_DEFAULT_FORMATTER(eu::Guid, std::string, eu::string_from); | |
| 87 |