Skip to content
Open
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
8 changes: 8 additions & 0 deletions tests/test_ulid.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ def test_same_millisecond_overflow() -> None:
ULID()


def test_same_millisecond_monotonic_sorting_without_frozen_time() -> None:
previous_ulid = ""
for i in range(10000):
new_ulid = ULID()
assert new_ulid > previous_ulid
previous_ulid = new_ulid


def assert_sorted(seq: list) -> None:
last = seq[0]
for item in seq[1:]:
Expand Down
12 changes: 6 additions & 6 deletions ulid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,17 @@ def timestamp(self, value: float | None = None) -> int:
raise ValueError("Value exceeds maximum possible timestamp")
return value

def randomness(self) -> bytes:
def randomness(self, timestamp: int) -> bytes:
with self.lock:
current_timestamp = self.timestamp()
if current_timestamp == self.prev_timestamp:
if timestamp == self.prev_timestamp:
if self.prev_randomness == constants.MAX_RANDOMNESS:
raise ValueError("Randomness within same millisecond exhausted")
randomness = self.increment_bytes(self.prev_randomness)
else:
randomness = os.urandom(constants.RANDOMNESS_LEN)

self.prev_randomness = randomness
self.prev_timestamp = current_timestamp
self.prev_timestamp = timestamp
return randomness

def increment_bytes(self, value: bytes) -> bytes:
Expand Down Expand Up @@ -148,8 +147,9 @@ def from_timestamp(cls, value: float) -> Self:
>>> ULID.from_timestamp(time.time())
ULID(01E75QWN5HKQ0JAVX9FG1K4YP4)
"""
timestamp = int.to_bytes(cls.provider.timestamp(value), constants.TIMESTAMP_LEN, "big")
randomness = cls.provider.randomness()
timestamp_value = cls.provider.timestamp(value)
timestamp = int.to_bytes(timestamp_value, constants.TIMESTAMP_LEN, "big")
randomness = cls.provider.randomness(timestamp_value)
return cls.from_bytes(timestamp + randomness)

@classmethod
Expand Down