Skip to content

Commit ef85b20

Browse files
committed
use UUID._from_int for UUIDv7 and remove divmod usage
1 parent 939b5a8 commit ef85b20

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

Lib/uuid.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ class SafeUUID:
9393
_RFC_4122_VERSION_3_FLAGS = ((3 << 76) | (0x8000 << 48))
9494
_RFC_4122_VERSION_4_FLAGS = ((4 << 76) | (0x8000 << 48))
9595
_RFC_4122_VERSION_5_FLAGS = ((5 << 76) | (0x8000 << 48))
96+
_RFC_4122_VERSION_7_FLAGS = ((7 << 76) | (0x8000 << 48))
9697
_RFC_4122_VERSION_8_FLAGS = ((8 << 76) | (0x8000 << 48))
9798

9899

@@ -782,7 +783,7 @@ def get_counter_and_tail():
782783

783784
import time
784785
nanoseconds = time.time_ns()
785-
timestamp_ms, _ = divmod(nanoseconds, 1_000_000)
786+
timestamp_ms = nanoseconds // 1_000_000
786787

787788
if _last_timestamp_v7 is None or timestamp_ms > _last_timestamp_v7:
788789
counter, tail = get_counter_and_tail()
@@ -800,11 +801,18 @@ def get_counter_and_tail():
800801
_last_timestamp_v7 = timestamp_ms
801802
_last_counter_v7 = counter
802803

803-
int_uuid_7 = (timestamp_ms & 0xffff_ffff_ffff) << 80
804-
int_uuid_7 |= ((counter >> 30) & 0xfff) << 64
805-
int_uuid_7 |= (counter & 0x3fff_ffff) << 32
804+
unix_ts_ms = timestamp_ms & 0xffff_ffff_ffff
805+
counter_msbs = counter >> 30
806+
counter_hi = counter_msbs & 0x0fff # keep 12 bits and clear variant bits
807+
counter_lo = counter & 0x3fff_ffff # keep 30 bits and clear version bits
808+
809+
int_uuid_7 = unix_ts_ms << 80
810+
int_uuid_7 |= counter_hi << 64
811+
int_uuid_7 |= counter_lo << 32
806812
int_uuid_7 |= tail & 0xffff_ffff
807-
return UUID(int=int_uuid_7, version=7)
813+
# by construction, the variant and version bits are already cleared
814+
int_uuid_7 |= _RFC_4122_VERSION_7_FLAGS
815+
return UUID._from_int(int_uuid_7)
808816

809817
def uuid8(a=None, b=None, c=None):
810818
"""Generate a UUID from three custom blocks.

0 commit comments

Comments
 (0)