-
Notifications
You must be signed in to change notification settings - Fork 27
[DRAFT] Improve init, encode, cli #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -80,12 +80,25 @@ class ULID: | |
| ValueError: If the provided value is not a valid encoded ULID. | ||
| """ | ||
|
|
||
| def __init__(self, value: bytes | None = None) -> None: | ||
| if value is not None and len(value) != constants.BYTES_LEN: | ||
| raise ValueError("ULID has to be exactly 16 bytes long.") | ||
| self.bytes: bytes = ( | ||
| value or ULID.from_timestamp(time.time_ns() // constants.NANOSECS_IN_MILLISECS).bytes | ||
| ) | ||
| def __init__(self, value: bytes | str | None = None) -> None: | ||
| if value is None: | ||
| value = self._gen_bytes_from_ts() | ||
| elif isinstance(value, bytes): | ||
| if len(value) != constants.BYTES_LEN: | ||
| raise ValueError(f"ULID has to be exactly {constants.BYTES_LEN} bytes long.") | ||
| elif isinstance(value, str): | ||
| if len(value) != constants.REPR_LEN: | ||
| raise ValueError(f"ULID has to be exactly {constants.REPR_LEN} characters long.") | ||
| value = base32.decode(value) | ||
|
|
||
| self.bytes: bytes = value | ||
|
|
||
| @staticmethod | ||
| def _gen_bytes_from_ts(ts_ms: int | None = None) -> bytes: | ||
| """Generate a new ULID bytes from the timestamp(ms).""" | ||
|
|
||
| ts_ms = ts_ms or time.time_ns() // constants.NANOSECS_IN_MILLISECS | ||
| return ts_ms.to_bytes(constants.TIMESTAMP_LEN, "big") + os.urandom(constants.RANDOMNESS_LEN) | ||
|
|
||
| @classmethod | ||
| @validate_type(datetime) | ||
|
|
@@ -116,9 +129,7 @@ def from_timestamp(cls: type[U], value: float) -> U: | |
| """ | ||
| if isinstance(value, float): | ||
| value = int(value * constants.MILLISECS_IN_SECS) | ||
| timestamp = int.to_bytes(value, constants.TIMESTAMP_LEN, "big") | ||
| randomness = os.urandom(constants.RANDOMNESS_LEN) | ||
| return cls.from_bytes(timestamp + randomness) | ||
| return cls.from_bytes(cls._gen_bytes_from_ts(value)) | ||
|
|
||
| @classmethod | ||
| @validate_type(uuid.UUID) | ||
|
|
@@ -190,7 +201,7 @@ def parse(cls: type[U], value: Any) -> U: | |
| return cls.from_bytes(value) | ||
| raise TypeError(f"Cannot parse ULID from type {type(value)}") | ||
|
|
||
| @property | ||
| @functools.cached_property | ||
| def milliseconds(self) -> int: | ||
| """The timestamp part as epoch time in milliseconds. | ||
|
|
||
|
|
@@ -201,7 +212,7 @@ def milliseconds(self) -> int: | |
| """ | ||
| return int.from_bytes(self.bytes[: constants.TIMESTAMP_LEN], byteorder="big") | ||
|
|
||
| @property | ||
| @functools.cached_property | ||
| def timestamp(self) -> float: | ||
| """The timestamp part as epoch time in seconds. | ||
|
|
||
|
|
@@ -212,7 +223,7 @@ def timestamp(self) -> float: | |
| """ | ||
| return self.milliseconds / constants.MILLISECS_IN_SECS | ||
|
|
||
| @property | ||
| @functools.cached_property | ||
| def datetime(self) -> datetime: | ||
| """Return the timestamp part as timezone-aware :class:`datetime` in UTC. | ||
|
|
||
|
|
@@ -223,7 +234,7 @@ def datetime(self) -> datetime: | |
| """ | ||
| return datetime.fromtimestamp(self.timestamp, timezone.utc) | ||
|
|
||
| @property | ||
| @functools.cached_property | ||
| def hex(self) -> str: | ||
| """Encode the :class:`ULID`-object as a 32 char sequence of hex values.""" | ||
| return self.bytes.hex() | ||
|
|
@@ -249,7 +260,7 @@ def to_uuid4(self) -> uuid.UUID: | |
| return uuid.UUID(bytes=self.bytes, version=4) | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"ULID({self!s})" | ||
| return f"ULID({str(self)!r})" | ||
|
|
||
| def __str__(self) -> str: | ||
| """Encode this object as a 26 character string sequence.""" | ||
|
|
@@ -297,7 +308,9 @@ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler | |
| core_schema.union_schema([ | ||
| core_schema.is_instance_schema(ULID), | ||
| core_schema.no_info_plain_validator_function(ULID), | ||
| core_schema.str_schema(pattern=r"[A-Z0-9]{26}", min_length=26, max_length=26), | ||
| core_schema.str_schema( | ||
| pattern=rf"[{base32.ENCODE}]{{26}}", min_length=26, max_length=26 | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a test that would need to be adapted. Good catch with the
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ok, I missed this issue and I'll follow up on a fix |
||
| ), | ||
| core_schema.bytes_schema(min_length=16, max_length=16), | ||
| ]), | ||
| serialization=core_schema.to_string_ser_schema( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_bytes_from_timestamp(...)