guid.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "dynamic_string.h"
  6. #include "guid.h"
  7. #include "macros.h"
  8. #include "platform.h"
  9. #if CROWN_PLATFORM_POSIX
  10. #include <fcntl.h>
  11. #include <unistd.h>
  12. #include <errno.h>
  13. #elif CROWN_PLATFORM_WINDOWS
  14. #include <objbase.h>
  15. #endif // CROWN_PLATFORM_POSIX
  16. namespace crown
  17. {
  18. namespace guid
  19. {
  20. Guid new_guid()
  21. {
  22. Guid guid;
  23. #if CROWN_PLATFORM_POSIX
  24. int fd = open("/dev/urandom", O_RDONLY);
  25. CE_ASSERT(fd != -1, "open: erron = %d", errno);
  26. read(fd, &guid, sizeof(guid));
  27. close(fd);
  28. guid.data3 = (guid.data3 & 0x4fffu) | 0x4000u;
  29. guid.data4 = (guid.data4 & 0x3fffffffffffffffu) | 0x8000000000000000u;
  30. #elif CROWN_PLATFORM_WINDOWS
  31. HRESULT hr = CoCreateGuid((GUID*)&guid);
  32. CE_ASSERT(hr == S_OK, "CoCreateGuid: error");
  33. CE_UNUSED(hr);
  34. #endif // CROWN_PLATFORM_POSIX
  35. return guid;
  36. }
  37. Guid parse(const char* str)
  38. {
  39. Guid guid;
  40. try_parse(str, guid);
  41. return guid;
  42. }
  43. bool try_parse(const char* str, Guid& guid)
  44. {
  45. CE_ASSERT_NOT_NULL(str);
  46. u32 a, b, c, d, e, f;
  47. int num = sscanf(str, "%8x-%4x-%4x-%4x-%4x%8x", &a, &b, &c, &d, &e, &f);
  48. guid.data1 = a;
  49. guid.data2 = (u16)(b & 0x0000ffffu);
  50. guid.data3 = (u16)(c & 0x0000ffffu);
  51. guid.data4 = (u64)(d & 0x0000ffffu) << 48 | (u64)(e & 0x0000ffffu) << 32 | (u64)f;
  52. return num == 6;
  53. }
  54. void to_string(const Guid& guid, DynamicString& s)
  55. {
  56. char str[36+1];
  57. snprintf(str, sizeof(str), "%.8x-%.4x-%.4x-%.4x-%.4x%.8x"
  58. , guid.data1
  59. , guid.data2
  60. , guid.data3
  61. , (u16)((guid.data4 & 0xffff000000000000u) >> 48)
  62. , (u16)((guid.data4 & 0x0000ffff00000000u) >> 32)
  63. , (u32)((guid.data4 & 0x00000000ffffffffu) >> 0)
  64. );
  65. s.set(str, sizeof(str)-1);
  66. }
  67. }
  68. } // namespace crown