aboutsummaryrefslogtreecommitdiffstats
path: root/servo
diff options
context:
space:
mode:
Diffstat (limited to 'servo')
-rw-r--r--servo/lib/shorturl.py15
1 files changed, 13 insertions, 2 deletions
diff --git a/servo/lib/shorturl.py b/servo/lib/shorturl.py
index f93028f..a78c699 100644
--- a/servo/lib/shorturl.py
+++ b/servo/lib/shorturl.py
@@ -56,42 +56,53 @@ class UrlEncoder(object):
self.alphabet = alphabet
self.block_size = block_size
self.mask = (1 << block_size) - 1
- self.mapping = range(block_size)
+ self.mapping = list(range(block_size))
self.mapping.reverse()
+
def encode_url(self, n, min_length=MIN_LENGTH):
return self.enbase(self.encode(n), min_length)
+
def decode_url(self, n):
return self.decode(self.debase(n))
+
def encode(self, n):
return (n & ~self.mask) | self._encode(n & self.mask)
+
def _encode(self, n):
result = 0
for i, b in enumerate(self.mapping):
if n & (1 << i):
result |= (1 << b)
return result
+
def decode(self, n):
return (n & ~self.mask) | self._decode(n & self.mask)
+
def _decode(self, n):
result = 0
for i, b in enumerate(self.mapping):
if n & (1 << b):
result |= (1 << i)
return result
+
def enbase(self, x, min_length=MIN_LENGTH):
result = self._enbase(x)
padding = self.alphabet[0] * (min_length - len(result))
return '%s%s' % (padding, result)
+
def _enbase(self, x):
+ x = int(x)
n = len(self.alphabet)
if x < n:
return self.alphabet[x]
return self._enbase(x / n) + self.alphabet[x % n]
+
def debase(self, x):
n = len(self.alphabet)
result = 0
for i, c in enumerate(reversed(x)):
result += self.alphabet.index(c) * (n ** i)
+
return result
DEFAULT_ENCODER = UrlEncoder()
@@ -127,4 +138,4 @@ if __name__ == '__main__':
assert a == e
assert b == d
c = (' ' * (7 - len(c))) + c
- print '%6d %12d %s %12d %6d' % (a, b, c, d, e)
+ print ('%6d %12d %s %12d %6d' % (a, b, c, d, e))