2021-06-30 17:00:22 +02:00
|
|
|
from typing import Optional
|
2021-06-18 17:57:02 +02:00
|
|
|
|
2019-04-07 19:03:26 +02:00
|
|
|
|
2021-06-30 17:00:22 +02:00
|
|
|
def varuint_to_bytes(value: int) -> bytes:
|
2019-04-07 19:03:26 +02:00
|
|
|
if value <= 0x7F:
|
|
|
|
return bytes([value])
|
|
|
|
|
|
|
|
ret = bytes()
|
|
|
|
while value:
|
|
|
|
temp = value & 0x7F
|
|
|
|
value >>= 7
|
|
|
|
if value:
|
|
|
|
ret += bytes([temp | 0x80])
|
|
|
|
else:
|
|
|
|
ret += bytes([temp])
|
|
|
|
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2021-06-30 17:00:22 +02:00
|
|
|
def bytes_to_varuint(value: bytes) -> Optional[int]:
|
2019-04-07 19:03:26 +02:00
|
|
|
result = 0
|
|
|
|
bitpos = 0
|
|
|
|
for val in value:
|
|
|
|
result |= (val & 0x7F) << bitpos
|
|
|
|
bitpos += 7
|
|
|
|
if (val & 0x80) == 0:
|
|
|
|
return result
|
|
|
|
return None
|