_uuid.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import subprocess
  2. def uuid_str_to_int(uuid_str: str) -> int:
  3. """
  4. >>> uuid_str_to_int('613ea4ac-a4cf-4026-8e99-1904b2bb5cd0')
  5. 129260377989791042510121038559452028112
  6. >>> uuid_str_to_int('c064bf40-4fd1-50e1-a2f7-2aefa4593f67')
  7. 255734883912096391966117250963728842599
  8. """
  9. return int(uuid_str.replace('-', ''), 16)
  10. def uuid_int_to_str(uuid_int: str) -> str:
  11. """
  12. >>> uuid_int_to_str(129260377989791042510121038559452028112)
  13. '613ea4ac-a4cf-4026-8e99-1904b2bb5cd0'
  14. >>> uuid_int_to_str(255734883912096391966117250963728842599)
  15. 'c064bf40-4fd1-50e1-a2f7-2aefa4593f67'
  16. """
  17. uuid_hex = hex(uuid_int)[2:]
  18. return '-'.join((uuid_hex[0:8], uuid_hex[8:12], uuid_hex[12:16],
  19. uuid_hex[16:20], uuid_hex[20:]))
  20. def uuid_int_to_bytes(uuid_siv: int) -> bytes:
  21. """
  22. >>> uuid_int_to_bytes(129260377989791042510121038559452028112)
  23. b'a>\\xa4\\xac\\xa4\\xcf@&\\x8e\\x99\\x19\\x04\\xb2\\xbb\\\\\\xd0'
  24. >>> uuid_int_to_bytes(255734883912096391966117250963728842599)
  25. b'\\xc0d\\xbf@O\\xd1P\\xe1\\xa2\\xf7*\\xef\\xa4Y?g'
  26. """
  27. return uuid_siv.to_bytes(16, byteorder='big')
  28. def uuid_bytes_to_int(uuid_bytes: bytes) -> int:
  29. """
  30. >>> uuid_bytes_to_int(b'a>\\xa4\\xac\\xa4\\xcf@&\\x8e\\x99\\x19\\x04\\xb2\\xbb\\\\\\xd0')
  31. 129260377989791042510121038559452028112
  32. >>> uuid_bytes_to_int(b'\\xc0d\\xbf@O\\xd1P\\xe1\\xa2\\xf7*\\xef\\xa4Y?g')
  33. 255734883912096391966117250963728842599
  34. """
  35. return int.from_bytes(uuid_bytes, byteorder='big', signed=False)
  36. def uuid_str_to_bytes(uuid_str: str) -> bytes:
  37. """
  38. >>> uuid_str_to_bytes('613ea4ac-a4cf-4026-8e99-1904b2bb5cd0')
  39. b'a>\\xa4\\xac\\xa4\\xcf@&\\x8e\\x99\\x19\\x04\\xb2\\xbb\\\\\\xd0'
  40. >>> uuid_str_to_bytes('c064bf40-4fd1-50e1-a2f7-2aefa4593f67')
  41. b'\\xc0d\\xbf@O\\xd1P\\xe1\\xa2\\xf7*\\xef\\xa4Y?g'
  42. """
  43. return uuid_int_to_bytes(uuid_str_to_int(uuid_str))
  44. def uuid_bytes_to_str(uuid_bytes: bytes) -> str:
  45. """
  46. >>> uuid_bytes_to_str(b'a>\\xa4\\xac\\xa4\\xcf@&\\x8e\\x99\\x19\\x04\\xb2\\xbb\\\\\\xd0')
  47. '613ea4ac-a4cf-4026-8e99-1904b2bb5cd0'
  48. >>> uuid_bytes_to_str(b'\\xc0d\\xbf@O\\xd1P\\xe1\\xa2\\xf7*\\xef\\xa4Y?g')
  49. 'c064bf40-4fd1-50e1-a2f7-2aefa4593f67'
  50. """
  51. return uuid_int_to_str(uuid_bytes_to_int(uuid_bytes))
  52. def generate_uuid4_bytes() -> bytes:
  53. return subprocess.check_output(['uuid', '-v', '4', '-F', 'BIN']).strip()