31 lines
1.1 KiB
Python
31 lines
1.1 KiB
Python
import uuid
|
|
from typing import Optional
|
|
|
|
UUID_BYTE_ARRAY_LENGTH = 16
|
|
|
|
|
|
class UuidExtension:
|
|
@staticmethod
|
|
def to_uuid(bytes_: Optional[bytes]) -> uuid.UUID:
|
|
"""
|
|
Converts a byte array into a UUID object.
|
|
"""
|
|
if bytes_ is None or len(bytes_) != UUID_BYTE_ARRAY_LENGTH:
|
|
raise ValueError(f"Wrong UUID size: expected {UUID_BYTE_ARRAY_LENGTH} bytes, got {len(bytes_)}")
|
|
|
|
# Unpack the byte array into two 64-bit integers
|
|
most_sig_bits = int.from_bytes(bytes_[:8], byteorder='big', signed=False)
|
|
least_sig_bits = int.from_bytes(bytes_[8:], byteorder='big', signed=False)
|
|
|
|
return uuid.UUID(int=(most_sig_bits << 64) | least_sig_bits)
|
|
|
|
@staticmethod
|
|
def to_bytes(uuid_: Optional[uuid.UUID]) -> bytes:
|
|
"""
|
|
Converts a UUID object into a byte array.
|
|
"""
|
|
if uuid_ is None:
|
|
raise ValueError(f"Input parameter is missing: {uuid.UUID.__name__}")
|
|
|
|
# Pack the UUID into a 16-byte array
|
|
return (uuid_.int >> 64).to_bytes(8, byteorder='big') + (uuid_.int & 0xFFFFFFFFFFFFFFFF).to_bytes(8, byteorder='big')
|