Fixed #23399 -- Optimized django.utils.http.int_to_bas36()

Thanks liminspace for the patch and Keryn Knight for benchmarking.
This commit is contained in:
Tim Graham 2014-09-08 19:31:21 -04:00
parent 5cba975d26
commit 2508be35ca
1 changed files with 8 additions and 16 deletions

View File

@ -189,8 +189,7 @@ def int_to_base36(i):
""" """
Converts an integer to a base36 string Converts an integer to a base36 string
""" """
digits = "0123456789abcdefghijklmnopqrstuvwxyz" char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
factor = 0
if i < 0: if i < 0:
raise ValueError("Negative base36 conversion input.") raise ValueError("Negative base36 conversion input.")
if six.PY2: if six.PY2:
@ -198,20 +197,13 @@ def int_to_base36(i):
raise TypeError("Non-integer base36 conversion input.") raise TypeError("Non-integer base36 conversion input.")
if i > sys.maxint: if i > sys.maxint:
raise ValueError("Base36 conversion input too large.") raise ValueError("Base36 conversion input too large.")
# Find starting factor if i < 36:
while True: return char_set[i]
factor += 1 b36 = ''
if i < 36 ** factor: while i != 0:
factor -= 1 i, n = divmod(i, 36)
break b36 = char_set[n] + b36
base36 = [] return b36
# Construct base36 representation
while factor >= 0:
j = 36 ** factor
base36.append(digits[i // j])
i = i % j
factor -= 1
return ''.join(base36)
def urlsafe_base64_encode(s): def urlsafe_base64_encode(s):