diff -r 14d1018940cb Lib/base64.py --- a/Lib/base64.py Sat May 30 19:37:19 2015 +0300 +++ b/Lib/base64.py Sat May 30 11:45:43 2015 -0700 @@ -7,6 +7,7 @@ import re import struct +import string import binascii @@ -29,14 +30,6 @@ EMPTYSTRING = '' -def _translate(s, altchars): - translation = _translation[:] - for k, v in altchars.items(): - translation[ord(k)] = v - return s.translate(''.join(translation)) - - - # Base64 encoding/decoding uses binascii def b64encode(s, altchars=None): @@ -52,7 +45,7 @@ # Strip off the trailing newline encoded = binascii.b2a_base64(s)[:-1] if altchars is not None: - return _translate(encoded, {'+': altchars[0], '/': altchars[1]}) + return encoded.translate(string.maketrans(b'+/', altchars[:2])) return encoded @@ -68,7 +61,7 @@ string. """ if altchars is not None: - s = _translate(s, {altchars[0]: '+', altchars[1]: '/'}) + s = s.translate(string.maketrans(altchars[:2], '+/')) try: return binascii.a2b_base64(s) except binascii.Error, msg: @@ -92,13 +85,16 @@ """ return b64decode(s) +_urlsafe_encode_translation = string.maketrans(b'+/', b'-_') +_urlsafe_decode_translation = string.maketrans(b'-_', b'+/') + def urlsafe_b64encode(s): """Encode a string using a url-safe Base64 alphabet. s is the string to encode. The encoded string is returned. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ - return b64encode(s, '-_') + return b64encode(s).translate(_urlsafe_encode_translation) def urlsafe_b64decode(s): """Decode a string encoded with the standard Base64 alphabet. @@ -109,10 +105,9 @@ The alphabet uses '-' instead of '+' and '_' instead of '/'. """ - return b64decode(s, '-_') + return b64decode(s.translate(_urlsafe_decode_translation)) - # Base32 encoding/decoding must be done in Python _b32alphabet = { 0: 'A', 9: 'J', 18: 'S', 27: '3', @@ -200,7 +195,7 @@ # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01: - s = _translate(s, {'0': 'O', '1': map01}) + s = s.translate(string.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad