guid.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include "fwd.h"
  3. #include <util/str_stl.h>
  4. /**
  5. * UUID generation
  6. *
  7. * NOTE: It is not a real GUID (RFC 4122), as described in
  8. * https://en.wikipedia.org/wiki/Universally_unique_identifier
  9. * https://en.wikipedia.org/wiki/Globally_unique_identifier
  10. *
  11. * See https://clubs.at.yandex-team.ru/stackoverflow/10238/10240
  12. * and https://st.yandex-team.ru/IGNIETFERRO-768 for details.
  13. */
  14. struct TGUID {
  15. ui32 dw[4] = {};
  16. constexpr bool IsEmpty() const noexcept {
  17. return (dw[0] | dw[1] | dw[2] | dw[3]) == 0;
  18. }
  19. constexpr explicit operator bool() const noexcept {
  20. return !IsEmpty();
  21. }
  22. // xxxx-xxxx-xxxx-xxxx
  23. TString AsGuidString() const;
  24. /**
  25. * RFC4122 GUID, which described in
  26. * https://en.wikipedia.org/wiki/Universally_unique_identifier
  27. * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  28. **/
  29. TString AsUuidString() const;
  30. static TGUID Create();
  31. /**
  32. * Generate time based UUID version 1 RFC4122 GUID
  33. * https://datatracker.ietf.org/doc/html/rfc4122#section-4.1
  34. **/
  35. static TGUID CreateTimebased();
  36. };
  37. constexpr bool operator==(const TGUID& a, const TGUID& b) noexcept {
  38. return a.dw[0] == b.dw[0] && a.dw[1] == b.dw[1] && a.dw[2] == b.dw[2] && a.dw[3] == b.dw[3];
  39. }
  40. constexpr bool operator!=(const TGUID& a, const TGUID& b) noexcept {
  41. return !(a == b);
  42. }
  43. struct TGUIDHash {
  44. constexpr int operator()(const TGUID& a) const noexcept {
  45. return a.dw[0] + a.dw[1] + a.dw[2] + a.dw[3];
  46. }
  47. };
  48. template <>
  49. struct THash<TGUID> {
  50. constexpr size_t operator()(const TGUID& g) const noexcept {
  51. return (unsigned int)TGUIDHash()(g);
  52. }
  53. };
  54. void CreateGuid(TGUID* res);
  55. TString GetGuidAsString(const TGUID& g);
  56. TString CreateGuidAsString();
  57. TGUID GetGuid(TStringBuf s);
  58. bool GetGuid(TStringBuf s, TGUID& result);
  59. /**
  60. * Functions for correct parsing RFC4122 GUID, which described in
  61. * https://en.wikipedia.org/wiki/Universally_unique_identifier
  62. **/
  63. TGUID GetUuid(TStringBuf s);
  64. bool GetUuid(TStringBuf s, TGUID& result);