Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions Lib/uuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,7 @@ def getnode():


_last_timestamp = None
_last_clock_seq = None

def uuid1(node=None, clock_seq=None):
"""Generate a UUID from a host ID, sequence number, and the current time.
Expand All @@ -674,15 +675,22 @@ def uuid1(node=None, clock_seq=None):
is_safe = SafeUUID.unknown
return UUID(bytes=uuid_time, is_safe=is_safe)

global _last_timestamp
global _last_timestamp, _last_clock_seq
import time
nanoseconds = time.time_ns()
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
timestamp = nanoseconds // 100 + 0x01b21dd213814000
if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
# if there is a previous clock sequence, then increment
# otherwise, the clock sequence will be regenerated
if _last_clock_seq is not None:
clock_seq = _last_clock_seq + 1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should not replace this one if clock_seq has been given by the user.

Copy link
Contributor Author

@rruuaanng rruuaanng Sep 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you're right about this. If the clock_seq goes past the max value for a long, it'll reset to 0. This means there's a chance it could clash with a UUID that was made when it was 0 (though for the clock to roll back, it would have to go back to the exact same time as that initial 0 moment).

else:
import random
clock_seq = random.getrandbits(14) # regen
_last_timestamp = timestamp
_last_clock_seq = clock_seq
if clock_seq is None:
import random
clock_seq = random.getrandbits(14) # instead of stable storage
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update :func:`uuid.uuid1` in :mod:`uuid` to meet RFC4122.
Loading