mirror of
https://github.com/LBRYFoundation/LBRY-Vault.git
synced 2025-08-23 17:47:31 +00:00
base_encode/base_decode: performance improvement
For example, for 50 KB of random data, and base 43, previously, - base_encode took ~38 seconds - base_decode took ~270 seconds now, - base_encode takes ~7.5 seconds - base_decode takes ~6 seconds
This commit is contained in:
parent
369d972aed
commit
01f94fcf58
1 changed files with 10 additions and 4 deletions
|
@ -455,8 +455,11 @@ def base_encode(v: bytes, base: int) -> str:
|
||||||
if base == 43:
|
if base == 43:
|
||||||
chars = __b43chars
|
chars = __b43chars
|
||||||
long_value = 0
|
long_value = 0
|
||||||
for (i, c) in enumerate(v[::-1]):
|
power_of_base = 1
|
||||||
long_value += (256**i) * c
|
for c in v[::-1]:
|
||||||
|
# naive but slow variant: long_value += (256**i) * c
|
||||||
|
long_value += power_of_base * c
|
||||||
|
power_of_base <<= 8
|
||||||
result = bytearray()
|
result = bytearray()
|
||||||
while long_value >= base:
|
while long_value >= base:
|
||||||
div, mod = divmod(long_value, base)
|
div, mod = divmod(long_value, base)
|
||||||
|
@ -486,11 +489,14 @@ def base_decode(v: Union[bytes, str], length: Optional[int], base: int) -> Optio
|
||||||
if base == 43:
|
if base == 43:
|
||||||
chars = __b43chars
|
chars = __b43chars
|
||||||
long_value = 0
|
long_value = 0
|
||||||
for (i, c) in enumerate(v[::-1]):
|
power_of_base = 1
|
||||||
|
for c in v[::-1]:
|
||||||
digit = chars.find(bytes([c]))
|
digit = chars.find(bytes([c]))
|
||||||
if digit == -1:
|
if digit == -1:
|
||||||
raise ValueError('Forbidden character {} for base {}'.format(c, base))
|
raise ValueError('Forbidden character {} for base {}'.format(c, base))
|
||||||
long_value += digit * (base**i)
|
# naive but slow variant: long_value += digit * (base**i)
|
||||||
|
long_value += digit * power_of_base
|
||||||
|
power_of_base *= base
|
||||||
result = bytearray()
|
result = bytearray()
|
||||||
while long_value >= 256:
|
while long_value >= 256:
|
||||||
div, mod = divmod(long_value, 256)
|
div, mod = divmod(long_value, 256)
|
||||||
|
|
Loading…
Add table
Reference in a new issue