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: 4 additions & 4 deletions base62.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def encode(n, charset=CHARSET_DEFAULT):
chs.insert(0, charset[r])

if not chs:
return "0"
return charset[0]

return "".join(chs)

Expand All @@ -50,9 +50,9 @@ def encodebytes(barray, charset=CHARSET_DEFAULT):
# Encode the leading zeros as "0" followed by a character indicating the count.
# This pattern may occur several times if there are many leading zeros.
n, r = divmod(leading_zeros_count, len(charset) - 1)
zero_padding = f"0{charset[-1]}" * n
zero_padding = f"{charset[0]}{charset[-1]}" * n
if r:
zero_padding += f"0{charset[r]}"
zero_padding += f"{charset[0]}{charset[r]}"

# Special case: the input is empty, or is entirely null bytes.
if leading_zeros_count == len(barray):
Expand Down Expand Up @@ -87,7 +87,7 @@ def decodebytes(encoded, charset=CHARSET_DEFAULT):
"""

leading_null_bytes = b""
while encoded.startswith("0") and len(encoded) >= 2:
while encoded.startswith(charset[0]) and len(encoded) >= 2:
leading_null_bytes += b"\x00" * _value(encoded[1], charset)
encoded = encoded[2:]

Expand Down
14 changes: 14 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import base62


CHARSET_QWERTY = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"

bytes_int_pairs = [
(b"\x01", 1),
(b"\x01\x01", 0x0101),
Expand Down Expand Up @@ -39,6 +41,18 @@ def test_basic_inverted():
assert base62.decode("base62", **kwargs) == 10231951886


def test_basic_qwerty():
kwargs = {"charset": CHARSET_QWERTY}

assert base62.encode(0, **kwargs) == "1"
assert base62.decode("1", **kwargs) == 0
assert base62.decode("1111", **kwargs) == 0
assert base62.decode("111112", **kwargs) == 1

assert base62.encode(54742896343, **kwargs) == "base62"
assert base62.decode("base62", **kwargs) == 54742896343


@pytest.mark.parametrize("b, i", bytes_int_pairs)
def test_bytes_to_int(b, i):
assert int.from_bytes(b, "big") == i
Expand Down