Last active
August 29, 2015 14:11
-
-
Save Higgs1/fee62d230bd87257e0b0 to your computer and use it in GitHub Desktop.
UUID for Python 3
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
# Simple UUID class for python. Doesn't currently create random UUIDs. | |
# Supports conversion between byte, octal, integer, hexadecimal, RFC formatted, | |
# base64 (with or w/o padding), base85, and ascii85 representations. | |
# Supports various math and boolean operations as if it were an integer. | |
import functools, builtins, base64, struct, re | |
Q=0xFFFFFFFFFFFFFFFF | |
@functools.total_ordering | |
class UUID: | |
def __init__(o,hex=None,*,int=0,b64=None,b85=None,a85=None,bytes=None): | |
a,b=struct.unpack('>QQ',base64.b64decode(b64+'='*(-len(b64)%4))if b64\ | |
else base64.a85decode(a85,foldspaces=True)if a85 else bytes if bytes\ | |
else base64.b85decode(b85)if b85 else b'\0'*16) | |
o.int=builtins.int(re.sub('[^a-fA-F0-9]*','',str(hex).replace('0x','')),16)\ | |
if hex else(a<<64)|b if a or b else int | |
__repr__=lambda _:'{}-{}-{}-{}-{}'.format(_.hex[:8],_.hex[8:12], | |
_.hex[12:16],_.hex[16:20],_.hex[20:]) | |
__bytes__=lambda _:struct.pack('>QQ',(_.int>>64)&Q,_.int&Q) | |
a85,b85,b64,hex,b64s,oct,bytes=map(property,[ | |
lambda _:base64.a85encode(_.bytes,foldspaces=True), | |
lambda _:base64.b85encode(_.bytes), | |
lambda _:base64.b64encode(_.bytes), | |
lambda _:'{:032x}'.format(_.int), | |
lambda _:_.b64.strip('='), | |
lambda _:oct(_)[2:], | |
lambda _:bytes(_)]) | |
__index__=__hash__=__int__=lambda _:_.int | |
__eq__=lambda _,o:int(o)==_.int | |
__lt__=lambda _,o:int(o)>_.int | |
__len__=lambda _:16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment