SUCJAH2564NTP4HE7JXIFWJN4C5533GQGQ5MQFJCL2QMKZVIRZEQC
import csv, random, sys
import pytest
from base64 import b64decode
sys.path.append("multiformats")
from unsignedvarint import *
def test_examples():
with open("../../spec/multiformats/unsigned-varint-examples.csv") as examples:
for [input, output] in csv.reader(examples):
assert(encode(int(input)) == b64decode(output))
assert(decode(encode(int(input))) == int(input))
def test_random():
for example in [random.randint(0, PRACTICAL_MAX) for i in range(1000)]:
assert(decode(encode(example)) == example)
def test_errors():
# Empty bytes can't be decoded
with pytest.raises(Exception):
decode(bytes([]))
# Negative numbers don't get encoded
with pytest.raises(AssertionError):
encode(-1)
# Leading nulls error
with pytest.raises(AssertionError):
decode(bytes([0, 0, 0]))
# PRACTICAL_MAX_BYTES is tipping point:
decode(bytes([255, 255, 255, 255, 255, 255, 255, 255, 127]))
with pytest.raises(AssertionError):
decode(bytes([255, 255, 255, 255, 255, 255, 255, 255, 255, 1]))
# PRACTICAL_MAX is tipping point:
encode(PRACTICAL_MAX)
with pytest.raises(AssertionError):
encode(PRACTICAL_MAX + 1)
[metadata]
name = multiformats
version = 0.0.1
[options]
packages = find_namespace:
[options.extras_require]
testing =
setuptools
pytest
pytest-cov
[tool:pytest]
testpaths = test
[coverage:run]
branch = True
[coverage:report]
show_missing = True
skip_covered = True
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
from typing import *
PRACTICAL_MAX_BYTES = 9
PRACTICAL_MAX = 2 ** (7 * PRACTICAL_MAX_BYTES) - 1
UnsignedVarint = NewType("UnsignedVarint", bytes)
def _encode(i: int) -> UnsignedVarint:
assert(i >= 0)
if i > 127:
r = (bytes([(i % 128) + 128]) + encode (i // 128))
else:
r = bytes([i])
return UnsignedVarint(r)
def encode(i: int) -> UnsignedVarint:
assert(i <= PRACTICAL_MAX)
return _encode(i)
def _decode(b: List[int]) -> int:
match b:
case []:
raise Exception("Expected at least 1 byte")
case [c, *t]:
if c >= 128:
assert(len(t) > 0)
return (c - 128) + 128 * _decode(t)
else:
assert(len(t) == 0)
return c
def decode(b: UnsignedVarint) -> int:
assert(len(b) <= PRACTICAL_MAX_BYTES)
return _decode(list(b))