diff -r de2a0cb6ba52 Lib/base64.py --- a/Lib/base64.py Fri Jun 22 18:32:07 2012 +0200 +++ b/Lib/base64.py Fri Jun 22 09:51:31 2012 -0700 @@ -40,12 +40,18 @@ else: raise TypeError("argument should be bytes or ASCII string, not %s" % s.__class__.__name__) + +def _translation_table(altchars): + translation = bytearray(range(256)) + for k, v in altchars.items(): + translation[ord(k)] = v[0] + return translation + + def _translate(s, altchars): if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) - translation = bytearray(range(256)) - for k, v in altchars.items(): - translation[ord(k)] = v[0] + translation = _translation_table(altchars) return s.translate(translation) @@ -116,6 +122,10 @@ """ return b64decode(s) + +_urlsafe_encode_translation = _translation_table({'+': b'-', '/': b'_'}) +_urlsafe_decode_translation = _translation_table({'-': b'+', '_': b'/'}) + def urlsafe_b64encode(s): """Encode a byte string using a url-safe Base64 alphabet. @@ -123,7 +133,7 @@ returned. The alphabet uses '-' instead of '+' and '_' instead of '/'. """ - return b64encode(s, b'-_') + return b64encode(s).translate(_urlsafe_encode_translation) def urlsafe_b64decode(s): """Decode a byte string encoded with the standard Base64 alphabet. @@ -135,8 +145,9 @@ The alphabet uses '-' instead of '+' and '_' instead of '/'. """ - return b64decode(s, b'-_') - + s = _bytes_from_decode_data(s) + s = s.translate(_urlsafe_decode_translation) + return b64decode(s) # Base32 encoding/decoding must be done in Python