BsUUID.cpp 1.9 KB

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