skorokithakis / shortuuid

A generator library for concise, unambiguous and URL-safe UUIDs.
http://www.stavros.io/
BSD 3-Clause "New" or "Revised" License
2.05k stars 109 forks source link

Values generated by `shortuuid.random` are often invalid #80

Closed rijenkii closed 2 years ago

rijenkii commented 2 years ago

Repro:

>>> import shortuuid
>>> while True: shortuuid.decode(shortuuid.random())
...
UUID('0b01b8fa-55db-37eb-95b4-5e8a5bb7de08')
UUID('06643955-e965-2c48-5317-a2a7185707d6')
UUID('0a714dc4-a310-7053-b6db-db117cd3db72')
UUID('5cfd332a-a814-87d7-bdb6-4594c587046c')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/rijenkii/.local/lib/python3.10/site-packages/shortuuid/main.py", line 79, in decode
    return _uu.UUID(int=string_to_int(string, self._alphabet))
  File "/usr/lib/python3.10/uuid.py", line 211, in __init__
    raise ValueError('int is out of range (need a 128-bit value)')
ValueError: int is out of range (need a 128-bit value)
rijenkii commented 2 years ago

For my purposes using shortuuid.encode(uuid.uuid4()) instead of shortuuid.random() is a good enough workaround:


>>> import uuid4
>>> import shortuuid
>>> while True: shortuuid.encode(uuid.uuid4())
'eYq2rLsdXUoYcnrQWLYQv4'
'oDyDQErXN5see3HTsHePfe'
'VwS9TAacmGkXMvL3e4ig8d'
'nvkdW43JoKF3tLvyrhgNvM'
'CdejV2s7x7fByFhYYMZewY'
'BRECgehLNSaTo4uLrApwzu'
'aLU56dd9YS7MDkpTbQmdYX'
...
skorokithakis commented 2 years ago

Yes, random data isn't a valid UUID and thus can't be decoded. If you need a UUID, you should use shortuuid.uuid() instead.