@@ -52,6 +52,25 @@ def _bytes_from_decode_data(s):
52
52
raise TypeError ("argument should be bytes or ASCII string, not %s" % s .__class__ .__name__ )
53
53
54
54
55
+ def _maketrans (f , t ):
56
+ """Re-implement bytes.maketrans() as there is no such function in micropython"""
57
+ if len (f ) != len (t ):
58
+ raise ValueError ("maketrans arguments must have same length" )
59
+ translation_table = dict (zip (f , t ))
60
+ return translation_table
61
+
62
+
63
+ def _translate (input_bytes , trans_table ):
64
+ """Re-implement bytes.translate() as there is no such function in micropython"""
65
+ result = bytearray ()
66
+
67
+ for byte in input_bytes :
68
+ translated_byte = trans_table .get (byte , byte )
69
+ result .append (translated_byte )
70
+
71
+ return bytes (result )
72
+
73
+
55
74
# Base64 encoding/decoding uses binascii
56
75
57
76
@@ -73,7 +92,7 @@ def b64encode(s, altchars=None):
73
92
if not isinstance (altchars , bytes_types ):
74
93
raise TypeError ("expected bytes, not %s" % altchars .__class__ .__name__ )
75
94
assert len (altchars ) == 2 , repr (altchars )
76
- return encoded . translate ( bytes . maketrans (b"+/" , altchars ))
95
+ encoded = _translate ( encoded , _maketrans (b"+/" , altchars ))
77
96
return encoded
78
97
79
98
@@ -95,7 +114,7 @@ def b64decode(s, altchars=None, validate=False):
95
114
if altchars is not None :
96
115
altchars = _bytes_from_decode_data (altchars )
97
116
assert len (altchars ) == 2 , repr (altchars )
98
- s = s . translate ( bytes . maketrans (altchars , b"+/" ))
117
+ s = _translate ( s , _maketrans (altchars , b"+/" ))
99
118
if validate and not re .match (b"^[A-Za-z0-9+/]*=*$" , s ):
100
119
raise binascii .Error ("Non-base64 digit found" )
101
120
return binascii .a2b_base64 (s )
@@ -120,8 +139,8 @@ def standard_b64decode(s):
120
139
return b64decode (s )
121
140
122
141
123
- # _urlsafe_encode_translation = bytes.maketrans (b'+/', b'-_')
124
- # _urlsafe_decode_translation = bytes.maketrans (b'-_', b'+/')
142
+ # _urlsafe_encode_translation = _maketrans (b'+/', b'-_')
143
+ # _urlsafe_decode_translation = _maketrans (b'-_', b'+/')
125
144
126
145
127
146
def urlsafe_b64encode (s ):
@@ -132,7 +151,7 @@ def urlsafe_b64encode(s):
132
151
'/'.
133
152
"""
134
153
# return b64encode(s).translate(_urlsafe_encode_translation)
135
- raise NotImplementedError ( )
154
+ return b64encode ( s , b"-_" ). rstrip ( b" \n " )
136
155
137
156
138
157
def urlsafe_b64decode (s ):
@@ -266,7 +285,7 @@ def b32decode(s, casefold=False, map01=None):
266
285
if map01 is not None :
267
286
map01 = _bytes_from_decode_data (map01 )
268
287
assert len (map01 ) == 1 , repr (map01 )
269
- s = s . translate ( bytes . maketrans (b"01" , b"O" + map01 ))
288
+ s = _translate ( s , _maketrans (b"01" , b"O" + map01 ))
270
289
if casefold :
271
290
s = s .upper ()
272
291
# Strip off pad characters from the right. We need to count the pad
0 commit comments