Created
November 21, 2012 19:52
-
-
Save slackorama/4127235 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Base 36 functions: useful for generating compact URLs | |
def decode(s): | |
""" | |
Converts a base 36 string to an ``int``. Raises ``ValueError` if the | |
input won't fit into an int. | |
""" | |
# To prevent overconsumption of server resources, reject any | |
# base36 string that is long than 13 base36 digits (13 digits | |
# is sufficient to base36-encode any 64-bit integer) | |
if len(s) > 13: | |
raise ValueError("Base36 input too large") | |
value = int(s, 36) | |
# ... then do a final check that the value will fit into an int. | |
if value > sys.maxint: | |
raise ValueError("Base36 input too large") | |
return value | |
def encode(i): | |
""" | |
Converts an integer to a base36 string | |
""" | |
digits = "0123456789abcdefghijklmnopqrstuvwxyz" | |
factor = 0 | |
# Find starting factor | |
while True: | |
factor += 1 | |
if i < 36 ** factor: | |
factor -= 1 | |
break | |
base36 = [] | |
# Construct base36 representation | |
while factor >= 0: | |
j = 36 ** factor | |
base36.append(digits[i / j]) | |
i = i % j | |
factor -= 1 | |
return ''.join(base36) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment