Skip to content

Commit 90fd7e1

Browse files
committed
Fixed minor bugs in __common__
1 parent 514198a commit 90fd7e1

2 files changed

Lines changed: 24 additions & 7 deletions

File tree

codext/__common__.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from importlib import import_module
1111
from inspect import currentframe
1212
from 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
1414
from string import *
1515
from types import FunctionType
1616
try: # Python3
@@ -29,7 +29,7 @@
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"]
3333
CODECS_REGISTRY = None
3434
MASKS = {
3535
'a': printable,
@@ -47,7 +47,7 @@
4747

4848

4949
entropy = 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

5252
isb = lambda s: isinstance(s, binary_type)
5353
iss = 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

tests/test_common.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ def dummy_decode(input, errors="strict"):
2222
return input, len(input)
2323

2424

25+
def dummy_errored_decode(useless):
26+
raise AttributeError
27+
def decode(input, errors="strict"):
28+
return input, len(input)
29+
return decode
30+
31+
2532
def ensure_str(s, encoding='utf-8', errors='strict'):
2633
""" Similar to six.ensure_str. Adapted here to avoid messing up with six version errors. """
2734
if not PY3 and isinstance(s, text_type):
@@ -49,6 +56,8 @@ def test_add_codec(self):
4956
ci = codext.lookup("dummy")
5057
for k in ["add_to_codecs", "category", "examples", "name", "pattern", "text"]:
5158
self.assertIn(k, ci.parameters.keys())
59+
self.assertIsNone(codext.add("dummy_errored", None, dummy_errored_decode, r"dummy_errored(\d+)$"))
60+
self.assertRaises(AttributeError, codext.lookup, "dummy_errored1")
5261

5362
def test_add_map_codec(self):
5463
ENCMAP = [{'a': "A", 'b': "B", 'c': "C"}, {'d': "D", 'e': "E", 'f': "F"}, {'g': "G", 'h': "H", 'i': "I"}]

0 commit comments

Comments
 (0)