1010from importlib import import_module
1111from inspect import currentframe
1212from itertools import chain , product
13- from six import binary_type , string_types , text_type
13+ from six import binary_type , string_types , text_type , BytesIO
1414from string import *
1515from types import FunctionType
1616try : # Python3
2929
3030__all__ = ["add" , "add_map" , "b" , "clear" , "codecs" , "decode" , "encode" , "ensure_str" , "examples" ,
3131 "generate_strings_from_regex" , "get_alphabet_from_mask" , "guess" , "handle_error" , "list_encodings" , "lookup" ,
32- "maketrans" , "re" , "register" , "remove" , "reset" , "s2i" , "search" , "MASKS" , "PY3" ]
32+ "maketrans" , "re" , "register" , "remove" , "reset" , "s2i" , "search" , "BytesIO" , " MASKS" , "PY3" ]
3333CODECS_REGISTRY = None
3434MASKS = {
3535 'a' : printable ,
4747
4848
4949entropy = lambda s : - sum ([p * log (p , 2 ) for p in [float (s .count (c )) / len (s ) for c in set (s )]])
50- is_printable = lambda s : all (c in printable for c in s )
50+ is_printable = lambda s : all (c in printable for c in ensure_str ( s ) )
5151
5252isb = lambda s : isinstance (s , binary_type )
5353iss = lambda s : isinstance (s , string_types )
@@ -92,7 +92,10 @@ def getregentry(encoding):
9292 fenc = fenc (g ) if fenc else fenc
9393 fdec = fdec (g ) if fdec else fdec
9494 except AttributeError :
95- return # this occurs when m is None, meaning no match
95+ # this occurs when m is None or there is an error in fenc(g) or fdec(g), meaning no match
96+ if m is not None :
97+ raise
98+ return
9699 except IndexError :
97100 # this occurs while m is not None, but possibly no capture group that gives at least 1 group index ; in
98101 # this case, if fenc/fdec is a decorated function, execute it with no arg
@@ -510,11 +513,11 @@ def b(s):
510513 """ Non-crashing bytes conversion function. """
511514 if PY3 :
512515 try :
513- return s .encode ("utf-8 " )
516+ return s .encode ("latin-1 " )
514517 except :
515518 pass
516519 try :
517- return s .encode ("latin-1 " )
520+ return s .encode ("utf-8 " )
518521 except :
519522 pass
520523 return s
@@ -539,8 +542,13 @@ def fix_inout_formats(f):
539542 @wraps (f )
540543 def _wrapper (* args , ** kwargs ):
541544 a0 = args [0 ]
542- a0 = ensure_str (a0 ) if iss (a0 ) or isb (a0 ) else a0
545+ a0_isb = isb (a0 )
546+ a0 = ensure_str (a0 ) if iss (a0 ) or a0_isb else a0
543547 r = f (a0 , * args [1 :], ** kwargs )
548+ # special case: input is in bytes ; ensure that the returned length is this of the bytes, not this processed by
549+ # the decode/encode function
550+ if isinstance (r , (tuple , list )) and isinstance (r [1 ], int ) and a0_isb :
551+ r = tuple ([list (r )[0 ]] + [len (args [0 ])] + list (r )[2 :])
544552 return (fix (r [0 ], args [0 ]), ) + r [1 :] if isinstance (r , (tuple , list )) else fix (r , args [0 ])
545553 return _wrapper
546554
0 commit comments