_uuid.py 2.2 KB

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