Skip to content
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

🚚 Move increment_base62 from lamindb here #85

Merged
merged 2 commits into from
Sep 29, 2024
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
12 changes: 12 additions & 0 deletions lamin_utils/_base62.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@
CHARSET_INVERTED = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def increment_base62(s: str) -> str:
# we don't need to throw an error for zzzz because uids are enforced to be unique
# on the db level and have an enforced maximum length
value = sum(CHARSET_DEFAULT.index(c) * (62**i) for i, c in enumerate(reversed(s)))
value += 1
result = ""
while value:
value, remainder = divmod(value, 62)
result = CHARSET_DEFAULT[remainder] + result
return result.zfill(len(s))


def encode(n, charset=CHARSET_DEFAULT):
"""Encodes a given integer ``n``."""
chs = []
Expand Down
12 changes: 12 additions & 0 deletions tests/test_base62.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import lamin_utils._base62 as base62
import pytest
from lamin_utils._base62 import increment_base62

bytes_int_pairs = [
(b"\x01", 1),
Expand All @@ -10,6 +11,17 @@
]


def test_increment_base62():
assert increment_base62("0000") == "0001"
assert increment_base62("0009") == "000A"
assert increment_base62("000Z") == "000a"
assert increment_base62("000z") == "0010"
assert increment_base62("0019") == "001A"
assert increment_base62("0zzz") == "1000"
# do not throw an error here, see comment in implementation
assert increment_base62("zzzz") == "10000"


def test_const():
assert len(base62.CHARSET_DEFAULT) == base62.BASE == 62
assert len(base62.CHARSET_INVERTED) == base62.BASE == 62
Expand Down
Loading