Created
June 11, 2015 17:54
-
-
Save adamcharnock/3779308f4f1fb994397e to your computer and use it in GitHub Desktop.
Experimenting with making a ShortUUID class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from uuid import UUID, uuid4 | |
import base64 | |
def make_uuid(type_bits, type_size): | |
bits = uuid4().int | |
id_size = 128 - type_size | |
# Zero out the type bits | |
bits &= pow(2, id_size) - 1 | |
# Now add in the type | |
bits |= (type_bits << id_size) | |
return UUID(int=bits) | |
def short_uuid(uuid=None): | |
return ShortUUID(int=(uuid or uuid4()).int) | |
def pack_uuid(uuid): | |
return base64.urlsafe_b64encode(UUID(str(uuid)).bytes).decode("utf-8").rstrip('=\n').replace('/', '_') | |
def unpack_uuid(short_uuid): | |
return UUID(bytes=base64.urlsafe_b64decode((short_uuid + '==').replace('_', '/'))) | |
class ShortUUID(UUID): | |
def __init__(self, hex=None, *args, **kwargs): | |
if hex and len(hex) <= 22: | |
uuid = unpack_uuid(hex) | |
return super(ShortUUID, self).__init__(int=uuid.int) | |
else: | |
return super(ShortUUID, self).__init__(hex, *args, **kwargs) | |
@property | |
def short(self): | |
return pack_uuid(self.hex) | |
def __str__(self): | |
return self.short | |
if __name__ == '__main__': | |
for x in range(0, 0b111111): | |
print(short_uuid(make_uuid(x, 6))) | |
uuid = short_uuid() | |
print("Hex:\t%s" % uuid.hex) | |
print("Short:\t%s" % uuid.short) | |
print("Str:\t%s" % uuid) | |
print("Repr:\t%s" % repr(uuid)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment