MCPcopy Index your code
hub / github.com/RustPython/RustPython / uuid7

Function uuid7

Lib/uuid.py:844–905  ·  view source on GitHub ↗

Generate a UUID from a Unix timestamp in milliseconds and random bits. UUIDv7 objects feature monotonicity within a millisecond.

()

Source from the content-addressed store, hash-verified

842
843
844def uuid7():
845 """Generate a UUID from a Unix timestamp in milliseconds and random bits.
846
847 UUIDv7 objects feature monotonicity within a millisecond.
848 """
849 # --- 48 --- -- 4 -- --- 12 --- -- 2 -- --- 30 --- - 32 -
850 # unix_ts_ms | version | counter_hi | variant | counter_lo | random
851 #
852 # 'counter = counter_hi | counter_lo' is a 42-bit counter constructed
853 # with Method 1 of RFC 9562, §6.2, and its MSB is set to 0.
854 #
855 # 'random' is a 32-bit random value regenerated for every new UUID.
856 #
857 # If multiple UUIDs are generated within the same millisecond, the LSB
858 # of 'counter' is incremented by 1. When overflowing, the timestamp is
859 # advanced and the counter is reset to a random 42-bit integer with MSB
860 # set to 0.
861
862 global _last_timestamp_v7
863 global _last_counter_v7
864
865 nanoseconds = time.time_ns()
866 timestamp_ms = nanoseconds // 1_000_000
867
868 if _last_timestamp_v7 is None or timestamp_ms > _last_timestamp_v7:
869 counter, tail = _uuid7_get_counter_and_tail()
870 else:
871 if timestamp_ms < _last_timestamp_v7:
872 timestamp_ms = _last_timestamp_v7 + 1
873 # advance the 42-bit counter
874 counter = _last_counter_v7 + 1
875 if counter > 0x3ff_ffff_ffff:
876 # advance the 48-bit timestamp
877 timestamp_ms += 1
878 counter, tail = _uuid7_get_counter_and_tail()
879 else:
880 # 32-bit random data
881 tail = int.from_bytes(os.urandom(4))
882
883 unix_ts_ms = timestamp_ms & 0xffff_ffff_ffff
884 counter_msbs = counter >> 30
885 # keep 12 counter's MSBs and clear variant bits
886 counter_hi = counter_msbs & 0x0fff
887 # keep 30 counter's LSBs and clear version bits
888 counter_lo = counter & 0x3fff_ffff
889 # ensure that the tail is always a 32-bit integer (by construction,
890 # it is already the case, but future interfaces may allow the user
891 # to specify the random tail)
892 tail &= 0xffff_ffff
893
894 int_uuid_7 = unix_ts_ms << 80
895 int_uuid_7 |= counter_hi << 64
896 int_uuid_7 |= counter_lo << 32
897 int_uuid_7 |= tail
898 # by construction, the variant and version bits are already cleared
899 int_uuid_7 |= _RFC_4122_VERSION_7_FLAGS
900 res = UUID._from_int(int_uuid_7)
901

Callers

nothing calls this directly

Calls 3

_from_intMethod · 0.80
from_bytesMethod · 0.45

Tested by

no test coverage detected