uuid.hpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. *
  3. * uuid.hpp
  4. * uuid generator
  5. *
  6. * @author : yandaren1220@126.com
  7. * @date : 2017-06-25
  8. */
  9. #ifndef __ydk_utility_uuid_hpp__
  10. #define __ydk_utility_uuid_hpp__
  11. #include <stdio.h>
  12. #include <stdint.h>
  13. #include <string>
  14. #if defined(_WIN32)
  15. #include <objbase.h>
  16. #elif defined(__linux__)
  17. #include <uuid/uuid.h>
  18. #else
  19. #error "uuid unsupport platform"
  20. #endif
  21. #define GUID_LEN 64
  22. namespace utility
  23. {
  24. namespace uuid
  25. {
  26. #if defined(_WIN32)
  27. static std::string generate()
  28. {
  29. char buf[GUID_LEN] = { 0 };
  30. GUID guid;
  31. if (CoCreateGuid(&guid))
  32. {
  33. return std::move(std::string(""));
  34. }
  35. sprintf(buf,
  36. "%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X",
  37. guid.Data1, guid.Data2, guid.Data3,
  38. guid.Data4[0], guid.Data4[1], guid.Data4[2],
  39. guid.Data4[3], guid.Data4[4], guid.Data4[5],
  40. guid.Data4[6], guid.Data4[7]);
  41. return std::move(std::string(buf));
  42. }
  43. #elif defined(__linux__)
  44. static std::string generate()
  45. {
  46. char buf[GUID_LEN] = { 0 };
  47. uuid_t uu;
  48. uuid_generate( uu );
  49. int32_t index = 0;
  50. for (int32_t i = 0; i < 16; i++)
  51. {
  52. int32_t len = i < 15 ?
  53. sprintf(buf + index, "%02X-", uu[i]) :
  54. sprintf(buf + index, "%02X", uu[i]);
  55. if(len < 0 )
  56. return std::move(std::string(""));
  57. index += len;
  58. }
  59. return std::move(std::string(buf));
  60. }
  61. #endif
  62. }
  63. }
  64. #endif