Skip to content

Commit 6e8abbe

Browse files
committed
use UUID._from_int for UUIDv6
1 parent 769e60d commit 6e8abbe

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

Lib/uuid.py

Lines changed: 10 additions & 14 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_6_FLAGS = ((6 << 76) | (0x8000 << 48))
9697
_RFC_4122_VERSION_8_FLAGS = ((8 << 76) | (0x8000 << 48))
9798

9899

@@ -780,27 +781,22 @@ def uuid6(node=None, clock_seq=None):
780781
timestamp = _last_timestamp_v6 + 1
781782
_last_timestamp_v6 = timestamp
782783
if clock_seq is None:
783-
# If the caller does not specify a clock sequence, we may assume that
784-
# sequentiality within the same 60-bit timestamp is less important
785-
# than unpredictability. In particular, by using a randomized clock
786-
# sequence, we indirectly slow down the next call, thereby allowing
787-
# the next 60-bit timestamp to be distinct.
788-
#
789-
# Stated otherwise, it is unlikely that two UUIDs are generated within
790-
# the same 100-ns interval since constructing a UUID object takes more
791-
# than 100 ns.
792784
import random
793785
clock_seq = random.getrandbits(14) # instead of stable storage
794786
time_hi_and_mid = (timestamp >> 12) & 0xffff_ffff_ffff
795-
time_ver_and_lo = timestamp & 0x0fff
796-
var_and_clock_s = clock_seq & 0x3fff
787+
time_lo = timestamp & 0x0fff # keep 12 bits and clear version bits
788+
clock_s = clock_seq & 0x3fff # keep 14 bits and clear variant bits
797789
if node is None:
798790
node = getnode()
791+
# --- 32 + 16 --- -- 4 -- -- 12 -- -- 2 -- -- 14 --- 48
792+
# time_hi_and_mid | version | time_lo | variant | clock_seq | node
799793
int_uuid_6 = time_hi_and_mid << 80
800-
int_uuid_6 |= time_ver_and_lo << 64
801-
int_uuid_6 |= var_and_clock_s << 48
794+
int_uuid_6 |= time_lo << 64
795+
int_uuid_6 |= clock_s << 48
802796
int_uuid_6 |= node & 0xffff_ffff_ffff
803-
return UUID(int=int_uuid_6, version=6)
797+
# by construction, the variant and version bits are already cleared
798+
int_uuid_6 |= _RFC_4122_VERSION_6_FLAGS
799+
return UUID._from_int(int_uuid_6)
804800

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

0 commit comments

Comments
 (0)