-
Notifications
You must be signed in to change notification settings - Fork 0
/
coding.py
49 lines (33 loc) · 865 Bytes
/
coding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""Encoding/decoding stuff."""
import base64
import string
import errors
CHARS = string.digits + string.ascii_letters + "-_"
RADIX = len(CHARS)
def urlenc_int(i):
if i < 0:
raise errors.InternalError("bad int for urlenc %r" % i)
result = ""
while True:
i, r = divmod(i, RADIX)
result = CHARS[r] + result
if i == 0:
return result
def urldec_int(s):
result = 0
while len(s):
result *= RADIX
c = s[0]
result += CHARS.index(c)
s = s[1:]
return result
def b32enc(s):
return base64.b32encode(s).rstrip("=").lower()
def b32dec(s):
s = s + "=" * (len(s) % 8)
return base64.b32decode(s.upper())
def b64enc(s):
return base64.urlsafe_b64encode(s).rstrip("=")
def b64dec(s):
s = s + "=" * (len(s) % 4)
return base64.urlsafe_b64decode(s)