uuid.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <string>
  6. #include <string_view>
  7. #include "common/common_types.h"
  8. namespace Common {
  9. constexpr u128 INVALID_UUID{{0, 0}};
  10. /**
  11. * Converts a hex string to a 128-bit unsigned integer.
  12. *
  13. * The hex string can be formatted in lowercase or uppercase, with or without the "0x" prefix.
  14. *
  15. * This function will assert and return INVALID_UUID under the following conditions:
  16. * - If the hex string is more than 32 characters long
  17. * - If the hex string contains non-hexadecimal characters
  18. *
  19. * @param hex_string Hexadecimal string
  20. *
  21. * @returns A 128-bit unsigned integer if successfully converted, INVALID_UUID otherwise.
  22. */
  23. [[nodiscard]] u128 HexStringToU128(std::string_view hex_string);
  24. struct UUID {
  25. // UUIDs which are 0 are considered invalid!
  26. u128 uuid;
  27. UUID() = default;
  28. constexpr explicit UUID(const u128& id) : uuid{id} {}
  29. constexpr explicit UUID(const u64 lo, const u64 hi) : uuid{{lo, hi}} {}
  30. explicit UUID(std::string_view hex_string) {
  31. uuid = HexStringToU128(hex_string);
  32. }
  33. [[nodiscard]] constexpr explicit operator bool() const {
  34. return uuid != INVALID_UUID;
  35. }
  36. [[nodiscard]] constexpr bool operator==(const UUID& rhs) const {
  37. return uuid == rhs.uuid;
  38. }
  39. [[nodiscard]] constexpr bool operator!=(const UUID& rhs) const {
  40. return !operator==(rhs);
  41. }
  42. // TODO(ogniK): Properly generate uuids based on RFC-4122
  43. [[nodiscard]] static UUID Generate();
  44. // Set the UUID to {0,0} to be considered an invalid user
  45. constexpr void Invalidate() {
  46. uuid = INVALID_UUID;
  47. }
  48. [[nodiscard]] constexpr bool IsInvalid() const {
  49. return uuid == INVALID_UUID;
  50. }
  51. [[nodiscard]] constexpr bool IsValid() const {
  52. return !IsInvalid();
  53. }
  54. // TODO(ogniK): Properly generate a Nintendo ID
  55. [[nodiscard]] constexpr u64 GetNintendoID() const {
  56. return uuid[0];
  57. }
  58. [[nodiscard]] std::string Format() const;
  59. [[nodiscard]] std::string FormatSwitch() const;
  60. };
  61. static_assert(sizeof(UUID) == 16, "UUID is an invalid size!");
  62. } // namespace Common
  63. namespace std {
  64. template <>
  65. struct hash<Common::UUID> {
  66. size_t operator()(const Common::UUID& uuid) const noexcept {
  67. return uuid.uuid[1] ^ uuid.uuid[0];
  68. }
  69. };
  70. } // namespace std