pneave

Generate UUID

Mar 14th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. inline int setbits(const int a, const int b, const int mask)
  2. {
  3.     return a | (b & mask);
  4. }
  5.  
  6. static unsigned char random_char()
  7. {
  8.     std::random_device rd;
  9.     std::mt19937 gen(rd());
  10.     std::uniform_int_distribution<> dis(0, 255);
  11.     return static_cast<unsigned char>(dis(gen));
  12. }
  13.  
  14. static std::string generate_hex(const unsigned int len)
  15. {
  16.     std::stringstream ss;
  17.     for (auto i = 0; static_cast<const unsigned>(i) < len; i++) {
  18.         auto rc = random_char();
  19.         std::stringstream hexstream;
  20.         hexstream << std::hex << int(rc);
  21.         auto hex = hexstream.str();
  22.         ss << (hex.length() < 2 ? '0' + hex : hex);
  23.     }
  24.     return ss.str();
  25. }
  26.  
  27. std::string uuid()
  28. {
  29.     // The UUID is of the form: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
  30.     //
  31.     // Where the 4 bits of digit M indicate the UUID version, and the 1–3
  32.     // most significant bits of digit N indicate the UUID variant.
  33.     //
  34.     // UUIDs generated here are version 4 variant 1.
  35.  
  36.     std::ostringstream ss;
  37.     const int version = std::stoi(generate_hex(2), nullptr, 16);
  38.     const int variant = std::stoi(generate_hex(2), nullptr, 16);
  39.     ss << generate_hex(4) << "-" << generate_hex(2) << "-"
  40.        << std::hex << setbits(0x4000, version, 0x0fff) << "-"
  41.        << std::hex << setbits(0x8000, variant, 0x3fff) << "-"
  42.        << generate_hex(6);
  43.     return ss.str();
  44. }
Add Comment
Please, Sign In to add comment