Skip to content
Merged
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: 7 additions & 1 deletion ksuid/ksuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,13 @@ class Ksuid:
@classmethod
def from_base62(cls: type[SelfT], data: str) -> SelfT:
"""initializes Ksuid from base62 encoding"""
return cls.from_bytes(int.to_bytes(int(base62.decode(data)), cls.BYTES_LENGTH, "big"))
decoded = int(base62.decode(data))
try:
value = int.to_bytes(decoded, cls.BYTES_LENGTH, "big")
except OverflowError as exc:
byte_length = (decoded.bit_length() + 7) // 8
raise ByteArrayLengthException(f"Incorrect value length {byte_length}") from exc
return cls.from_bytes(value)

@classmethod
def from_bytes(cls: type[SelfT], value: bytes) -> SelfT:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_ksuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ def test_to_from_base62():
assert ksuid == ksuid_from_base62


@pytest.mark.parametrize("ksuid_cls", [Ksuid, KsuidMs])
def test_from_base62_rejects_oversized_value(ksuid_cls):
with pytest.raises(ByteArrayLengthException):
ksuid_cls.from_base62("z" * ksuid_cls.BASE62_LENGTH)


def test_eq_with_non_ksuid_does_not_raise():
ksuid = Ksuid.from_bytes(bytes(Ksuid.BYTES_LENGTH))

Expand Down
Loading