Skip to content

Commit 49e2421

Browse files
committed
Issue #15138: Speed up base64.urlsafe_b64* considerably (2.7 backport).
1 parent f8a253e commit 49e2421

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

Lib/base64.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import re
99
import struct
10+
import string
1011
import binascii
1112

1213

@@ -52,7 +53,7 @@ def b64encode(s, altchars=None):
5253
# Strip off the trailing newline
5354
encoded = binascii.b2a_base64(s)[:-1]
5455
if altchars is not None:
55-
return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
56+
return encoded.translate(string.maketrans(b'+/', altchars[:2]))
5657
return encoded
5758

5859

@@ -68,7 +69,7 @@ def b64decode(s, altchars=None):
6869
string.
6970
"""
7071
if altchars is not None:
71-
s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
72+
s = s.translate(string.maketrans(altchars[:2], '+/'))
7273
try:
7374
return binascii.a2b_base64(s)
7475
except binascii.Error, msg:
@@ -92,13 +93,16 @@ def standard_b64decode(s):
9293
"""
9394
return b64decode(s)
9495

96+
_urlsafe_encode_translation = string.maketrans(b'+/', b'-_')
97+
_urlsafe_decode_translation = string.maketrans(b'-_', b'+/')
98+
9599
def urlsafe_b64encode(s):
96100
"""Encode a string using a url-safe Base64 alphabet.
97101
98102
s is the string to encode. The encoded string is returned. The alphabet
99103
uses '-' instead of '+' and '_' instead of '/'.
100104
"""
101-
return b64encode(s, '-_')
105+
return b64encode(s).translate(_urlsafe_encode_translation)
102106

103107
def urlsafe_b64decode(s):
104108
"""Decode a string encoded with the standard Base64 alphabet.
@@ -109,7 +113,7 @@ def urlsafe_b64decode(s):
109113
110114
The alphabet uses '-' instead of '+' and '_' instead of '/'.
111115
"""
112-
return b64decode(s, '-_')
116+
return b64decode(s.translate(_urlsafe_decode_translation))
113117

114118

115119

@@ -200,7 +204,7 @@ def b32decode(s, casefold=False, map01=None):
200204
# False, or the character to map the digit 1 (one) to. It should be
201205
# either L (el) or I (eye).
202206
if map01:
203-
s = _translate(s, {'0': 'O', '1': map01})
207+
s = s.translate(string.maketrans(b'01', b'O' + map01))
204208
if casefold:
205209
s = s.upper()
206210
# Strip off pad characters from the right. We need to count the pad

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ Core and Builtins
3434
Library
3535
-------
3636

37+
- Issue #15138: Speed up base64.urlsafe_b64{en,de}code considerably.
38+
3739
- Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
3840
written by Matthieu Gautier.
3941

0 commit comments

Comments
 (0)