_uuid.py 2.3 KB

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