18 lines
471 B
Python
18 lines
471 B
Python
from __future__ import annotations
|
|
|
|
import secrets
|
|
import time
|
|
|
|
_CROCKFORD32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
|
|
|
|
def new_ulid() -> str:
|
|
"""Return a lexicographically sortable 26-character ULID."""
|
|
timestamp_ms = int(time.time_ns() // 1_000_000)
|
|
value = (timestamp_ms << 80) | secrets.randbits(80)
|
|
encoded = ["0"] * 26
|
|
for index in range(25, -1, -1):
|
|
encoded[index] = _CROCKFORD32[value & 31]
|
|
value >>= 5
|
|
return "".join(encoded)
|