CmUUID.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "CmUUID.h"
  2. #include "CmPlatform.h"
  3. #include <chrono>
  4. using namespace std::chrono;
  5. namespace BansheeEngine
  6. {
  7. UUIDGenerator::UUIDGenerator()
  8. :mRandomGenerator((unsigned int)system_clock::now().time_since_epoch().count())
  9. {
  10. mHaveMacAddress = Platform::getMACAddress(mMACAddress);
  11. }
  12. void appendHex(String& str, UINT8 n)
  13. {
  14. static const char* digits = "0123456789abcdef";
  15. str += digits[(n >> 4) & 0xF];
  16. str += digits[n & 0xF];
  17. }
  18. void appendHex(String& str, UINT16 n)
  19. {
  20. appendHex(str, UINT8(n >> 8));
  21. appendHex(str, UINT8(n & 0xFF));
  22. }
  23. void appendHex(String& str, UINT32 n)
  24. {
  25. appendHex(str, UINT16(n >> 16));
  26. appendHex(str, UINT16(n & 0xFFFF));
  27. }
  28. String UUIDGenerator::generateRandom()
  29. {
  30. mSpinLock.lock();
  31. auto timestamp = system_clock::now().time_since_epoch().count();
  32. UINT32 timeLow = UINT32(timestamp & 0xFFFFFFFF);
  33. UINT16 timeMid = UINT16((timestamp >> 32) & 0xFFFF);
  34. UINT16 timeHiAndVersion = UINT16((timestamp >> 48) & 0x0FFF) + (UUIDV_TimeBased << 12);
  35. UINT16 clockSeq = (UINT16(mRandomGenerator() >> 4) & 0x3FFF) | 0x8000;
  36. String result;
  37. result.reserve(36);
  38. appendHex(result, timeLow);
  39. result += '-';
  40. appendHex(result, timeMid);
  41. result += '-';
  42. appendHex(result, timeHiAndVersion);
  43. result += '-';
  44. appendHex(result, clockSeq);
  45. result += '-';
  46. if (mHaveMacAddress)
  47. {
  48. for (int i = 0; i < sizeof(MACAddress); ++i)
  49. appendHex(result, mMACAddress.value[i]);
  50. }
  51. else
  52. {
  53. for (int i = 0; i < sizeof(MACAddress); ++i)
  54. appendHex(result, (UINT8)(mRandomGenerator() % 255));
  55. }
  56. mSpinLock.unlock();
  57. return result;
  58. }
  59. };