86 lines
1.9 KiB
Python
86 lines
1.9 KiB
Python
import uuid
|
|
|
|
|
|
class UUIDObj:
|
|
__slots__ = ('_value',)
|
|
|
|
def __init__(self, value=None):
|
|
if value is None:
|
|
self._value = uuid.uuid4()
|
|
elif isinstance(value, UUIDObj):
|
|
self._value = value._value
|
|
elif isinstance(value, uuid.UUID):
|
|
self._value = value
|
|
elif isinstance(value, bytes):
|
|
if len(value) == 16:
|
|
self._value = uuid.UUID(bytes=value)
|
|
else:
|
|
raise ValueError(f'Invalid UUID bytes length: {len(value)}, expected 16')
|
|
elif isinstance(value, str):
|
|
self._value = uuid.UUID(value)
|
|
else:
|
|
raise TypeError(f'Cannot convert {type(value).__name__} to UUIDObj')
|
|
|
|
@property
|
|
def Str(self):
|
|
return str(self._value)
|
|
|
|
@property
|
|
def Bytes(self):
|
|
return self._value.bytes
|
|
|
|
@property
|
|
def UUID(self):
|
|
return self._value
|
|
|
|
def __str__(self):
|
|
return self.Str
|
|
|
|
def __repr__(self):
|
|
return f'UUIDObj({self.Str})'
|
|
|
|
def __eq__(self, other):
|
|
if isinstance(other, UUIDObj):
|
|
return self._value == other._value
|
|
if isinstance(other, uuid.UUID):
|
|
return self._value == other
|
|
if isinstance(other, str):
|
|
return self.Str == other
|
|
if isinstance(other, bytes) and len(other) == 16:
|
|
return self.Bytes == other
|
|
return NotImplemented
|
|
|
|
def __hash__(self):
|
|
return hash(self._value)
|
|
|
|
def __bool__(self):
|
|
return True
|
|
|
|
|
|
def NewUUID():
|
|
return UUIDObj()
|
|
|
|
|
|
def NewUUIDBytes():
|
|
return uuid.uuid4().bytes
|
|
|
|
|
|
def NewUUIDStr():
|
|
return str(uuid.uuid4())
|
|
|
|
|
|
def UUIDToBytes(value):
|
|
return UUIDObj(value).Bytes
|
|
|
|
|
|
def UUIDToStr(value):
|
|
return UUIDObj(value).Str
|
|
|
|
|
|
def BytesToUUIDStr(value):
|
|
return str(uuid.UUID(bytes=value))
|
|
|
|
|
|
def StrToUUIDBytes(value):
|
|
return uuid.UUID(value).bytes
|