@@ -52,6 +52,25 @@ def _bytes_from_decode_data(s):
5252 raise  TypeError ("argument should be bytes or ASCII string, not %s"  %  s .__class__ .__name__ )
5353
5454
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+ 5574# Base64 encoding/decoding uses binascii 
5675
5776
@@ -73,7 +92,7 @@ def b64encode(s, altchars=None):
7392 if  not  isinstance (altchars , bytes_types ):
7493 raise  TypeError ("expected bytes, not %s"  %  altchars .__class__ .__name__ )
7594 assert  len (altchars ) ==  2 , repr (altchars )
76-  return encoded . translate ( bytes . maketrans (b"+/" , altchars ))
95+  encoded = _translate ( encoded ,  _maketrans (b"+/" , altchars ))
7796 return  encoded 
7897
7998
@@ -95,7 +114,7 @@ def b64decode(s, altchars=None, validate=False):
95114 if  altchars  is  not None :
96115 altchars  =  _bytes_from_decode_data (altchars )
97116 assert  len (altchars ) ==  2 , repr (altchars )
98-  s  =  s . translate ( bytes . maketrans (altchars , b"+/" ))
117+  s  =  _translate ( s ,  _maketrans (altchars , b"+/" ))
99118 if  validate  and  not  re .match (b"^[A-Za-z0-9+/]*=*$" , s ):
100119 raise  binascii .Error ("Non-base64 digit found" )
101120 return  binascii .a2b_base64 (s )
@@ -120,8 +139,8 @@ def standard_b64decode(s):
120139 return  b64decode (s )
121140
122141
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'+/') 
125144
126145
127146def  urlsafe_b64encode (s ):
@@ -132,7 +151,7 @@ def urlsafe_b64encode(s):
132151 '/'. 
133152 """ 
134153 # return b64encode(s).translate(_urlsafe_encode_translation) 
135-  raise NotImplementedError ( )
154+  return b64encode ( s ,  b"-_" ). rstrip ( b" \n " 
136155
137156
138157def  urlsafe_b64decode (s ):
@@ -266,7 +285,7 @@ def b32decode(s, casefold=False, map01=None):
266285 if  map01  is  not None :
267286 map01  =  _bytes_from_decode_data (map01 )
268287 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 ))
270289 if  casefold :
271290 s  =  s .upper ()
272291 # Strip off pad characters from the right. We need to count the pad 
0 commit comments