uuid.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "common/uuid.hpp"
  2. #include <openssl/rand.h>
  3. #include <cstring>
  4. namespace smartbotic::common {
  5. thread_local std::mt19937_64 UUID::generator_{std::random_device{}()};
  6. std::string UUID::generate() {
  7. unsigned char bytes[16];
  8. RAND_bytes(bytes, 16);
  9. // Set version 4 (random)
  10. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  11. // Set variant (RFC 4122)
  12. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  13. std::ostringstream ss;
  14. ss << std::hex << std::setfill('0');
  15. for (int i = 0; i < 16; ++i) {
  16. if (i == 4 || i == 6 || i == 8 || i == 10) {
  17. ss << '-';
  18. }
  19. ss << std::setw(2) << static_cast<int>(bytes[i]);
  20. }
  21. return ss.str();
  22. }
  23. std::string UUID::generatePrefixed(const std::string& prefix) {
  24. return prefix + "_" + generate();
  25. }
  26. bool UUID::isValid(const std::string& uuid) {
  27. if (uuid.length() != 36) {
  28. return false;
  29. }
  30. for (size_t i = 0; i < uuid.length(); ++i) {
  31. char c = uuid[i];
  32. if (i == 8 || i == 13 || i == 18 || i == 23) {
  33. if (c != '-') return false;
  34. } else {
  35. if (!std::isxdigit(c)) return false;
  36. }
  37. }
  38. return true;
  39. }
  40. } // namespace smartbotic::common